@hydra-acp/cli 0.1.192 → 0.1.193
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 +66 -66
- package/dist/daemon.js +14 -14
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
var lO=Object.defineProperty;var q=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ji=(n,e)=>{for(var t in e)lO(n,t,{get:e[t],enumerable:!0})};import*as Ee from"path";import*as ty from"os";function V(n){let e=ty.homedir();if(!e)return n;let t=o=>process.platform==="win32"?o.replace(/\\/g,"/").toLowerCase():o,r=t(e),s=t(n);return s===r?"~":s.startsWith(r+"/")?"~"+n.slice(e.length):n}function ny(n,e){let t=r=>process.platform==="win32"?Ee.resolve(r).toLowerCase():Ee.resolve(r);return t(n)===t(e)}function mO(){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 gO(n,e){KS||Ee.isAbsolute(n)||(KS=!0,process.stderr.write(`hydra-acp: ${GS} is relative (${JSON.stringify(n)}); resolved against the current directory to ${e}. Processes started from elsewhere will use a different home and will not see each other's daemon. Set an absolute path.
|
|
3
3
|
`))}function Le(){let n=process.env[GS];if(n&&n.length>0){let t=Ee.resolve(n);return gO(n,t),t}let e=mO();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 Ee.join(ty.homedir(),".hydra-acp")}var GS,KS,D,ke=q(()=>{"use strict";GS="HYDRA_ACP_HOME";KS=!1;D={home:Le,config:()=>Ee.join(Le(),"config.json"),authToken:()=>Ee.join(Le(),"auth-token"),remotes:()=>Ee.join(Le(),"remotes.json"),peers:()=>Ee.join(Le(),"peers.json"),pidFile:()=>Ee.join(Le(),"daemon.pid"),logFile:()=>Ee.join(Le(),"daemon.log"),daemonBootLog:()=>Ee.join(Le(),"daemon-boot.log"),currentLogFile:()=>Ee.join(Le(),"current.log"),registryCache:()=>Ee.join(Le(),"registry.json"),themesDir:()=>Ee.join(Le(),"themes"),ttySessionDir:()=>Ee.join(Le(),"tty"),ttySessionFile:n=>Ee.join(Le(),"tty",n),agentsDir:()=>Ee.join(Le(),"agents"),agentLogFile:n=>Ee.join(Le(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>Ee.join(Le(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>Ee.join(Le(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>Ee.join(Le(),"sessions"),sessionDir:n=>Ee.join(Le(),"sessions",n),sessionFile:n=>Ee.join(Le(),"sessions",n,"meta.json"),historyFile:n=>Ee.join(Le(),"sessions",n,"history.jsonl"),historyArchiveFile:(n,e)=>Ee.join(Le(),"sessions",n,`history.jsonl.${e}`),toolsDir:n=>Ee.join(Le(),"sessions",n,"tools"),toolBlobFile:(n,e)=>Ee.join(Le(),"sessions",n,"tools",e),queueFile:n=>Ee.join(Le(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>Ee.join(Le(),"sessions",".tombstones"),tombstoneAgentDir:n=>Ee.join(Le(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>Ee.join(Le(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>Ee.join(Le(),"extensions"),extensionLogDir:n=>Ee.join(Le(),"extensions",n),extensionLogFile:n=>Ee.join(Le(),"extensions",n,"current.log"),extensionPidFile:n=>Ee.join(Le(),"extensions",n,"extension.pid"),transformersDir:()=>Ee.join(Le(),"transformers"),transformerLogDir:n=>Ee.join(Le(),"transformers",n),transformerLogFile:n=>Ee.join(Le(),"transformers",n,"current.log"),transformerPidFile:n=>Ee.join(Le(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>Ee.join(Le(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>Ee.join(Le(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>Ee.join(Le(),"prompt-history"),tuiLogFile:()=>Ee.join(Le(),"tui.log"),shimWireLogFile:()=>Ee.join(Le(),"shim-wire.log")}});import*as Pd from"fs/promises";function Md(){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 _d(){try{let e=(await Pd.readFile(D.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Vi(){let n=await _d();if(!n)throw new Error(`No service token found at ${D.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Yi(n){await Pd.mkdir(D.home(),{recursive:!0}),await Pd.writeFile(D.authToken(),n+`
|
|
4
4
|
`,{encoding:"utf8",mode:384})}async function Il(){let n=await _d();if(n)return n;let e=Md();return await Yi(e),process.stderr.write(`hydra-acp: initialized ${D.authToken()} with a fresh service token.
|
|
5
|
-
`),e}var
|
|
6
|
-
`;await vO(n,s,t)}async function kO(n,e,t={}){let r=t.rename??Rn.rename,s=t.platform??process.platform,o=t.sleep??(i=>new Promise(a=>setTimeout(a,i)));for(let i=0;;i++)try{await r(n,e);return}catch(a){let d=a.code??"";if(!(s==="win32"&&wO.has(d)&&i<bO-1))throw a;await o(10*(i+1))}}async function vO(n,e,t={}){let r=await SO(n),s=br.dirname(r);await Rn.mkdir(s,{recursive:!0});let o=`${r}.tmp-${process.pid}-${xO()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await Rn.writeFile(o,e,i),await kO(o,r)}catch(i){throw await Rn.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{JS.chmodSync(r,t.mode)}catch{}}async function SO(n){let e;try{e=await Rn.lstat(n)}catch(s){if(s.code==="ENOENT")return n;throw s}if(!e.isSymbolicLink())return n;let t=await Rn.readlink(n),r=br.isAbsolute(t)?t:br.resolve(br.dirname(n),t);try{let s=await Rn.realpath(br.dirname(r));return br.join(s,br.basename(r))}catch(s){if(s.code==="ENOENT")return r;throw s}}async function jt(n){let e;try{e=await Rn.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 xO(){return yO(4).toString("hex")}var wO,bO,es=q(()=>{"use strict";wO=new Set(["EPERM","EACCES","EBUSY"]),bO=10});function ry(n){return VS[n]??{reload:"restart",overlay:"inert"}}function sy(n){return IO[n]??{reload:"restart",overlay:"inert"}}function oy(){let n=[];for(let[e,t]of Object.entries(VS))t.overlay!=="effective"&&n.push({key:e,effect:t.overlay,note:t.overlayNote??Lt});return n}var Lt,VS,IO,iy=q(()=>{"use strict";Lt="read by the daemon, which loads config.json at startup",VS={daemon:{reload:"restart",overlay:"partial",overlayNote:"only changes which daemon this client dials; a daemon started from here still binds config.json's host/port. Use `home` for a separate daemon",nested:!0},agents:{reload:"live",overlay:"inert",overlayNote:Lt},agentOverrides:{reload:"live",overlay:"inert",overlayNote:Lt},registry:{reload:"live",overlay:"inert",overlayNote:Lt},npmRegistry:{reload:"live",overlay:"inert",overlayNote:Lt},defaultAgent:{reload:"live",overlay:"effective"},defaultCwd:{reload:"live",overlay:"effective"},sessionDefaults:{reload:"live",overlay:"partial",overlayNote:"applies to WS session/new and child_session/spawn; POST /v1/sessions has no model/mode/effort field to apply any of it to"},synopsisAgent:{reload:"warn",overlay:"inert",overlayNote:Lt},synopsisModel:{reload:"warn",overlay:"inert",overlayNote:Lt},compaction:{reload:"warn",overlay:"inert",overlayNote:Lt},defaultTransformers:{reload:"warn",overlay:"inert",overlayNote:Lt},disableWorkspaceSnapshots:{reload:"warn",overlay:"inert",overlayNote:Lt},compressToolContent:{reload:"warn",overlay:"inert",overlayNote:Lt},extensions:{reload:"warn",overlay:"inert",overlayNote:Lt},transformers:{reload:"warn",overlay:"inert",overlayNote:Lt},tui:{reload:"client",overlay:"effective"},sessionListColdLimit:{reload:"client",overlay:"effective"}},IO={host:{reload:"restart",overlay:"inert"},port:{reload:"restart",overlay:"inert"},publicHost:{reload:"restart",overlay:"inert"},tls:{reload:"restart",overlay:"inert"},scrubEnv:{reload:"live",overlay:"inert",overlayNote:Lt},logLevel:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionIdleTimeoutSeconds:{reload:"warn",overlay:"inert",overlayNote:Lt},nonInteractiveOrphanTimeoutSeconds:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionHistoryMaxEntries:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionHistoryArchiveMaxBytes:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionHistoryArchiveTiers:{reload:"warn",overlay:"inert",overlayNote:Lt},agentStderrTailBytes:{reload:"warn",overlay:"inert",overlayNote:Lt},agentSyncIntervalMinutes:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionGcIntervalMinutes:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionGcMaxAgeDays:{reload:"warn",overlay:"inert",overlayNote:Lt}}});var tx={};Ji(tx,{DAEMON_OWNED_KEYS:()=>RO,DIRECTORY_CONFIG_FILENAME:()=>QS,HOME_KEY:()=>Rl,applyDirectoryConfig:()=>TO,currentDirectoryOverlay:()=>cy,deepMergeConfig:()=>Al,directoryConfigNotices:()=>ZS,findDirectoryConfigs:()=>XS,formatDirectoryConfigNotices:()=>EO,nestedStringMapField:()=>Vf,resolveDirectoryConfig:()=>Tl,resolveDirectorySessionDefaults:()=>$d,setDirectoryOverlay:()=>dy,stringField:()=>Jf,stringMapField:()=>PO});import*as YS from"fs/promises";import*as Cl from"os";import*as As from"path";function AO(n){return n==="~"?Cl.homedir():n.startsWith("~/")?As.join(Cl.homedir(),n.slice(2)):n.startsWith("$HOME/")?As.join(Cl.homedir(),n.slice(6)):n}function ay(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Al(n,e){let t={...n};for(let[r,s]of Object.entries(e)){let o=t[r];t[r]=ay(o)&&ay(s)?Al(o,s):s}return t}async function XS(n,e=Cl.homedir()){let t=[],r=[],s=As.resolve(e),o=As.resolve(n);for(let i=0;i<CO;i+=1){let a=As.join(o,QS),d;try{d=await YS.readFile(a,"utf8")}catch{d=void 0}if(d!==void 0)try{let l=JSON.parse(d);ay(l)?t.push({file:a,data:l}):r.push({file:a,key:"",message:"expected a JSON object; ignoring this file"})}catch(l){r.push({file:a,key:"",message:`is not valid JSON (${l.message}); ignoring this file`})}if(o===s)break;let c=As.dirname(o);if(c===o)break;o=c}return t.reverse(),{layers:t,notices:r}}function ZS(n){let e=new Map(oy().map(r=>[r.key,r])),t=[];for(let r of n)for(let s of Object.keys(r.data)){let o=e.get(s);if(!o)continue;let i=o.effect==="partial"?`\`${s}\` ${o.note}`:`\`${s}\` is ${o.note}, so it has no effect in a directory config`;t.push({file:r.file,key:s,message:i})}return t}function cy(){return ex}function dy(n){ex=n}async function TO(n=process.cwd()){let{layers:e,notices:t,merged:r,homeRequest:s}=await Tl(n);if(e.length===0)return dy(void 0),{layers:e,notices:t};let o;if(s!==void 0){let i=process.env.HYDRA_ACP_HOME;i&&i.length>0?t.push({file:e[e.length-1].file,key:Rl,message:`\`home\` ignored: HYDRA_ACP_HOME is already set to ${i}`}):(o=s,process.env.HYDRA_ACP_HOME=o)}return dy(Object.keys(r).length>0?r:void 0),{layers:e,notices:t,...o!==void 0?{home:o}:{}}}async function Tl(n=process.cwd()){let{layers:e,notices:t}=await XS(n);t.push(...ZS(e));let r={};for(let i of e)r=Al(r,i.data);let s,o=r[Rl];return typeof o=="string"&&o.length>0?s=As.resolve(AO(o)):o!==void 0&&t.push({file:e[e.length-1].file,key:Rl,message:"`home` must be a non-empty string; ignoring it"}),delete r[Rl],{layers:e,notices:t,merged:r,...s!==void 0?{homeRequest:s}:{}}}function EO(n){return n.map(e=>`hydra-acp: ${e.file}: ${e.message}`)}function Jf(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function PO(n,e){let t=n[e];if(t===null||typeof t!="object"||Array.isArray(t))return;let r={};for(let[s,o]of Object.entries(t))typeof o=="string"&&(r[s]=o);return Object.keys(r).length>0?r:void 0}function Vf(n,e){let t=n[e];if(t===null||typeof t!="object"||Array.isArray(t))return;let r={};for(let[s,o]of Object.entries(t)){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i={};for(let[a,d]of Object.entries(o))typeof d=="string"&&(i[a]=d);Object.keys(i).length>0&&(r[s]=i)}return Object.keys(r).length>0?r:void 0}async function $d(n){let e={};try{e=(await Tl(n)).merged}catch{return{}}let t=Jf(e,"defaultAgent"),r=Vf(e,"sessionDefaults");return{...t!==void 0?{agentId:t}:{},...r!==void 0?{configDefaults:r}:{}}}var QS,Rl,CO,RO,ex,Od=q(()=>{"use strict";iy();QS=".hydra-acp.json",Rl="home",CO=64,RO=oy().map(n=>n.key)});var wy={};Ji(wy,{DEFAULT_COMPOSER_BOTTOM_LEFT:()=>Fd,DEFAULT_COMPOSER_BOTTOM_RIGHT:()=>Ld,DEFAULT_COMPOSER_TOP_LEFT:()=>Qi,DEFAULT_COMPOSER_TOP_RIGHT:()=>Xi,DEFAULT_DAEMON_PORT:()=>An,DEFAULT_SESSIONBAR_LEFT:()=>Nd,DEFAULT_SESSIONBAR_RIGHT:()=>Dd,HydraConfig:()=>Bd,defaultConfig:()=>zO,expandHome:()=>mt,extensionList:()=>fy,hasConfiguredDefaultAgent:()=>yy,loadConfig:()=>He,loadGlobalConfig:()=>
|
|
5
|
+
`),e}var go=q(()=>{"use strict";ke()});import*as Rn from"fs/promises";import*as JS from"fs";import*as br from"path";import{randomBytes as yO}from"crypto";async function nn(n,e,t={}){let s=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
|
|
6
|
+
`;await vO(n,s,t)}async function kO(n,e,t={}){let r=t.rename??Rn.rename,s=t.platform??process.platform,o=t.sleep??(i=>new Promise(a=>setTimeout(a,i)));for(let i=0;;i++)try{await r(n,e);return}catch(a){let d=a.code??"";if(!(s==="win32"&&wO.has(d)&&i<bO-1))throw a;await o(10*(i+1))}}async function vO(n,e,t={}){let r=await SO(n),s=br.dirname(r);await Rn.mkdir(s,{recursive:!0});let o=`${r}.tmp-${process.pid}-${xO()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await Rn.writeFile(o,e,i),await kO(o,r)}catch(i){throw await Rn.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{JS.chmodSync(r,t.mode)}catch{}}async function SO(n){let e;try{e=await Rn.lstat(n)}catch(s){if(s.code==="ENOENT")return n;throw s}if(!e.isSymbolicLink())return n;let t=await Rn.readlink(n),r=br.isAbsolute(t)?t:br.resolve(br.dirname(n),t);try{let s=await Rn.realpath(br.dirname(r));return br.join(s,br.basename(r))}catch(s){if(s.code==="ENOENT")return r;throw s}}async function jt(n){let e;try{e=await Rn.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 xO(){return yO(4).toString("hex")}var wO,bO,es=q(()=>{"use strict";wO=new Set(["EPERM","EACCES","EBUSY"]),bO=10});function ry(n){return VS[n]??{reload:"restart",overlay:"inert"}}function sy(n){return IO[n]??{reload:"restart",overlay:"inert"}}function oy(){let n=[];for(let[e,t]of Object.entries(VS))t.overlay!=="effective"&&n.push({key:e,effect:t.overlay,note:t.overlayNote??Lt});return n}var Lt,VS,IO,iy=q(()=>{"use strict";Lt="read by the daemon, which loads config.json at startup",VS={daemon:{reload:"restart",overlay:"partial",overlayNote:"only changes which daemon this client dials; a daemon started from here still binds config.json's host/port. Use `home` for a separate daemon",nested:!0},agents:{reload:"live",overlay:"inert",overlayNote:Lt},agentOverrides:{reload:"live",overlay:"inert",overlayNote:Lt},registry:{reload:"live",overlay:"inert",overlayNote:Lt},npmRegistry:{reload:"live",overlay:"inert",overlayNote:Lt},defaultAgent:{reload:"live",overlay:"effective"},defaultCwd:{reload:"live",overlay:"effective"},sessionDefaults:{reload:"live",overlay:"partial",overlayNote:"applies to WS session/new and child_session/spawn; POST /v1/sessions has no model/mode/effort field to apply any of it to"},synopsisAgent:{reload:"warn",overlay:"inert",overlayNote:Lt},synopsisModel:{reload:"warn",overlay:"inert",overlayNote:Lt},compaction:{reload:"warn",overlay:"inert",overlayNote:Lt},defaultTransformers:{reload:"warn",overlay:"inert",overlayNote:Lt},disableWorkspaceSnapshots:{reload:"warn",overlay:"inert",overlayNote:Lt},compressToolContent:{reload:"warn",overlay:"inert",overlayNote:Lt},extensions:{reload:"warn",overlay:"inert",overlayNote:Lt},transformers:{reload:"warn",overlay:"inert",overlayNote:Lt},tui:{reload:"client",overlay:"effective"},sessionListColdLimit:{reload:"client",overlay:"effective"}},IO={host:{reload:"restart",overlay:"inert"},port:{reload:"restart",overlay:"inert"},publicHost:{reload:"restart",overlay:"inert"},tls:{reload:"restart",overlay:"inert"},scrubEnv:{reload:"live",overlay:"inert",overlayNote:Lt},logLevel:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionIdleTimeoutSeconds:{reload:"warn",overlay:"inert",overlayNote:Lt},nonInteractiveOrphanTimeoutSeconds:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionHistoryMaxEntries:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionHistoryArchiveMaxBytes:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionHistoryArchiveTiers:{reload:"warn",overlay:"inert",overlayNote:Lt},agentStderrTailBytes:{reload:"warn",overlay:"inert",overlayNote:Lt},agentSyncIntervalMinutes:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionGcIntervalMinutes:{reload:"warn",overlay:"inert",overlayNote:Lt},sessionGcMaxAgeDays:{reload:"warn",overlay:"inert",overlayNote:Lt}}});var tx={};Ji(tx,{DAEMON_OWNED_KEYS:()=>RO,DIRECTORY_CONFIG_FILENAME:()=>QS,HOME_KEY:()=>Rl,applyDirectoryConfig:()=>TO,currentDirectoryOverlay:()=>cy,deepMergeConfig:()=>Al,directoryConfigNotices:()=>ZS,findDirectoryConfigs:()=>XS,formatDirectoryConfigNotices:()=>EO,nestedStringMapField:()=>Vf,resolveDirectoryConfig:()=>Tl,resolveDirectorySessionDefaults:()=>$d,setDirectoryOverlay:()=>dy,stringField:()=>Jf,stringMapField:()=>PO});import*as YS from"fs/promises";import*as Cl from"os";import*as As from"path";function AO(n){return n==="~"?Cl.homedir():n.startsWith("~/")?As.join(Cl.homedir(),n.slice(2)):n.startsWith("$HOME/")?As.join(Cl.homedir(),n.slice(6)):n}function ay(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Al(n,e){let t={...n};for(let[r,s]of Object.entries(e)){let o=t[r];t[r]=ay(o)&&ay(s)?Al(o,s):s}return t}async function XS(n,e=Cl.homedir()){let t=[],r=[],s=As.resolve(e),o=As.resolve(n);for(let i=0;i<CO;i+=1){let a=As.join(o,QS),d;try{d=await YS.readFile(a,"utf8")}catch{d=void 0}if(d!==void 0)try{let l=JSON.parse(d);ay(l)?t.push({file:a,data:l}):r.push({file:a,key:"",message:"expected a JSON object; ignoring this file"})}catch(l){r.push({file:a,key:"",message:`is not valid JSON (${l.message}); ignoring this file`})}if(o===s)break;let c=As.dirname(o);if(c===o)break;o=c}return t.reverse(),{layers:t,notices:r}}function ZS(n){let e=new Map(oy().map(r=>[r.key,r])),t=[];for(let r of n)for(let s of Object.keys(r.data)){let o=e.get(s);if(!o)continue;let i=o.effect==="partial"?`\`${s}\` ${o.note}`:`\`${s}\` is ${o.note}, so it has no effect in a directory config`;t.push({file:r.file,key:s,message:i})}return t}function cy(){return ex}function dy(n){ex=n}async function TO(n=process.cwd()){let{layers:e,notices:t,merged:r,homeRequest:s}=await Tl(n);if(e.length===0)return dy(void 0),{layers:e,notices:t};let o;if(s!==void 0){let i=process.env.HYDRA_ACP_HOME;i&&i.length>0?t.push({file:e[e.length-1].file,key:Rl,message:`\`home\` ignored: HYDRA_ACP_HOME is already set to ${i}`}):(o=s,process.env.HYDRA_ACP_HOME=o)}return dy(Object.keys(r).length>0?r:void 0),{layers:e,notices:t,...o!==void 0?{home:o}:{}}}async function Tl(n=process.cwd()){let{layers:e,notices:t}=await XS(n);t.push(...ZS(e));let r={};for(let i of e)r=Al(r,i.data);let s,o=r[Rl];return typeof o=="string"&&o.length>0?s=As.resolve(AO(o)):o!==void 0&&t.push({file:e[e.length-1].file,key:Rl,message:"`home` must be a non-empty string; ignoring it"}),delete r[Rl],{layers:e,notices:t,merged:r,...s!==void 0?{homeRequest:s}:{}}}function EO(n){return n.map(e=>`hydra-acp: ${e.file}: ${e.message}`)}function Jf(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function PO(n,e){let t=n[e];if(t===null||typeof t!="object"||Array.isArray(t))return;let r={};for(let[s,o]of Object.entries(t))typeof o=="string"&&(r[s]=o);return Object.keys(r).length>0?r:void 0}function Vf(n,e){let t=n[e];if(t===null||typeof t!="object"||Array.isArray(t))return;let r={};for(let[s,o]of Object.entries(t)){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i={};for(let[a,d]of Object.entries(o))typeof d=="string"&&(i[a]=d);Object.keys(i).length>0&&(r[s]=i)}return Object.keys(r).length>0?r:void 0}async function $d(n){let e={};try{e=(await Tl(n)).merged}catch{return{}}let t=Jf(e,"defaultAgent"),r=Vf(e,"sessionDefaults");return{...t!==void 0?{agentId:t}:{},...r!==void 0?{configDefaults:r}:{}}}var QS,Rl,CO,RO,ex,Od=q(()=>{"use strict";iy();QS=".hydra-acp.json",Rl="home",CO=64,RO=oy().map(n=>n.key)});var wy={};Ji(wy,{DEFAULT_COMPOSER_BOTTOM_LEFT:()=>Fd,DEFAULT_COMPOSER_BOTTOM_RIGHT:()=>Ld,DEFAULT_COMPOSER_TOP_LEFT:()=>Qi,DEFAULT_COMPOSER_TOP_RIGHT:()=>Xi,DEFAULT_DAEMON_PORT:()=>An,DEFAULT_SESSIONBAR_LEFT:()=>Nd,DEFAULT_SESSIONBAR_RIGHT:()=>Dd,HydraConfig:()=>Bd,defaultConfig:()=>zO,expandHome:()=>mt,extensionList:()=>fy,hasConfiguredDefaultAgent:()=>yy,loadConfig:()=>He,loadGlobalConfig:()=>yo,migrateLegacyAuthToken:()=>Ud,migrateLegacyDefaultModels:()=>Yf,resolveInAppSelection:()=>El,setAgentOverride:()=>my,setDefaultAgent:()=>Jo,setLocalAgent:()=>Qf,setRegistryPinned:()=>gy,setSessionDefaultForAgent:()=>Pl,setTuiConfigValue:()=>Zi,setTuiSidebarEnabled:()=>hy,transformerList:()=>py,updateRawConfig:()=>ts,writeConfig:()=>qO});import*as Go from"fs/promises";import{homedir as ly}from"os";import{z as j}from"zod";function uy(n,e){return j.object({left:nx.default(n),right:nx.default(e)}).default({})}function El(n){return n.tui.inAppSelection??n.tui.mouse}function fy(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function py(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Hd(){return await jO(),await jt(D.config())??{}}async function jO(){let n;try{n=await Go.lstat(D.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Go.stat(D.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Go.readlink(D.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${D.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 Ud(){let n=await Hd(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let r=!1;try{await Go.access(D.authToken()),r=!0}catch(s){if(s.code!=="ENOENT")throw s}if(r)throw new Error(`Auth token present in both ${D.authToken()} and ${D.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Yi(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await nn(D.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${D.config()} to ${D.authToken()}.
|
|
7
7
|
`)}async function Yf(){let n=await Hd(),e=n.defaultModels&&typeof n.defaultModels=="object"&&!Array.isArray(n.defaultModels)?n.defaultModels:void 0;if(!e)return;let t=n.sessionDefaults&&typeof n.sessionDefaults=="object"&&!Array.isArray(n.sessionDefaults)?n.sessionDefaults:{};for(let[r,s]of Object.entries(e)){if(typeof s!="string")continue;let o=t[r]&&typeof t[r]=="object"&&!Array.isArray(t[r])?t[r]:{};o.model===void 0&&(o.model=s),t[r]=o}n.sessionDefaults=t,delete n.defaultModels,await nn(D.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated defaultModels to sessionDefaults in ${D.config()}.
|
|
8
|
-
`)}async function go(){return await Ud(),await Yf(),Bd.parse(await Hd())}async function He(){await Ud(),await Yf();let n=await Hd(),e=cy();return Bd.parse(e?Al(n,e):n)}async function qO(n){await nn(D.config(),n,{mode:384})}async function ts(n){await Ud(),await Yf();let e=await Hd();n(e),Bd.parse(e),await nn(D.config(),e,{mode:384})}async function Zi(n,e){await ts(t=>{let r=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};r[n]=e,t.tui=r})}async function hy(n){await ts(e=>{let t=e.tui&&typeof e.tui=="object"&&!Array.isArray(e.tui)?e.tui:{},r=t.sidebar&&typeof t.sidebar=="object"&&!Array.isArray(t.sidebar)?t.sidebar:{};r.enabled=n,t.sidebar=r,e.tui=t})}async function Jo(n){await ts(e=>{e.defaultAgent=n})}async function Pl(n,e,t){await ts(r=>{let s=r.sessionDefaults&&typeof r.sessionDefaults=="object"?r.sessionDefaults:{},o=s[n]&&typeof s[n]=="object"?s[n]:{};o[e]=t,s[n]=o,r.sessionDefaults=s})}async function my(n,e){await ts(t=>{let r=t.agentOverrides&&typeof t.agentOverrides=="object"?t.agentOverrides:{},s=r[n]&&typeof r[n]=="object"?r[n]:{};e===void 0?delete s.packageSpec:s.packageSpec=e,Object.keys(s).length===0?delete r[n]:r[n]=s,t.agentOverrides=r})}async function Qf(n,e){await ts(t=>{let r=t.agents&&typeof t.agents=="object"?t.agents:{};e===void 0?delete r[n]:r[n]=e,t.agents=r})}async function gy(n){await ts(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function yy(){let n=await Hd();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function zO(){return Bd.parse({})}function mt(n){return n==="~"||n==="$HOME"?ly():n.startsWith("~/")?ly()+n.slice(1):n.startsWith("$HOME/")?ly()+n.slice(5):n}var sx,MO,An,_O,$O,OO,FO,LO,NO,DO,BO,nx,Qi,Xi,Fd,Ld,Nd,Dd,HO,rx,UO,WO,Bd,rt=q(()=>{"use strict";ke();mo();es();Od();sx="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",MO=j.object({cert:j.string(),key:j.string()}),An=55514,_O=j.object({host:j.string().default("127.0.0.1"),port:j.number().int().positive().default(An),logLevel:j.enum(["debug","info","warn","error"]).default("info"),tls:MO.optional(),sessionIdleTimeoutSeconds:j.number().int().nonnegative().default(3600),nonInteractiveOrphanTimeoutSeconds:j.number().int().nonnegative().default(180),sessionHistoryMaxEntries:j.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:j.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:j.number().int().positive().default(10),agentStderrTailBytes:j.number().int().positive().default(4096),publicHost:j.string().optional(),agentSyncIntervalMinutes:j.number().nonnegative().default(60),scrubEnv:j.array(j.string()).default([]),sessionGcIntervalMinutes:j.number().nonnegative().default(60),sessionGcMaxAgeDays:j.number().positive().default(2)}),$O=j.object({url:j.string().url().default(sx),ttlHours:j.number().positive().default(24),pinned:j.boolean().default(!1)}),OO=j.object({extends:j.string().optional(),name:j.string().optional(),description:j.string().optional(),command:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),FO=j.object({packageSpec:j.string().optional(),extraArgs:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),LO=j.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-x-ctrl-e","ctrl-y","ctrl-underscore","alt-underscore","escape"]),NO=j.union([j.string(),j.object({field:j.string().optional(),text:j.string().optional(),script:j.string().optional(),refreshMs:j.number().int().positive().optional(),maxWidth:j.number().int().positive().optional(),minWidth:j.number().int().nonnegative().optional(),truncate:j.boolean().optional(),priority:j.number().optional(),prefix:j.string().optional(),suffix:j.string().optional(),separator:j.string().optional(),style:j.string().optional(),onClick:j.string().optional(),onDoubleClick:j.string().optional()}).strict()]),DO=j.object({id:j.string().min(1),script:j.string().min(1),refreshMs:j.number().int().positive().optional(),title:j.string().optional(),cap:j.number().int().positive().optional()}).strict(),BO=j.union([j.string(),DO]),nx=j.array(NO);Qi=["status",{field:"elapsed",separator:" "},"sessionId","queued","scroll"],Xi=["usage"],Fd=[],Ld=["helpHint"],Nd=["cwd","title"],Dd=["agentModel"],HO=j.object({composer:j.object({top:uy(Qi,Xi),bottom:uy(Fd,Ld),hintTurns:j.number().int().nonnegative().nullable().default(3)}).default({}),sessionbar:uy(Nd,Dd),scriptRefreshMs:j.number().int().positive().default(5e3),repaintThrottleMs:j.number().int().nonnegative().default(1e3),maxScrollbackLines:j.number().int().positive().default(1e4),mouse:j.boolean().default(!0),inAppSelection:j.boolean().optional(),selectionClipboard:j.enum(["primary","clipboard","both"]).default("both"),openFileCommand:j.union([j.string(),j.array(j.string())]).optional(),openFileInTerminal:j.boolean().optional(),logMaxBytes:j.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:j.number().int().positive().default(32),progressIndicator:j.boolean().default(!0),terminalHost:j.union([j.boolean(),j.enum(["auto","paseo","herdr","tmux"])]).default(!0),launcherModeWhenHosted:j.boolean().default(!1),skipPermissions:j.boolean().default(!1),defaultEnterAction:j.enum(["enqueue","amend"]).default("amend"),showThoughts:j.boolean().default(!0),ambiguousWidth:j.enum(["auto","narrow","wide"]).default("auto"),toolContent:j.enum(["inline","references"]).default("references"),diffContextLines:j.number().int().min(0).default(3),promptHistoryMaxEntries:j.number().int().positive().default(2e3),maxToolItems:j.number().int().nonnegative().default(5),maxPlanItems:j.number().int().nonnegative().default(5),sidebar:j.object({enabled:j.boolean().default(!0),width:j.number().int().positive().optional(),border:j.enum(["none","rule","frame"]).default("frame"),gadgets:j.array(BO).default(["activity","sessions","tasks","context","queue","todo","files","git","resources","info","tools"])}).default({}),showFileUpdates:j.enum(["none","edit","diff"]).default("edit"),sessionColumns:j.array(j.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),defaultHost:j.string().min(1).default("remote:all"),hotkeys:j.record(LO,j.object({command:j.union([j.string(),j.array(j.string())])})).default({}),theme:j.union([j.string(),j.record(j.string(),j.unknown())]).optional(),themeBackground:j.string().optional()}),rx=j.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),UO=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),WO=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),Bd=j.object({daemon:_O.default({}),registry:$O.default({url:sx,ttlHours:24,pinned:!1}),agents:j.record(j.string(),OO).default({}),agentOverrides:j.record(j.string(),FO).default({}),defaultAgent:j.string().default("opencode"),sessionDefaults:j.record(j.string(),j.record(j.string(),j.string())).default({}),synopsisAgent:j.string().optional(),synopsisModel:j.string().optional(),compaction:j.object({agent:j.string().optional(),model:j.string().optional(),tailK:j.number().int().nonnegative().default(20),maxIterations:j.number().int().positive().default(3),contextFraction:j.number().min(0).max(1).default(.5),hardCeilingFraction:j.number().min(0).max(1).default(.85),absoluteFallback:j.number().int().positive().default(2e5),idleBeforePromptMs:j.number().int().nonnegative().default(3e5),modelContextWindows:j.record(j.string(),j.number().int().positive()).default({})}).default({}),defaultCwd:j.string().default("~"),disableWorkspaceSnapshots:j.boolean().optional(),compressToolContent:j.boolean().default(!0),sessionListColdLimit:j.number().int().nonnegative().default(20),extensions:j.record(rx,UO).default({}),transformers:j.record(rx,WO).default({}),defaultTransformers:j.array(j.string()).default([]),npmRegistry:j.string().url().optional(),tui:HO.default({})})});function Vt(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function by(n){return{httpScheme:"https",wsScheme:"wss"}}function Ml(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 ${Xf(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Xf(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 r=KO(`http://${e}`);if(!r)throw new Error(`invalid hydra:// URL: ${Xf(n)}`);let s=r.hostname;if(!s)throw new Error(`hydra:// URL is missing a host: ${Xf(n)}`);let o=Vt(s),i;if(r.port){let c=Number(r.port);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${r.port}`);i=c}else i=An;let a=r.pathname.replace(/^\/+/,"");return{host:s,port:i,sessionId:a===""?void 0:a,isLoopback:o}}function ox(n){let e=n.port!==void 0&&n.port!==An?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function KO(n){try{return new URL(n)}catch{return null}}function Xf(n){return n.length>80?`${n.slice(0,77)}...`:n}var Ts=q(()=>{"use strict";rt()});function ea(n,e){return`${n}:${e}`}function ix(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function GO(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),r=Number(n.slice(e+1));return Number.isInteger(r)?{host:t,port:r}:null}async function JO(){let n=await jt(D.remotes());return n===void 0?{version:1,entries:{}}:VO(n)}function VO(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},r={};for(let[s,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.token!="string"||typeof i.expiresAt!="string")continue;let a={token:i.token,expiresAt:i.expiresAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),r[s]=a}return{version:1,entries:r}}async function ky(n){await nn(D.remotes(),n,{mode:384})}var Zf,vy=q(()=>{"use strict";ke();es();Zf=class n{data;constructor(e){this.data=e}static async load(){let e=await JO(),t=Date.now(),r={},s=!1;for(let[i,a]of Object.entries(e.entries)){if(ix(a,t)){s=!0;continue}r[i]=a}let o={version:1,entries:r};return s&&await ky(o),new n(o)}get(e,t){let r=this.data.entries[ea(e,t)];if(r&&!ix(r,Date.now()))return r}async set(e,t,r){this.data.entries[ea(e,t)]=r,await ky(this.data)}async delete(e,t){let r=ea(e,t);return r in this.data.entries?(delete this.data.entries[r],await ky(this.data),!0):!1}list(){let e=[];for(let[t,r]of Object.entries(this.data.entries)){let s=GO(t);s&&e.push({host:s.host,port:s.port,entry:r})}return e}}});async function Vo(n){return process.stdout.write(n),process.stdin.isTTY?new Promise((e,t)=>{let r=process.stdin,s=r.isRaw===!0,o="",i=()=>{r.removeListener("data",a),r.removeListener("error",d),s||r.setRawMode(!1),r.pause()},a=c=>{for(let l of c){if(l===10||l===13){process.stdout.write(`
|
|
8
|
+
`)}async function yo(){return await Ud(),await Yf(),Bd.parse(await Hd())}async function He(){await Ud(),await Yf();let n=await Hd(),e=cy();return Bd.parse(e?Al(n,e):n)}async function qO(n){await nn(D.config(),n,{mode:384})}async function ts(n){await Ud(),await Yf();let e=await Hd();n(e),Bd.parse(e),await nn(D.config(),e,{mode:384})}async function Zi(n,e){await ts(t=>{let r=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};r[n]=e,t.tui=r})}async function hy(n){await ts(e=>{let t=e.tui&&typeof e.tui=="object"&&!Array.isArray(e.tui)?e.tui:{},r=t.sidebar&&typeof t.sidebar=="object"&&!Array.isArray(t.sidebar)?t.sidebar:{};r.enabled=n,t.sidebar=r,e.tui=t})}async function Jo(n){await ts(e=>{e.defaultAgent=n})}async function Pl(n,e,t){await ts(r=>{let s=r.sessionDefaults&&typeof r.sessionDefaults=="object"?r.sessionDefaults:{},o=s[n]&&typeof s[n]=="object"?s[n]:{};o[e]=t,s[n]=o,r.sessionDefaults=s})}async function my(n,e){await ts(t=>{let r=t.agentOverrides&&typeof t.agentOverrides=="object"?t.agentOverrides:{},s=r[n]&&typeof r[n]=="object"?r[n]:{};e===void 0?delete s.packageSpec:s.packageSpec=e,Object.keys(s).length===0?delete r[n]:r[n]=s,t.agentOverrides=r})}async function Qf(n,e){await ts(t=>{let r=t.agents&&typeof t.agents=="object"?t.agents:{};e===void 0?delete r[n]:r[n]=e,t.agents=r})}async function gy(n){await ts(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function yy(){let n=await Hd();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function zO(){return Bd.parse({})}function mt(n){return n==="~"||n==="$HOME"?ly():n.startsWith("~/")?ly()+n.slice(1):n.startsWith("$HOME/")?ly()+n.slice(5):n}var sx,MO,An,_O,$O,OO,FO,LO,NO,DO,BO,nx,Qi,Xi,Fd,Ld,Nd,Dd,HO,rx,UO,WO,Bd,rt=q(()=>{"use strict";ke();go();es();Od();sx="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",MO=j.object({cert:j.string(),key:j.string()}),An=55514,_O=j.object({host:j.string().default("127.0.0.1"),port:j.number().int().positive().default(An),logLevel:j.enum(["debug","info","warn","error"]).default("info"),tls:MO.optional(),sessionIdleTimeoutSeconds:j.number().int().nonnegative().default(3600),nonInteractiveOrphanTimeoutSeconds:j.number().int().nonnegative().default(180),sessionHistoryMaxEntries:j.number().int().positive().default(1e4),sessionHistoryArchiveMaxBytes:j.number().int().nonnegative().default(1e7),sessionHistoryArchiveTiers:j.number().int().positive().default(10),agentStderrTailBytes:j.number().int().positive().default(4096),publicHost:j.string().optional(),agentSyncIntervalMinutes:j.number().nonnegative().default(60),scrubEnv:j.array(j.string()).default([]),sessionGcIntervalMinutes:j.number().nonnegative().default(60),sessionGcMaxAgeDays:j.number().positive().default(2)}),$O=j.object({url:j.string().url().default(sx),ttlHours:j.number().positive().default(24),pinned:j.boolean().default(!1)}),OO=j.object({extends:j.string().optional(),name:j.string().optional(),description:j.string().optional(),command:j.string().optional(),args:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),FO=j.object({packageSpec:j.string().optional(),extraArgs:j.array(j.string()).optional(),env:j.record(j.string()).optional()}),LO=j.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-x-ctrl-e","ctrl-y","ctrl-underscore","alt-underscore","escape"]),NO=j.union([j.string(),j.object({field:j.string().optional(),text:j.string().optional(),script:j.string().optional(),refreshMs:j.number().int().positive().optional(),maxWidth:j.number().int().positive().optional(),minWidth:j.number().int().nonnegative().optional(),truncate:j.boolean().optional(),priority:j.number().optional(),prefix:j.string().optional(),suffix:j.string().optional(),separator:j.string().optional(),style:j.string().optional(),onClick:j.string().optional(),onDoubleClick:j.string().optional()}).strict()]),DO=j.object({id:j.string().min(1),script:j.string().min(1),refreshMs:j.number().int().positive().optional(),title:j.string().optional(),cap:j.number().int().positive().optional()}).strict(),BO=j.union([j.string(),DO]),nx=j.array(NO);Qi=["status",{field:"elapsed",separator:" "},"sessionId","queued","scroll"],Xi=["usage"],Fd=[],Ld=["helpHint"],Nd=["cwd","title"],Dd=["agentModel"],HO=j.object({composer:j.object({top:uy(Qi,Xi),bottom:uy(Fd,Ld),hintTurns:j.number().int().nonnegative().nullable().default(3)}).default({}),sessionbar:uy(Nd,Dd),scriptRefreshMs:j.number().int().positive().default(5e3),repaintThrottleMs:j.number().int().nonnegative().default(1e3),maxScrollbackLines:j.number().int().positive().default(1e4),mouse:j.boolean().default(!0),inAppSelection:j.boolean().optional(),selectionClipboard:j.enum(["primary","clipboard","both"]).default("both"),openFileCommand:j.union([j.string(),j.array(j.string())]).optional(),openFileInTerminal:j.boolean().optional(),logMaxBytes:j.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:j.number().int().positive().default(32),progressIndicator:j.boolean().default(!0),terminalHost:j.union([j.boolean(),j.enum(["auto","paseo","herdr","tmux"])]).default(!0),launcherModeWhenHosted:j.boolean().default(!1),skipPermissions:j.boolean().default(!1),defaultEnterAction:j.enum(["enqueue","amend"]).default("amend"),showThoughts:j.boolean().default(!0),ambiguousWidth:j.enum(["auto","narrow","wide"]).default("auto"),toolContent:j.enum(["inline","references"]).default("references"),diffContextLines:j.number().int().min(0).default(3),promptHistoryMaxEntries:j.number().int().positive().default(2e3),maxToolItems:j.number().int().nonnegative().default(5),maxPlanItems:j.number().int().nonnegative().default(5),sidebar:j.object({enabled:j.boolean().default(!0),width:j.number().int().positive().optional(),border:j.enum(["none","rule","frame"]).default("frame"),gadgets:j.array(BO).default(["activity","sessions","tasks","context","queue","todo","files","git","resources","info","tools"])}).default({}),showFileUpdates:j.enum(["none","edit","diff"]).default("edit"),sessionColumns:j.array(j.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),defaultHost:j.string().min(1).default("remote:all"),hotkeys:j.record(LO,j.object({command:j.union([j.string(),j.array(j.string())])})).default({}),theme:j.union([j.string(),j.record(j.string(),j.unknown())]).optional(),themeBackground:j.string().optional()}),rx=j.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),UO=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),WO=j.object({command:j.array(j.string()).default([]),args:j.array(j.string()).default([]),env:j.record(j.string()).default({}),enabled:j.boolean().default(!0)}),Bd=j.object({daemon:_O.default({}),registry:$O.default({url:sx,ttlHours:24,pinned:!1}),agents:j.record(j.string(),OO).default({}),agentOverrides:j.record(j.string(),FO).default({}),defaultAgent:j.string().default("opencode"),sessionDefaults:j.record(j.string(),j.record(j.string(),j.string())).default({}),synopsisAgent:j.string().optional(),synopsisModel:j.string().optional(),compaction:j.object({agent:j.string().optional(),model:j.string().optional(),tailK:j.number().int().nonnegative().default(20),maxIterations:j.number().int().positive().default(3),contextFraction:j.number().min(0).max(1).default(.5),hardCeilingFraction:j.number().min(0).max(1).default(.85),absoluteFallback:j.number().int().positive().default(2e5),idleBeforePromptMs:j.number().int().nonnegative().default(3e5),modelContextWindows:j.record(j.string(),j.number().int().positive()).default({})}).default({}),defaultCwd:j.string().default("~"),disableWorkspaceSnapshots:j.boolean().optional(),compressToolContent:j.boolean().default(!0),sessionListColdLimit:j.number().int().nonnegative().default(20),extensions:j.record(rx,UO).default({}),transformers:j.record(rx,WO).default({}),defaultTransformers:j.array(j.string()).default([]),npmRegistry:j.string().url().optional(),tui:HO.default({})})});function Vt(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function by(n){return{httpScheme:"https",wsScheme:"wss"}}function Ml(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 ${Xf(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Xf(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 r=KO(`http://${e}`);if(!r)throw new Error(`invalid hydra:// URL: ${Xf(n)}`);let s=r.hostname;if(!s)throw new Error(`hydra:// URL is missing a host: ${Xf(n)}`);let o=Vt(s),i;if(r.port){let c=Number(r.port);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${r.port}`);i=c}else i=An;let a=r.pathname.replace(/^\/+/,"");return{host:s,port:i,sessionId:a===""?void 0:a,isLoopback:o}}function ox(n){let e=n.port!==void 0&&n.port!==An?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function KO(n){try{return new URL(n)}catch{return null}}function Xf(n){return n.length>80?`${n.slice(0,77)}...`:n}var Ts=q(()=>{"use strict";rt()});function ea(n,e){return`${n}:${e}`}function ix(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function GO(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),r=Number(n.slice(e+1));return Number.isInteger(r)?{host:t,port:r}:null}async function JO(){let n=await jt(D.remotes());return n===void 0?{version:1,entries:{}}:VO(n)}function VO(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},r={};for(let[s,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.token!="string"||typeof i.expiresAt!="string")continue;let a={token:i.token,expiresAt:i.expiresAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),r[s]=a}return{version:1,entries:r}}async function ky(n){await nn(D.remotes(),n,{mode:384})}var Zf,vy=q(()=>{"use strict";ke();es();Zf=class n{data;constructor(e){this.data=e}static async load(){let e=await JO(),t=Date.now(),r={},s=!1;for(let[i,a]of Object.entries(e.entries)){if(ix(a,t)){s=!0;continue}r[i]=a}let o={version:1,entries:r};return s&&await ky(o),new n(o)}get(e,t){let r=this.data.entries[ea(e,t)];if(r&&!ix(r,Date.now()))return r}async set(e,t,r){this.data.entries[ea(e,t)]=r,await ky(this.data)}async delete(e,t){let r=ea(e,t);return r in this.data.entries?(delete this.data.entries[r],await ky(this.data),!0):!1}list(){let e=[];for(let[t,r]of Object.entries(this.data.entries)){let s=GO(t);s&&e.push({host:s.host,port:s.port,entry:r})}return e}}});async function Vo(n){return process.stdout.write(n),process.stdin.isTTY?new Promise((e,t)=>{let r=process.stdin,s=r.isRaw===!0,o="",i=()=>{r.removeListener("data",a),r.removeListener("error",d),s||r.setRawMode(!1),r.pause()},a=c=>{for(let l of c){if(l===10||l===13){process.stdout.write(`
|
|
9
9
|
`),i(),e(o);return}if(l===3){i(),t(new Error("password entry cancelled"));return}if(l===127||l===8){o=o.slice(0,-1);continue}o+=String.fromCharCode(l)}},d=c=>{i(),t(c)};r.setRawMode(!0),r.resume(),r.on("data",a),r.on("error",d)}):YO()}function YO(){return new Promise((n,e)=>{let t="";process.stdin.setEncoding("utf8");let r=o=>{t+=o;let i=t.indexOf(`
|
|
10
10
|
`);i!==-1&&(process.stdin.removeListener("data",r),process.stdin.removeListener("error",s),n(t.slice(0,i).replace(/\r$/,"")))},s=o=>{process.stdin.removeListener("data",r),process.stdin.removeListener("error",s),e(o)};process.stdin.on("data",r),process.stdin.on("error",s)})}var ep=q(()=>{"use strict"});import*as ax from"path";function Nn(){let n=process.argv[1];if(!n)return"hydra-acp";let e=ax.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Wd=q(()=>{"use strict"});import*as tp from"fs/promises";async function Es(){try{let n=await tp.readFile(D.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 dx(n){await tp.writeFile(D.pidFile(),JSON.stringify(n)+`
|
|
11
11
|
`,{encoding:"utf8",mode:384})}function kr(n){try{return process.kill(n,0),!0}catch(e){let t=e.code;return t==="EPERM"||t==="EACCES"}}var jd=q(()=>{"use strict";ke()});var hx={};Ji(hx,{_resetForTests:()=>sF,clearPin:()=>xy,fetchPeerFingerprint:()=>Ay,formatFingerprint:()=>Qo,getPin:()=>Iy,installGlobalTlsTrust:()=>_l,loadPinsFromPeerStore:()=>Ry,loadPinsFromStore:()=>Cy,setPin:()=>Yo,sha256Hex:()=>Ty,wsTlsOptions:()=>$l});import{createHash as QO}from"crypto";import*as cx from"tls";import{Agent as XO,Dispatcher as ZO,buildConnector as eF,getGlobalDispatcher as tF,setGlobalDispatcher as nF}from"undici";function Yo(n,e,t){ta.set(ea(n,e),lx(t))}function xy(n,e){ta.delete(ea(n,e))}function Iy(n,e){return ta.get(ea(n,e))}function Cy(n){ta.clear();for(let e of n.list())e.entry.pinnedFingerprint&&Yo(e.host,e.port,e.entry.pinnedFingerprint)}function Ry(n){for(let e of n.list())e.pinnedFingerprint&&Yo(e.host,e.port,e.pinnedFingerprint)}async function Ay(n,e,t={}){let r=t.timeoutMs??1e4;return new Promise((s,o)=>{let i=cx.connect({host:n,port:e,servername:n,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,d=(l,u)=>{if(!a){a=!0,clearTimeout(c);try{i.destroy()}catch{}l?o(l):u&&s(u)}},c=setTimeout(()=>{d(new Error(`TLS connect to ${n}:${e} timed out`))},r);i.once("secureConnect",()=>{let l=i.getPeerCertificate(!1);if(!l||!l.raw){d(new Error(`${n}:${e} did not present a TLS certificate`));return}d(null,Ty(l.raw))}),i.once("error",l=>d(l))})}function Ty(n){return QO("sha256").update(n).digest("hex")}function Qo(n){let e=lx(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function lx(n){return n.replace(/:/g,"").toLowerCase()}function _l(){if(Sy)return;Sy=!0;let n=tF(),e=new XO({connect:eF({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(r,s)=>fx(r,s)})}),t=new ZO;t.dispatch=(r,s)=>{let o=rF(r.origin);return(o&&ux(o)?e:n).dispatch(r,s)},t.close=(()=>Promise.all([e.close(),n.close()]).then(()=>{})),t.destroy=(r=>Promise.all([e.destroy(r??null),n.destroy(r??null)]).then(()=>{})),nF(t)}function rF(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function ux(n){for(let e of ta.keys())if(px(e)?.host===n)return!0;return!1}function fx(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=Ty(e.raw);for(let[r,s]of ta.entries()){let o=px(r);if(o&&o.host===n&&s===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${Qo(t)})`)}function px(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),r=Number(n.slice(e+1));return Number.isInteger(r)?{host:t,port:r}:null}function $l(n){return ux(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>fx(e,t)}:{autoSelectFamily:!0}}function sF(){ta.clear(),Sy=!1}var ta,Sy,Xo=q(()=>{"use strict";vy();ta=new Map,Sy=!1});import*as yx from"os";async function rn(n){let e=await Il(),t=await Es();if(t&&kr(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 r=n.daemon.host,s=r==="0.0.0.0"||r==="::"||r==="0.0.0.0/0"?"127.0.0.1":r,o=n.daemon.port;return{baseUrl:`http://${s}:${o}`,wsUrl:`ws://${s}:${o}/acp`,token:e,display:`${r}:${o}`,isLocal:Vt(s)}}function mx(n,e){let{httpScheme:t,wsScheme:r}=by(n.host);return{baseUrl:`${t}://${n.host}:${n.port}`,wsUrl:`${r}://${n.host}:${n.port}/acp`,token:e,display:bx(n),isLocal:n.isLoopback}}async function wx(n,e={}){let t=e.fetchImpl??fetch,r=e.promptImpl??Vo,s=e.confirmImpl??My,o=e.tlsHandshakeImpl??Py,i=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(n.isLoopback&&i){let w=await _d();if(w)return iF(n,w)}let d=e.store??await Zf.load();Cy(d),_l();let c=d.get(n.host,n.port);if(c)return c.pinnedFingerprint&&Yo(n.host,n.port,c.pinnedFingerprint),mx(n,c.token);if(!a)throw new Ey(n.host,n.port);let l=bx(n),{httpScheme:u}=by(n.host),f;if(u==="https"&&Iy(n.host,n.port)===void 0){let w=await o(n.host,n.port);if(w.kind==="untrusted"){let b=w.subject||w.issuer?`
|
|
@@ -13,8 +13,8 @@ var lO=Object.defineProperty;var q=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ji=(n,e)=>{f
|
|
|
13
13
|
issuer: ${w.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
|
|
14
14
|
sha256: ${Qo(w.fingerprint)}${b}
|
|
15
15
|
`),!await s(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Yo(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 r(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let m=`${u}://${n.host}:${n.port}`,h=await t(`${m}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:np()})});if(h.status===401)throw new Error(`Wrong password for ${l}.`);if(h.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(h.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!h.ok)throw new Error(`Login to ${l} failed: HTTP ${h.status}`);let g=await h.json();if(!g.session_token||!g.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await d.set(n.host,n.port,{token:g.session_token,expiresAt:g.expires_at,label:np(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),mx(n,g.session_token)}async function Py(n,e){let t=await oF(n,e);return t.kind!=="untrusted"?t:{kind:"untrusted",fingerprint:await Ay(n,e),...t.subject!==void 0?{subject:t.subject}:{},...t.issuer!==void 0?{issuer:t.issuer}:{}}}async function oF(n,e,t=1e4){let r=await import("tls");return new Promise(s=>{let o=!1,i=c=>{if(!o){o=!0,clearTimeout(d);try{a.destroy()}catch{}s(c)}},a=r.connect({host:n,port:e,servername:n,autoSelectFamily:!0}),d=setTimeout(()=>i({kind:"error",message:`TLS connect timed out after ${t}ms`}),t);a.once("secureConnect",()=>i({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);i({kind:"untrusted",subject:p?.subject?gx(p.subject):void 0,issuer:p?.issuer?gx(p.issuer):void 0});return}let f=[l,c.message].filter(p=>p&&p.length>0);i({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{i({kind:"error",message:"connection closed before TLS handshake completed"})})})}function gx(n){if(!n)return"";let e=[];for(let[t,r]of Object.entries(n)){let s=Array.isArray(r)?r.join(", "):r;e.push(`${t}=${s}`)}return e.join(", ")}async function iF(n,e){let t=await Es(),s=t&&kr(t.pid)?t.loopbackPort:n.port,o=n.port===An?n.host:`${n.host}:${n.port}`;return{baseUrl:`http://127.0.0.1:${s}`,wsUrl:`ws://127.0.0.1:${s}/acp`,token:e,display:o,isLocal:!0}}async function My(n){return process.stdout.write(n),new Promise(e=>{let t="",r=s=>{t+=s.toString("utf8");let o=t.indexOf(`
|
|
16
|
-
`);if(o===-1)return;process.stdin.removeListener("data",r),process.stdin.pause();let i=t.slice(0,o).trim().toLowerCase();e(i==="y"||i==="yes")};process.stdin.resume(),process.stdin.on("data",r)})}function np(){try{let n=yx.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function bx(n){return n.port===An?n.host:`${n.host}:${n.port}`}var Ey,
|
|
17
|
-
`)}catch{}}function lF(n){try{if(cF(n).size<vx)return;dF(n,`${n}.0`)}catch{}}var vx,na=q(()=>{"use strict";ke();vx=5*1024*1024});import{WebSocket as uF}from"ws";async function
|
|
16
|
+
`);if(o===-1)return;process.stdin.removeListener("data",r),process.stdin.pause();let i=t.slice(0,o).trim().toLowerCase();e(i==="y"||i==="yes")};process.stdin.resume(),process.stdin.on("data",r)})}function np(){try{let n=yx.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function bx(n){return n.port===An?n.host:`${n.host}:${n.port}`}var Ey,wo=q(()=>{"use strict";rt();go();Ts();vy();ep();Wd();jd();Xo();Ts();Ey=class extends Error{host;port;constructor(e,t){let r=t===An?"":`:${t}`;super(`No cached credentials for ${e}:${t}. Run \`${Nn()} --session hydra://${e}${r}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=t}}});import{appendFileSync as aF,renameSync as dF,statSync as cF}from"fs";function Sx(n){vx=n}function ge(n){let e=process.env.HYDRA_TUI_DEBUG_LOG,t=e===void 0?D.tuiLogFile():e;if(t.length!==0)try{lF(t);let r=JSON.stringify({t:new Date().toISOString(),...n});aF(t,`${r}
|
|
17
|
+
`)}catch{}}function lF(n){try{if(cF(n).size<vx)return;dF(n,`${n}.0`)}catch{}}var vx,na=q(()=>{"use strict";ke();vx=5*1024*1024});import{WebSocket as uF}from"ws";async function bo(n,e,t=fF){let r={};try{let s=new URL(n);if(s.protocol==="wss:"){let o=$l(s.hostname);o.rejectUnauthorized!==void 0&&(r.rejectUnauthorized=o.rejectUnauthorized),o.autoSelectFamily!==void 0&&(r.autoSelectFamily=o.autoSelectFamily),o.checkServerIdentity!==void 0&&(r.checkServerIdentity=o.checkServerIdentity)}}catch{}return new Promise((s,o)=>{let i=new uF(n,e,r),a=Date.now(),d=setTimeout(()=>{i.off("open",c),i.off("error",l),i.on("error",()=>{});try{i.terminate()}catch{}o(new $y(n,Date.now()-a))},t),c=()=>{clearTimeout(d),i.off("error",l),s(i)},l=u=>{clearTimeout(d),i.off("open",c),o(u)};i.once("open",c),i.once("error",l)})}var fF,$y,qd=q(()=>{"use strict";Xo();fF=1e4,$y=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 rp from"fs/promises";function pF(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"?"127.0.0.1":n}async function zd(){let n=await Es();if(n&&kr(n.pid))return`http://127.0.0.1:${n.loopbackPort}`;let e=await He();return xx(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function xx(n,e,t){return`${t?"https":"http"}://${pF(n)}:${e}`}async function Pe(n,e={}){let t=await Vi(),r=await zd(),s=n.startsWith("http")?n:`${r}${n}`,o={Authorization:`Bearer ${t}`},i;e.body!==void 0&&(o["Content-Type"]="application/json",i=JSON.stringify(e.body));let a;try{a=await fetch(s,{method:e.method,headers:o,...i!==void 0?{body:i}:{}})}catch(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${r}: ${u.message}
|
|
18
18
|
`),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}
|
|
19
19
|
`),process.exit(1)}return{ok:a.ok,status:a.status,body:d}}function Kd(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),r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;let s=Math.floor(r/60);if(s<60)return`${s}m ago`;let o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function sp(n,e){let t=e!=="agent",r=t?[]:void 0,s=[],o={},i=!0,a,d=0;for(;d<n.length;){let c=n[d];if(c==="--command"){let l=n[d+1];l===void 0&&(process.stderr.write(`--command requires a value
|
|
20
20
|
`),process.exit(2)),r=t?hF(l):l,d+=2;continue}if(c==="--args"){let l=n[d+1];l===void 0&&(process.stderr.write(`--args requires a value
|
|
@@ -23,12 +23,12 @@ var lO=Object.defineProperty;var q=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ji=(n,e)=>{f
|
|
|
23
23
|
`),process.exit(2)),o[l.slice(0,u)]=l.slice(u+1),d+=2;continue}if(c==="--extends"&&e==="agent"){let l=n[d+1];l===void 0&&(process.stderr.write(`--extends requires an agent id
|
|
24
24
|
`),process.exit(2)),a=l,d+=2;continue}if(c==="--disabled"&&e!=="agent"){i=!1,d+=1;continue}process.stderr.write(`Unknown flag: ${c}
|
|
25
25
|
`),process.exit(2)}return{command:r,args:s,env:o,enabled:i,extendsBase:a}}function hF(n){return n.split(/\s+/).filter(e=>e.length>0)}async function Gd(){let n=await rp.readFile(D.config(),"utf8");return JSON.parse(n)}async function Oy(n){await rp.writeFile(D.config(),JSON.stringify(n,null,2)+`
|
|
26
|
-
`,{encoding:"utf8",mode:384})}var vr=q(()=>{"use strict";rt();mo();ke();jd();qd()});function gt(n){if(!Number.isInteger(n)||n<0||n>15)throw new Error(`ansi() takes 0-15, got ${n}`);return{kind:"ansi",index:n}}function Dn(n,e,t){return{kind:"rgb",r:Fy(n),g:Fy(e),b:Fy(t)}}function Zo(n){let e=n.trim().toLowerCase(),t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/.exec(e);if(t){let s=t[1];return s.length===3?Dn(parseInt(s[0]+s[0],16),parseInt(s[1]+s[1],16),parseInt(s[2]+s[2],16)):Dn(parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16))}let r=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/.exec(e);return r?Dn(Number(r[1]),Number(r[2]),Number(r[3])):null}function Rx(n){let e=f=>{let p=[0,95,135,175,215,255],m=0;for(let h=1;h<p.length;h++)Math.abs(p[h]-f)<Math.abs(p[m]-f)&&(m=h);return m},t=[0,95,135,175,215,255],r=e(n.r),s=e(n.g),o=e(n.b),i=16+36*r+6*s+o,a=(t[r]-n.r)**2+(t[s]-n.g)**2+(t[o]-n.b)**2,d=(n.r+n.g+n.b)/3,c=Math.round((d-8)/10);c=Math.max(0,Math.min(23,c));let l=8+c*10;return(l-n.r)**2+(l-n.g)**2+(l-n.b)**2<a?232+c:i}function mF(n){let e=(n.r+n.g+n.b)/3;return e<=4?16:e>=247?231:232+Math.max(0,Math.min(23,Math.round((e-8)/10)))}function Ax(n){if(n===void 0||n.size===0){Ol=void 0;return}let e=new Map;for(let[t,r]of n)r.kind==="rgb"&&e.set(t,r);Ol=e.size>0?e:void 0}function By(n){let e=Ol?.get(n);if(e!==void 0)return e;let[t,r,s]=Dy[n];return{kind:"rgb",r:t,g:r,b:s}}function Tx(n,e){let t=By(n);return(t.r-e.r)**2+(t.g-e.g)**2+(t.b-e.b)**2}function Ex(n){let e=gF;if(Ol!==void 0){let s=Dy.map((o,i)=>i).filter(o=>{let i=By(o);return Math.max(i.r,i.g,i.b)-Math.min(i.r,i.g,i.b)<=Ly});s.length>0&&(e=s)}let t=e[0],r=1/0;for(let s of e){let o=Tx(s,n);o<r&&(r=o,t=s)}return t}function Px(n){let e=Math.max(n.r,n.g,n.b),t=Math.min(n.r,n.g,n.b);if(e-t<=Ly)return Ex(n);if(Ol!==void 0){let o=Dy.map((i,a)=>a).filter(i=>{let a=By(i);return Math.max(a.r,a.g,a.b)-Math.min(a.r,a.g,a.b)>Ly});if(o.length>0){let i=o[0],a=1/0;for(let d of o){let c=Tx(d,n);c<a&&(a=c,i=d)}return i}}let r=(e+t)/2,s=(n.r>=r?1:0)|(n.g>=r?2:0)|(n.b>=r?4:0);return e>=yF?s+8:s}function wF(n,e){let t=r=>String(r<8?30+r:90+(r-8));return n.kind==="ansi"?t(n.index):e==="truecolor"?`38;2;${n.r};${n.g};${n.b}`:e==="ansi256"?`38;5;${Rx(n)}`:t(Px(n))}function bF(n,e,t=!1){let r=s=>String(s<8?40+s:100+(s-8));return n.kind==="ansi"?r(n.index):e==="truecolor"?`48;2;${n.r};${n.g};${n.b}`:e==="ansi256"?`48;5;${t?mF(n):Rx(n)}`:r(t?Ex(n):Px(n))}function Ny(n){if(n.kind==="ansi")return null;let e=t=>{let r=t/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4};return .2126*e(n.r)+.7152*e(n.g)+.0722*e(n.b)}function Jd(n,e=!0){let t=Ny(n);return t===null?e:t<kF}function Wy(n,e){let t=Ny(n),r=Ny(e);return t===null||r===null?null:(Math.max(t,r)+.05)/(Math.min(t,r)+.05)}function vF(n,e){return n.kind==="ansi"?n:Dn(n.r+(255-n.r)*e,n.g+(255-n.g)*e,n.b+(255-n.b)*e)}function SF(n,e){return n.kind==="ansi"?n:Dn(n.r*(1-e),n.g*(1-e),n.b*(1-e))}function Vd(n,e,t){if(n.kind==="ansi")return n;let r=s=>Jd(n)?vF(n,s):SF(n,s);if(t===void 0)return r(e);for(let s=e;s>.005;s-=.01){let o=r(s),i=Wy(o,t);if(i===null||i>=xF)return o}return n}var Fy,op,Dy,gF,Ly,yF,Ol,Hy,ra,Mx,Uy,kF,xF,Yd=q(()=>{"use strict";Fy=n=>Math.max(0,Math.min(255,Math.round(n)));op="\x1B[";Dy=[[0,0,0],[128,0,0],[0,128,0],[128,128,0],[0,0,128],[128,0,128],[0,128,128],[192,192,192],[128,128,128],[255,0,0],[0,255,0],[255,255,0],[0,0,255],[255,0,255],[0,255,255],[255,255,255]],gF=[0,8,7,15],Ly=24,yF=170;Hy=`${op}39m`,ra=`${op}49m`,Mx=(n,e)=>`${op}${wF(n,e)}m`,Uy=(n,e,t=!1)=>`${op}${bF(n,e,t)}m`;kF=.179;xF=4});function _x(n){let e=n.NO_COLOR;return e!==void 0&&e!==""}function IF(n){let e=n.FORCE_COLOR;if(e!==void 0)switch(e){case"0":case"false":return"none";case"1":return"ansi16";case"2":return"ansi256";case"3":return"truecolor";default:return}}function CF(n){let e=n.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"}function jy(n){let e=(n.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return"truecolor";let t=(n.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("direct")?"truecolor":t.includes("256")?"ansi256":"ansi16"}function Fl(n=process.stdout,e=process.env){if(_x(e))return"none";let t=IF(e);return t!==void 0?t:CF(e)?jy(e):(e.TERM??"").toLowerCase()==="dumb"||n.isTTY!==!0?"none":jy(e)}function $x(n=process.stdout,e=process.env){return Fl(n,e)!=="none"}function RF(n){return Ox(n)?(n.TERM??"").toLowerCase().startsWith("screen"):!1}function Ox(n){return n.TMUX!==void 0&&n.TMUX!==""}function Qd(n,e=process.env){if(_x(e))return"none";let t=n?.esc,r=l=>l!==void 0&&!l.na&&!l.fb,s=r(t?.color24bits)?"truecolor":r(t?.color256)?"ansi256":"ansi16",o=t?.color256?.na===!0?"ansi16":"truecolor",i=jy(e),a=i==="truecolor"&&RF(e)||Ox(e)&&i==="ansi16"?"ansi256":i,d=["none","ansi16","ansi256","truecolor"],c=l=>d.indexOf(l);return d[Math.min(Math.max(c(s),c(a)),c(o))]}function Fx(n=process.env){let e=n.COLORFGBG;if(e===void 0||e==="")return;let t=e.split(";").pop()?.trim()??"";if(!/^\d+$/.test(t))return;let r=Number(t);if(!(r>15))return r<=6||r===8?"dark":"light"}var sa=q(()=>{"use strict"});function TF(n,e){let t=`${Ms}49m`;if(e==="truecolor")return{open:`${Ms}48;2;${n};${n};${n}m`,close:t};let r=Math.round(n*25/255),s=r===0?16:r===25?231:r+231;return{open:`${Ms}48;5;${s}m`,close:t}}function Hx(){return Ie.fg===void 0?Bx:void 0}function Ux(){return Dx??Ie.bg}function Wx(){let n=Ux();if(n===void 0)return EF;let e=Hx();return{user:Vd(n,Ll.user,e),code:Vd(n,Ll.code,e),hoverThought:Vd(n,Ll.hoverThought,e),hoverCode:Vd(n,Ll.hoverCode,e)}}function qy(n,e){return Ze(MF(n,e))}function MF(n,e){if(n.kind!=="rgb")return e;let t=[Ie.bg,Ie.fg,e].filter(i=>i!==void 0),r=i=>{let a=e,d=-1;for(let c of i){let l=Wy(n,c)??-1;l>d&&(d=l,a=c)}return{color:a,ratio:d}},s=r(t);if(s.ratio>=_F)return s.color;let o=r([...t,Dn(0,0,0),Dn(255,255,255)]);return o.ratio>s.ratio?o.color:s.color}function dp(){return{fg:Ie.fg===void 0?[]:[Ze(Ie.fg)],fgStrong:[Ze(Ie.brightWhite)],muted:Ie.fg===void 0?[ip]:[ip,Ze(Ie.brightBlack)],subtle:[Ze(Ie.brightBlack)],emphasis:[Ky],active:[Ze(Ie.brightYellow)],warn:[Ze(Ie.yellow)],ok:[Ze(Ie.green)],error:[Ze(Ie.brightRed)],errorSoft:[Ze(Ie.red)],cold:[Ze(Ie.brightMagenta)],gitStaged:[Ze(Ie.green)],gitDirty:[Ze(Ie.brightBlue)],gitUntracked:Ie.fg===void 0?[ip]:[ip,Ze(Ie.brightBlack)],accent:[Ze(Ie.brightCyan)],info:[Ze(Ie.cyan)],reference:[Ze(Ie.brightBlue)],focus:[Ze(Ie.brightBlue)],selectionBand:[Ps(Ie.blue)],selection:[Ps(Ie.blue),qy(Ie.blue,Ie.brightWhite)],cursor:[Ps(Ie.white)],promptCursor:[Ps(Ie.brightYellow)],match:[Ps(Ie.brightYellow),qy(Ie.brightYellow,Ie.black)],matchActive:[Ps(Ie.red),qy(Ie.red,Ie.brightWhite)],invert:[OF],codeText:[Ze(Ie.white)],syntaxKeyword:[Ze(Ie.brightBlue)],syntaxType:[Ze(Ie.brightCyan)],syntaxBuiltin:[Ze(Ie.cyan)],syntaxLiteral:[Ze(Ie.blue)],syntaxNumber:[Ze(Ie.brightGreen)],syntaxString:[Ze(Ie.yellow)],syntaxRegexp:[Ze(Ie.red)],syntaxComment:[Ze(Ie.brightBlack)],syntaxClass:[Ze(Ie.brightYellow)],syntaxMeta:[Ze(Ie.magenta)],syntaxVariable:[Ze(Ie.white)],diffAdded:[Ze(Ie.brightGreen)],diffRemoved:[Ze(Ie.brightRed)],syntaxDoctag:[Ze(Ie.green)],syntaxEmphasis:[FF],syntaxStrong:[Ky],syntaxLink:[LF]}}function jx(n,e){let t=!1,r=!1,s=n.map(o=>o.kind==="fg"&&e.fg!==void 0?(t=!0,Ze(e.fg)):o.kind==="bg"&&e.bg!==void 0?(r=!0,Ps(e.bg)):(o.kind==="fg"&&(t=!0),o.kind==="bg"&&(r=!0),o));return e.fg!==void 0&&!t&&s.push(Ze(e.fg)),e.bg!==void 0&&!r&&s.unshift(Ps(e.bg)),s}function qx(n){return n.some(e=>e.kind==="fg")||!n.some(e=>e.kind==="bg")}function Kx(n){if(Object.keys(Gy).length===0)return n;let e={...n};for(let[t,r]of Object.entries(Gy))r===void 0||e[t]===void 0||(e[t]=jx(e[t],r));return e}function Gx(n){n!==Dl&&(Dl=n,_s=Yy(),ap=void 0,oa={prose:Qy(),thought:Xy(),revision:oa.revision+1})}function Xd(n){return n.map(e=>e.open(Dl)).join("")}function Yy(){let n=Xd(z.accent);return{code:n,codeQuiet:Xd(z.info),link:n+Zd,thoughtBase:Xd(z.subtle)}}function Qy(){return{codeOpen:_s.code,linkOpen:_s.link,base:Xd(z.fg)}}function Xy(){return{codeOpen:_s.codeQuiet,linkOpen:_s.link,base:_s.thoughtBase}}function Jx(){return oa.prose}function Vx(){return oa.thought}function cp(n){return{codeOpen:n==="heading-2"?Xd(z.active):_s.code,linkOpen:_s.link,base:ec(n,Dl).open}}function Lx(n,e){return{open:n.map(t=>t.open(e)).join(""),close:n.slice().reverse().map(t=>t.close).join("")}}function Yx(){return{user:{band:Nl.user,layers:[...z.emphasis]},agent:{layers:[...z.fg],inlineSgr:!0},thought:{layers:[...z.subtle],inlineSgr:!0},tool:{layers:[...z.reference]},"tool-status-ok":{layers:[...z.muted]},"tool-status-pending":{layers:[...z.muted]},"tool-status-cancelled":{layers:[...z.muted]},"tool-status-running":{layers:[...z.active]},"tool-status-fail":{layers:[...z.emphasis,...z.errorSoft]},plan:{layers:[...z.active],inlineSgr:!0},"plan-done":{layers:[...z.ok],inlineSgr:!0},"plan-pending":{layers:[...z.muted],inlineSgr:!0},"local-heading":{layers:[...z.emphasis]},"local-item":{layers:[...z.info]},notice:{layers:[...z.info]},"notice-ok":{layers:[...z.ok]},"notice-error":{layers:[...z.errorSoft]},metric:{layers:[...z.info]},muted:{layers:[...z.muted]},"tool-output":{layers:[...z.muted]},"status-ready":{layers:[...z.fg]},"status-active":{layers:[...z.active]},"status-blocked":{layers:[...z.warn]},"status-queued":{layers:[...z.active]},"status-alert":{layers:[...z.error]},"status-cold":{layers:[...z.cold]},"git-staged":{layers:[...z.gitStaged]},"git-dirty":{layers:[...z.gitDirty]},"git-untracked":{layers:[...z.gitUntracked]},"file-path":{layers:[...z.reference]},"meter-fill":{layers:[...z.ok]},"meter-warn":{layers:[...z.emphasis,...z.errorSoft]},"sidebar-rule":{layers:[...z.muted]},"sidebar-title":{layers:[...z.muted]},"sidebar-value":{layers:[...z.fg]},"status-idle":{layers:[...z.muted]},"box-border":{layers:[...z.muted]},"box-border-focused":{layers:[...z.focus]},"box-border-hover":{layers:[...z.muted,...z.emphasis]},"box-border-focused-hover":{layers:[...z.focus,...z.emphasis]},"box-title":{layers:[...z.accent]},"modal-title":{layers:[...z.fgStrong,...z.emphasis]},"modal-label":{layers:[...z.muted]},"modal-value":{layers:[...z.fgStrong]},"modal-note":{layers:[...z.active]},"modal-error":{layers:[...z.error]},"modal-hint":{layers:[...z.muted]},"modal-status":{layers:[...z.muted]},"modal-key":{layers:[...z.accent]},"input-error":{layers:[...z.errorSoft]},"input-cursor":{layers:[...z.cursor]},"prompt-text":{layers:[...z.active]},"prompt-cursor":{layers:[...z.promptCursor]},"prompt-destructive":{layers:[...z.error]},"list-selected":{layers:[...z.selection]},"list-description":{layers:[...z.muted]},"list-header":{layers:[...z.muted]},"modal-option":{layers:[...z.muted]},"modal-option-selected":{layers:[...z.active]},"bar-text":{layers:[...z.emphasis]},"bar-indicator":{layers:[...z.accent]},rule:{layers:[...z.emphasis]},"rule-pad":{layers:[...z.muted]},"rule-meta":{layers:[...z.muted]},"hint-hover":{layers:[...z.fg]},"completion-name":{layers:[...z.accent]},"completion-desc":{layers:[...z.muted]},attachment:{layers:[...z.warn]},"queue-row":{layers:[...z.selection]},"queue-cursor":{layers:[...z.selection,Ky]},"queue-blank":{layers:[...z.selectionBand]},"composer-gutter":{layers:[...z.fgStrong]},"composer-inactive":{layers:[...z.muted]},"composer-continuation":{layers:[...z.muted]},"syntax-addition":{layers:[...z.diffAdded]},"syntax-attr":{layers:[...z.syntaxBuiltin]},"syntax-attribute":{layers:[...z.syntaxBuiltin]},"syntax-built_in":{layers:[...z.syntaxBuiltin]},"syntax-builtin-name":{layers:[...z.fg]},"syntax-bullet":{layers:[...z.fg]},"syntax-class":{layers:[...z.syntaxClass]},"syntax-code":{layers:[...z.fg]},"syntax-comment":{layers:[...z.syntaxComment]},"syntax-default":{layers:[...z.fg]},"syntax-deletion":{layers:[...z.diffRemoved]},"syntax-doctag":{layers:[...z.syntaxDoctag]},"syntax-emphasis":{layers:[...z.syntaxEmphasis]},"syntax-formula":{layers:[...z.fg]},"syntax-function":{layers:[...z.syntaxString]},"syntax-keyword":{layers:[...z.syntaxKeyword]},"syntax-link":{layers:[...z.syntaxLink]},"syntax-literal":{layers:[...z.syntaxLiteral]},"syntax-meta":{layers:[...z.syntaxMeta]},"syntax-meta-keyword":{layers:[...z.fg]},"syntax-meta-string":{layers:[...z.fg]},"syntax-name":{layers:[...z.syntaxType]},"syntax-number":{layers:[...z.syntaxNumber]},"syntax-params":{layers:[...z.syntaxVariable]},"syntax-quote":{layers:[...z.fg]},"syntax-regexp":{layers:[...z.syntaxRegexp]},"syntax-section":{layers:[...z.syntaxBuiltin]},"syntax-selector-attr":{layers:[...z.fg]},"syntax-selector-class":{layers:[...z.fg]},"syntax-selector-id":{layers:[...z.fg]},"syntax-selector-pseudo":{layers:[...z.fg]},"syntax-selector-tag":{layers:[...z.fg]},"syntax-string":{layers:[...z.syntaxString]},"syntax-strong":{layers:[...z.syntaxStrong]},"syntax-subst":{layers:[...z.fg]},"syntax-symbol":{layers:[...z.syntaxMeta]},"syntax-tag":{layers:[...z.syntaxBuiltin]},"syntax-template-tag":{layers:[...z.fg]},"syntax-template-variable":{layers:[...z.fg]},"syntax-title":{layers:[...z.syntaxString]},"syntax-type":{layers:[...z.syntaxType]},"syntax-variable":{layers:[...z.syntaxVariable]},content:{layers:[...z.fg]},"cli-warn":{layers:[...z.warn]},code:{band:Nl.code,layers:[...z.codeText]},"heading-1":{layers:[...z.emphasis,...z.active],inlineSgr:!0},"heading-2":{layers:[...z.emphasis,...z.accent],inlineSgr:!0},"heading-3":{layers:[...z.emphasis],inlineSgr:!0},"search-highlight":{layers:[...z.match]},"search-highlight-active":{layers:[...z.matchActive]},"selection-highlight":{layers:[...z.invert]}}}function Zy(n,e={}){Ie=n,Gy=e.roles??{},zx=e.elements??{},Dx=e.background,Bx=e.foreground,Nl=Wx(),z=Kx(dp()),_s=Yy(),Hl=Yx(),ap=void 0,oa={prose:Qy(),thought:Xy(),revision:oa.revision+1}}function Qx(){return Object.keys(dp()).sort()}function Xx(){return Object.keys(Hl).sort()}function Zx(n){let t=dp()[n];return t===void 0?!0:qx(t)}function eI(n){let e=Hl[n];return e===void 0||e.band!==void 0?!0:qx(e.layers??[])}function tI(){return oa.revision}function nI(){return ap??=DF(),ap}function Jy(n){return typeof n=="number"?{open:e=>TF(n,e).open,close:ra,kind:"bg"}:$F(n)}function ec(n,e){if(e==="none")return zy;if(n===void 0)return z.fg.length===0?zy:{...Lx(z.fg,e),inlineSgr:!1};let t=Hl[n];if(t===void 0)return zy;let r=[],s=zx[n];return t.band!==void 0&&r.push(s?.bg!==void 0?Ps(s.bg):Jy(t.band)),t.layers&&r.push(...t.layers),s!==void 0&&(r=jx(r,t.band!==void 0?{fg:s.fg}:s)),z.fg.length>0&&!r.some(o=>o.kind==="fg")&&((t.layers??[]).some(i=>i.kind==="bg")||r.push(...z.fg)),{...Lx(r,e),inlineSgr:t.inlineSgr===!0}}function rI(n){return n===void 0?!1:Hl[n]?.inlineSgr===!0}function B(n,e,t){t.length!==0&&n.noFormat(aa(e,t,Qd(n)))}function aa(n,e,t="ansi256"){let r=ec(n,t);return r.open+e+r.close}function DF(){let n=Xd(z.codeText),e={};for(let t of NF){let{open:r,close:s}=ec(t,Dl),o=t.slice(7);if(r===""){e[o]=a=>a;continue}let i=s.split(Hy).join(n);e[o]=a=>r+a+i}return e}function HF(n){let e=Ux();if(e===void 0)return PF;let t=Ps(Vd(e,Ll.hoverRow,Hx()));return{open:t.open(n),close:t.close}}function Nx(n,e){return n.split(ns).join(ns+e)}function sI(n,e){if(n===void 0)return;if(n==="thought"){let s=Jy(Nl.hoverThought).open(e);return{open:s,close:ra,inlineSgr:!0,transform:o=>Nx(o.split(_s.thoughtBase).join(`${Ms}39m`),s)}}if(n==="code")return{open:Jy(Nl.hoverCode).open(e),close:ra,inlineSgr:!1};if(!BF.has(n))return;let t=ec(n,e),r=HF(e);return{open:r.open+t.open,close:t.close+r.close,inlineSgr:t.inlineSgr,transform:t.inlineSgr?s=>Nx(s,r.open):void 0}}var AF,Ms,ia,Ie,Ll,EF,Dx,Bx,PF,Nl,_F,Ze,Ps,$F,Bl,Ky,ip,OF,FF,LF,Gy,zx,z,Dl,ns,Vy,Zd,_s,Hl,oa,ap,zy,NF,BF,Tn=q(()=>{"use strict";Yd();sa();AF="\x1B",Ms=`${AF}[`;ia={black:gt(0),red:gt(1),green:gt(2),yellow:gt(3),blue:gt(4),magenta:gt(5),cyan:gt(6),white:gt(7),brightBlack:gt(8),brightRed:gt(9),brightGreen:gt(10),brightYellow:gt(11),brightBlue:gt(12),brightMagenta:gt(13),brightCyan:gt(14),brightWhite:gt(15)},Ie=ia,Ll={user:.17,code:.11,hoverThought:.1,hoverRow:.19,hoverCode:.2},EF={user:43,code:28,hoverThought:25,hoverCode:48};PF={open:`${Ms}48;5;236m`,close:ra},Nl=Wx();_F=3,Ze=n=>({open:e=>Mx(n,e),close:Hy,kind:"fg"}),Ps=n=>({open:e=>Uy(n,e),close:ra,kind:"bg"}),$F=n=>({open:e=>Uy(n,e,!0),close:ra,kind:"bg"}),Bl=(n,e)=>({open:()=>`${Ms}${n}m`,close:`${Ms}${e}m`,kind:"attr"}),Ky=Bl(1,22),ip=Bl(2,22),OF=Bl(7,27),FF=Bl(3,23),LF=Bl(4,24);Gy={},zx={};z=Kx(dp()),Dl="ansi256";ns=`${Ms}0m`,Vy=`${Ms}1m`,Zd=`${Ms}4m`;_s=Yy();Hl=Yx(),oa={prose:Qy(),thought:Xy(),revision:0};zy={open:"",close:"",inlineSgr:!1};NF=["syntax-addition","syntax-attr","syntax-attribute","syntax-built_in","syntax-builtin-name","syntax-bullet","syntax-class","syntax-code","syntax-comment","syntax-default","syntax-deletion","syntax-doctag","syntax-emphasis","syntax-formula","syntax-function","syntax-keyword","syntax-link","syntax-literal","syntax-meta","syntax-meta-keyword","syntax-meta-string","syntax-name","syntax-number","syntax-params","syntax-quote","syntax-regexp","syntax-section","syntax-selector-attr","syntax-selector-class","syntax-selector-id","syntax-selector-pseudo","syntax-selector-tag","syntax-string","syntax-strong","syntax-subst","syntax-symbol","syntax-tag","syntax-template-tag","syntax-template-variable","syntax-title","syntax-type","syntax-variable"];BF=new Set(["muted","tool-output","status-idle","tool","tool-status-ok","tool-status-pending","tool-status-cancelled","tool-status-running","tool-status-fail","plan","plan-done","plan-pending"])});function lp(n,e){return n?{...e??{},[aI]:n}:e}function Ul(n){dI=n?[...n]:[]}function qF(n,e){return e.endsWith("*")?n.startsWith(e.slice(0,-1)):n===e}function zF(){return[...jF,...dI]}function tc(n=process.env){let e=zF(),t={};for(let[r,s]of Object.entries(n))s!==void 0&&(e.some(o=>qF(r,o))||(t[r]=s));return t}var UF,aI,WF,jF,dI,nc=q(()=>{"use strict";UF={herdr:["HERDR_PANE_ID","HERDR_TAB_ID","HERDR_WORKSPACE_ID","HERDR_STARTUP_CWD"],tmux:["TMUX_PANE"],zellij:["ZELLIJ_PANE_ID","ZELLIJ_SESSION_NAME"],wezterm:["WEZTERM_PANE"],kitty:["KITTY_WINDOW_ID"],screen:["STY"],iterm2:["ITERM_SESSION_ID"],paseo:["PASEO_TERMINAL_ID","PASEO_ACTIVITY_TOKEN"],hydra:["HYDRA_TAB_LABEL"]},aI="HYDRA_ACP_SESSION",WF=[aI],jF=[...Object.values(UF).flat(),...WF];dI=[]});import*as yI from"fs";import*as Bn from"fs/promises";import*as ei from"path";import{spawn as wI}from"child_process";import{Readable as QF}from"stream";function Sr(){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 sw(n,e=Sr()){if(e)return n[e]}function ow(n){rc=n??(e=>process.stderr.write(e+`
|
|
26
|
+
`,{encoding:"utf8",mode:384})}var vr=q(()=>{"use strict";rt();go();ke();jd();qd()});function gt(n){if(!Number.isInteger(n)||n<0||n>15)throw new Error(`ansi() takes 0-15, got ${n}`);return{kind:"ansi",index:n}}function Dn(n,e,t){return{kind:"rgb",r:Fy(n),g:Fy(e),b:Fy(t)}}function Zo(n){let e=n.trim().toLowerCase(),t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/.exec(e);if(t){let s=t[1];return s.length===3?Dn(parseInt(s[0]+s[0],16),parseInt(s[1]+s[1],16),parseInt(s[2]+s[2],16)):Dn(parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16))}let r=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/.exec(e);return r?Dn(Number(r[1]),Number(r[2]),Number(r[3])):null}function Rx(n){let e=f=>{let p=[0,95,135,175,215,255],m=0;for(let h=1;h<p.length;h++)Math.abs(p[h]-f)<Math.abs(p[m]-f)&&(m=h);return m},t=[0,95,135,175,215,255],r=e(n.r),s=e(n.g),o=e(n.b),i=16+36*r+6*s+o,a=(t[r]-n.r)**2+(t[s]-n.g)**2+(t[o]-n.b)**2,d=(n.r+n.g+n.b)/3,c=Math.round((d-8)/10);c=Math.max(0,Math.min(23,c));let l=8+c*10;return(l-n.r)**2+(l-n.g)**2+(l-n.b)**2<a?232+c:i}function mF(n){let e=(n.r+n.g+n.b)/3;return e<=4?16:e>=247?231:232+Math.max(0,Math.min(23,Math.round((e-8)/10)))}function Ax(n){if(n===void 0||n.size===0){Ol=void 0;return}let e=new Map;for(let[t,r]of n)r.kind==="rgb"&&e.set(t,r);Ol=e.size>0?e:void 0}function By(n){let e=Ol?.get(n);if(e!==void 0)return e;let[t,r,s]=Dy[n];return{kind:"rgb",r:t,g:r,b:s}}function Tx(n,e){let t=By(n);return(t.r-e.r)**2+(t.g-e.g)**2+(t.b-e.b)**2}function Ex(n){let e=gF;if(Ol!==void 0){let s=Dy.map((o,i)=>i).filter(o=>{let i=By(o);return Math.max(i.r,i.g,i.b)-Math.min(i.r,i.g,i.b)<=Ly});s.length>0&&(e=s)}let t=e[0],r=1/0;for(let s of e){let o=Tx(s,n);o<r&&(r=o,t=s)}return t}function Px(n){let e=Math.max(n.r,n.g,n.b),t=Math.min(n.r,n.g,n.b);if(e-t<=Ly)return Ex(n);if(Ol!==void 0){let o=Dy.map((i,a)=>a).filter(i=>{let a=By(i);return Math.max(a.r,a.g,a.b)-Math.min(a.r,a.g,a.b)>Ly});if(o.length>0){let i=o[0],a=1/0;for(let d of o){let c=Tx(d,n);c<a&&(a=c,i=d)}return i}}let r=(e+t)/2,s=(n.r>=r?1:0)|(n.g>=r?2:0)|(n.b>=r?4:0);return e>=yF?s+8:s}function wF(n,e){let t=r=>String(r<8?30+r:90+(r-8));return n.kind==="ansi"?t(n.index):e==="truecolor"?`38;2;${n.r};${n.g};${n.b}`:e==="ansi256"?`38;5;${Rx(n)}`:t(Px(n))}function bF(n,e,t=!1){let r=s=>String(s<8?40+s:100+(s-8));return n.kind==="ansi"?r(n.index):e==="truecolor"?`48;2;${n.r};${n.g};${n.b}`:e==="ansi256"?`48;5;${t?mF(n):Rx(n)}`:r(t?Ex(n):Px(n))}function Ny(n){if(n.kind==="ansi")return null;let e=t=>{let r=t/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4};return .2126*e(n.r)+.7152*e(n.g)+.0722*e(n.b)}function Jd(n,e=!0){let t=Ny(n);return t===null?e:t<kF}function Wy(n,e){let t=Ny(n),r=Ny(e);return t===null||r===null?null:(Math.max(t,r)+.05)/(Math.min(t,r)+.05)}function vF(n,e){return n.kind==="ansi"?n:Dn(n.r+(255-n.r)*e,n.g+(255-n.g)*e,n.b+(255-n.b)*e)}function SF(n,e){return n.kind==="ansi"?n:Dn(n.r*(1-e),n.g*(1-e),n.b*(1-e))}function Vd(n,e,t){if(n.kind==="ansi")return n;let r=s=>Jd(n)?vF(n,s):SF(n,s);if(t===void 0)return r(e);for(let s=e;s>.005;s-=.01){let o=r(s),i=Wy(o,t);if(i===null||i>=xF)return o}return n}var Fy,op,Dy,gF,Ly,yF,Ol,Hy,ra,Mx,Uy,kF,xF,Yd=q(()=>{"use strict";Fy=n=>Math.max(0,Math.min(255,Math.round(n)));op="\x1B[";Dy=[[0,0,0],[128,0,0],[0,128,0],[128,128,0],[0,0,128],[128,0,128],[0,128,128],[192,192,192],[128,128,128],[255,0,0],[0,255,0],[255,255,0],[0,0,255],[255,0,255],[0,255,255],[255,255,255]],gF=[0,8,7,15],Ly=24,yF=170;Hy=`${op}39m`,ra=`${op}49m`,Mx=(n,e)=>`${op}${wF(n,e)}m`,Uy=(n,e,t=!1)=>`${op}${bF(n,e,t)}m`;kF=.179;xF=4});function _x(n){let e=n.NO_COLOR;return e!==void 0&&e!==""}function IF(n){let e=n.FORCE_COLOR;if(e!==void 0)switch(e){case"0":case"false":return"none";case"1":return"ansi16";case"2":return"ansi256";case"3":return"truecolor";default:return}}function CF(n){let e=n.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"}function jy(n){let e=(n.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return"truecolor";let t=(n.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("direct")?"truecolor":t.includes("256")?"ansi256":"ansi16"}function Fl(n=process.stdout,e=process.env){if(_x(e))return"none";let t=IF(e);return t!==void 0?t:CF(e)?jy(e):(e.TERM??"").toLowerCase()==="dumb"||n.isTTY!==!0?"none":jy(e)}function $x(n=process.stdout,e=process.env){return Fl(n,e)!=="none"}function RF(n){return Ox(n)?(n.TERM??"").toLowerCase().startsWith("screen"):!1}function Ox(n){return n.TMUX!==void 0&&n.TMUX!==""}function Qd(n,e=process.env){if(_x(e))return"none";let t=n?.esc,r=l=>l!==void 0&&!l.na&&!l.fb,s=r(t?.color24bits)?"truecolor":r(t?.color256)?"ansi256":"ansi16",o=t?.color256?.na===!0?"ansi16":"truecolor",i=jy(e),a=i==="truecolor"&&RF(e)||Ox(e)&&i==="ansi16"?"ansi256":i,d=["none","ansi16","ansi256","truecolor"],c=l=>d.indexOf(l);return d[Math.min(Math.max(c(s),c(a)),c(o))]}function Fx(n=process.env){let e=n.COLORFGBG;if(e===void 0||e==="")return;let t=e.split(";").pop()?.trim()??"";if(!/^\d+$/.test(t))return;let r=Number(t);if(!(r>15))return r<=6||r===8?"dark":"light"}var sa=q(()=>{"use strict"});function TF(n,e){let t=`${Ms}49m`;if(e==="truecolor")return{open:`${Ms}48;2;${n};${n};${n}m`,close:t};let r=Math.round(n*25/255),s=r===0?16:r===25?231:r+231;return{open:`${Ms}48;5;${s}m`,close:t}}function Hx(){return Ie.fg===void 0?Bx:void 0}function Ux(){return Dx??Ie.bg}function Wx(){let n=Ux();if(n===void 0)return EF;let e=Hx();return{user:Vd(n,Ll.user,e),code:Vd(n,Ll.code,e),hoverThought:Vd(n,Ll.hoverThought,e),hoverCode:Vd(n,Ll.hoverCode,e)}}function qy(n,e){return Ze(MF(n,e))}function MF(n,e){if(n.kind!=="rgb")return e;let t=[Ie.bg,Ie.fg,e].filter(i=>i!==void 0),r=i=>{let a=e,d=-1;for(let c of i){let l=Wy(n,c)??-1;l>d&&(d=l,a=c)}return{color:a,ratio:d}},s=r(t);if(s.ratio>=_F)return s.color;let o=r([...t,Dn(0,0,0),Dn(255,255,255)]);return o.ratio>s.ratio?o.color:s.color}function dp(){return{fg:Ie.fg===void 0?[]:[Ze(Ie.fg)],fgStrong:[Ze(Ie.brightWhite)],muted:Ie.fg===void 0?[ip]:[ip,Ze(Ie.brightBlack)],subtle:[Ze(Ie.brightBlack)],emphasis:[Ky],active:[Ze(Ie.brightYellow)],warn:[Ze(Ie.yellow)],ok:[Ze(Ie.green)],error:[Ze(Ie.brightRed)],errorSoft:[Ze(Ie.red)],cold:[Ze(Ie.brightMagenta)],gitStaged:[Ze(Ie.green)],gitDirty:[Ze(Ie.brightBlue)],gitUntracked:Ie.fg===void 0?[ip]:[ip,Ze(Ie.brightBlack)],accent:[Ze(Ie.brightCyan)],info:[Ze(Ie.cyan)],reference:[Ze(Ie.brightBlue)],focus:[Ze(Ie.brightBlue)],selectionBand:[Ps(Ie.blue)],selection:[Ps(Ie.blue),qy(Ie.blue,Ie.brightWhite)],cursor:[Ps(Ie.white)],promptCursor:[Ps(Ie.brightYellow)],match:[Ps(Ie.brightYellow),qy(Ie.brightYellow,Ie.black)],matchActive:[Ps(Ie.red),qy(Ie.red,Ie.brightWhite)],invert:[OF],codeText:[Ze(Ie.white)],syntaxKeyword:[Ze(Ie.brightBlue)],syntaxType:[Ze(Ie.brightCyan)],syntaxBuiltin:[Ze(Ie.cyan)],syntaxLiteral:[Ze(Ie.blue)],syntaxNumber:[Ze(Ie.brightGreen)],syntaxString:[Ze(Ie.yellow)],syntaxRegexp:[Ze(Ie.red)],syntaxComment:[Ze(Ie.brightBlack)],syntaxClass:[Ze(Ie.brightYellow)],syntaxMeta:[Ze(Ie.magenta)],syntaxVariable:[Ze(Ie.white)],diffAdded:[Ze(Ie.brightGreen)],diffRemoved:[Ze(Ie.brightRed)],syntaxDoctag:[Ze(Ie.green)],syntaxEmphasis:[FF],syntaxStrong:[Ky],syntaxLink:[LF]}}function jx(n,e){let t=!1,r=!1,s=n.map(o=>o.kind==="fg"&&e.fg!==void 0?(t=!0,Ze(e.fg)):o.kind==="bg"&&e.bg!==void 0?(r=!0,Ps(e.bg)):(o.kind==="fg"&&(t=!0),o.kind==="bg"&&(r=!0),o));return e.fg!==void 0&&!t&&s.push(Ze(e.fg)),e.bg!==void 0&&!r&&s.unshift(Ps(e.bg)),s}function qx(n){return n.some(e=>e.kind==="fg")||!n.some(e=>e.kind==="bg")}function Kx(n){if(Object.keys(Gy).length===0)return n;let e={...n};for(let[t,r]of Object.entries(Gy))r===void 0||e[t]===void 0||(e[t]=jx(e[t],r));return e}function Gx(n){n!==Dl&&(Dl=n,_s=Yy(),ap=void 0,oa={prose:Qy(),thought:Xy(),revision:oa.revision+1})}function Xd(n){return n.map(e=>e.open(Dl)).join("")}function Yy(){let n=Xd(z.accent);return{code:n,codeQuiet:Xd(z.info),link:n+Zd,thoughtBase:Xd(z.subtle)}}function Qy(){return{codeOpen:_s.code,linkOpen:_s.link,base:Xd(z.fg)}}function Xy(){return{codeOpen:_s.codeQuiet,linkOpen:_s.link,base:_s.thoughtBase}}function Jx(){return oa.prose}function Vx(){return oa.thought}function cp(n){return{codeOpen:n==="heading-2"?Xd(z.active):_s.code,linkOpen:_s.link,base:ec(n,Dl).open}}function Lx(n,e){return{open:n.map(t=>t.open(e)).join(""),close:n.slice().reverse().map(t=>t.close).join("")}}function Yx(){return{user:{band:Nl.user,layers:[...z.emphasis]},agent:{layers:[...z.fg],inlineSgr:!0},thought:{layers:[...z.subtle],inlineSgr:!0},tool:{layers:[...z.reference]},"tool-status-ok":{layers:[...z.muted]},"tool-status-pending":{layers:[...z.muted]},"tool-status-cancelled":{layers:[...z.muted]},"tool-status-running":{layers:[...z.active]},"tool-status-fail":{layers:[...z.emphasis,...z.errorSoft]},plan:{layers:[...z.active],inlineSgr:!0},"plan-done":{layers:[...z.ok],inlineSgr:!0},"plan-pending":{layers:[...z.muted],inlineSgr:!0},"local-heading":{layers:[...z.emphasis]},"local-item":{layers:[...z.info]},notice:{layers:[...z.info]},"notice-ok":{layers:[...z.ok]},"notice-error":{layers:[...z.errorSoft]},metric:{layers:[...z.info]},muted:{layers:[...z.muted]},"tool-output":{layers:[...z.muted]},"status-ready":{layers:[...z.fg]},"status-active":{layers:[...z.active]},"status-blocked":{layers:[...z.warn]},"status-queued":{layers:[...z.active]},"status-alert":{layers:[...z.error]},"status-cold":{layers:[...z.cold]},"git-staged":{layers:[...z.gitStaged]},"git-dirty":{layers:[...z.gitDirty]},"git-untracked":{layers:[...z.gitUntracked]},"file-path":{layers:[...z.reference]},"meter-fill":{layers:[...z.ok]},"meter-warn":{layers:[...z.emphasis,...z.errorSoft]},"sidebar-rule":{layers:[...z.muted]},"sidebar-title":{layers:[...z.muted]},"sidebar-value":{layers:[...z.fg]},"status-idle":{layers:[...z.muted]},"box-border":{layers:[...z.muted]},"box-border-focused":{layers:[...z.focus]},"box-border-hover":{layers:[...z.muted,...z.emphasis]},"box-border-focused-hover":{layers:[...z.focus,...z.emphasis]},"box-title":{layers:[...z.accent]},"modal-title":{layers:[...z.fgStrong,...z.emphasis]},"modal-label":{layers:[...z.muted]},"modal-value":{layers:[...z.fgStrong]},"modal-note":{layers:[...z.active]},"modal-error":{layers:[...z.error]},"modal-hint":{layers:[...z.muted]},"modal-status":{layers:[...z.muted]},"modal-key":{layers:[...z.accent]},"input-error":{layers:[...z.errorSoft]},"input-cursor":{layers:[...z.cursor]},"prompt-text":{layers:[...z.active]},"prompt-cursor":{layers:[...z.promptCursor]},"prompt-destructive":{layers:[...z.error]},"list-selected":{layers:[...z.selection]},"list-description":{layers:[...z.muted]},"list-header":{layers:[...z.muted]},"modal-option":{layers:[...z.muted]},"modal-option-selected":{layers:[...z.active]},"bar-text":{layers:[...z.emphasis]},"bar-indicator":{layers:[...z.accent]},rule:{layers:[...z.emphasis]},"rule-pad":{layers:[...z.muted]},"rule-meta":{layers:[...z.muted]},"hint-hover":{layers:[...z.fg]},"completion-name":{layers:[...z.accent]},"completion-desc":{layers:[...z.muted]},attachment:{layers:[...z.warn]},"queue-row":{layers:[...z.selection]},"queue-cursor":{layers:[...z.selection,Ky]},"queue-blank":{layers:[...z.selectionBand]},"composer-gutter":{layers:[...z.fgStrong]},"composer-inactive":{layers:[...z.muted]},"composer-continuation":{layers:[...z.muted]},"syntax-addition":{layers:[...z.diffAdded]},"syntax-attr":{layers:[...z.syntaxBuiltin]},"syntax-attribute":{layers:[...z.syntaxBuiltin]},"syntax-built_in":{layers:[...z.syntaxBuiltin]},"syntax-builtin-name":{layers:[...z.fg]},"syntax-bullet":{layers:[...z.fg]},"syntax-class":{layers:[...z.syntaxClass]},"syntax-code":{layers:[...z.fg]},"syntax-comment":{layers:[...z.syntaxComment]},"syntax-default":{layers:[...z.fg]},"syntax-deletion":{layers:[...z.diffRemoved]},"syntax-doctag":{layers:[...z.syntaxDoctag]},"syntax-emphasis":{layers:[...z.syntaxEmphasis]},"syntax-formula":{layers:[...z.fg]},"syntax-function":{layers:[...z.syntaxString]},"syntax-keyword":{layers:[...z.syntaxKeyword]},"syntax-link":{layers:[...z.syntaxLink]},"syntax-literal":{layers:[...z.syntaxLiteral]},"syntax-meta":{layers:[...z.syntaxMeta]},"syntax-meta-keyword":{layers:[...z.fg]},"syntax-meta-string":{layers:[...z.fg]},"syntax-name":{layers:[...z.syntaxType]},"syntax-number":{layers:[...z.syntaxNumber]},"syntax-params":{layers:[...z.syntaxVariable]},"syntax-quote":{layers:[...z.fg]},"syntax-regexp":{layers:[...z.syntaxRegexp]},"syntax-section":{layers:[...z.syntaxBuiltin]},"syntax-selector-attr":{layers:[...z.fg]},"syntax-selector-class":{layers:[...z.fg]},"syntax-selector-id":{layers:[...z.fg]},"syntax-selector-pseudo":{layers:[...z.fg]},"syntax-selector-tag":{layers:[...z.fg]},"syntax-string":{layers:[...z.syntaxString]},"syntax-strong":{layers:[...z.syntaxStrong]},"syntax-subst":{layers:[...z.fg]},"syntax-symbol":{layers:[...z.syntaxMeta]},"syntax-tag":{layers:[...z.syntaxBuiltin]},"syntax-template-tag":{layers:[...z.fg]},"syntax-template-variable":{layers:[...z.fg]},"syntax-title":{layers:[...z.syntaxString]},"syntax-type":{layers:[...z.syntaxType]},"syntax-variable":{layers:[...z.syntaxVariable]},content:{layers:[...z.fg]},"cli-warn":{layers:[...z.warn]},code:{band:Nl.code,layers:[...z.codeText]},"heading-1":{layers:[...z.emphasis,...z.active],inlineSgr:!0},"heading-2":{layers:[...z.emphasis,...z.accent],inlineSgr:!0},"heading-3":{layers:[...z.emphasis],inlineSgr:!0},"search-highlight":{layers:[...z.match]},"search-highlight-active":{layers:[...z.matchActive]},"selection-highlight":{layers:[...z.invert]}}}function Zy(n,e={}){Ie=n,Gy=e.roles??{},zx=e.elements??{},Dx=e.background,Bx=e.foreground,Nl=Wx(),z=Kx(dp()),_s=Yy(),Hl=Yx(),ap=void 0,oa={prose:Qy(),thought:Xy(),revision:oa.revision+1}}function Qx(){return Object.keys(dp()).sort()}function Xx(){return Object.keys(Hl).sort()}function Zx(n){let t=dp()[n];return t===void 0?!0:qx(t)}function eI(n){let e=Hl[n];return e===void 0||e.band!==void 0?!0:qx(e.layers??[])}function tI(){return oa.revision}function nI(){return ap??=DF(),ap}function Jy(n){return typeof n=="number"?{open:e=>TF(n,e).open,close:ra,kind:"bg"}:$F(n)}function ec(n,e){if(e==="none")return zy;if(n===void 0)return z.fg.length===0?zy:{...Lx(z.fg,e),inlineSgr:!1};let t=Hl[n];if(t===void 0)return zy;let r=[],s=zx[n];return t.band!==void 0&&r.push(s?.bg!==void 0?Ps(s.bg):Jy(t.band)),t.layers&&r.push(...t.layers),s!==void 0&&(r=jx(r,t.band!==void 0?{fg:s.fg}:s)),z.fg.length>0&&!r.some(o=>o.kind==="fg")&&((t.layers??[]).some(i=>i.kind==="bg")||r.push(...z.fg)),{...Lx(r,e),inlineSgr:t.inlineSgr===!0}}function rI(n){return n===void 0?!1:Hl[n]?.inlineSgr===!0}function B(n,e,t){t.length!==0&&n.noFormat(aa(e,t,Qd(n)))}function aa(n,e,t="ansi256"){let r=ec(n,t);return r.open+e+r.close}function DF(){let n=Xd(z.codeText),e={};for(let t of NF){let{open:r,close:s}=ec(t,Dl),o=t.slice(7);if(r===""){e[o]=a=>a;continue}let i=s.split(Hy).join(n);e[o]=a=>r+a+i}return e}function HF(n){let e=Ux();if(e===void 0)return PF;let t=Ps(Vd(e,Ll.hoverRow,Hx()));return{open:t.open(n),close:t.close}}function Nx(n,e){return n.split(ns).join(ns+e)}function sI(n,e){if(n===void 0)return;if(n==="thought"){let s=Jy(Nl.hoverThought).open(e);return{open:s,close:ra,inlineSgr:!0,transform:o=>Nx(o.split(_s.thoughtBase).join(`${Ms}39m`),s)}}if(n==="code")return{open:Jy(Nl.hoverCode).open(e),close:ra,inlineSgr:!1};if(!BF.has(n))return;let t=ec(n,e),r=HF(e);return{open:r.open+t.open,close:t.close+r.close,inlineSgr:t.inlineSgr,transform:t.inlineSgr?s=>Nx(s,r.open):void 0}}var AF,Ms,ia,Ie,Ll,EF,Dx,Bx,PF,Nl,_F,Ze,Ps,$F,Bl,Ky,ip,OF,FF,LF,Gy,zx,z,Dl,ns,Vy,Zd,_s,Hl,oa,ap,zy,NF,BF,Tn=q(()=>{"use strict";Yd();sa();AF="\x1B",Ms=`${AF}[`;ia={black:gt(0),red:gt(1),green:gt(2),yellow:gt(3),blue:gt(4),magenta:gt(5),cyan:gt(6),white:gt(7),brightBlack:gt(8),brightRed:gt(9),brightGreen:gt(10),brightYellow:gt(11),brightBlue:gt(12),brightMagenta:gt(13),brightCyan:gt(14),brightWhite:gt(15)},Ie=ia,Ll={user:.17,code:.11,hoverThought:.1,hoverRow:.19,hoverCode:.2},EF={user:43,code:28,hoverThought:25,hoverCode:48};PF={open:`${Ms}48;5;236m`,close:ra},Nl=Wx();_F=3,Ze=n=>({open:e=>Mx(n,e),close:Hy,kind:"fg"}),Ps=n=>({open:e=>Uy(n,e),close:ra,kind:"bg"}),$F=n=>({open:e=>Uy(n,e,!0),close:ra,kind:"bg"}),Bl=(n,e)=>({open:()=>`${Ms}${n}m`,close:`${Ms}${e}m`,kind:"attr"}),Ky=Bl(1,22),ip=Bl(2,22),OF=Bl(7,27),FF=Bl(3,23),LF=Bl(4,24);Gy={},zx={};z=Kx(dp()),Dl="ansi256";ns=`${Ms}0m`,Vy=`${Ms}1m`,Zd=`${Ms}4m`;_s=Yy();Hl=Yx(),oa={prose:Qy(),thought:Xy(),revision:0};zy={open:"",close:"",inlineSgr:!1};NF=["syntax-addition","syntax-attr","syntax-attribute","syntax-built_in","syntax-builtin-name","syntax-bullet","syntax-class","syntax-code","syntax-comment","syntax-default","syntax-deletion","syntax-doctag","syntax-emphasis","syntax-formula","syntax-function","syntax-keyword","syntax-link","syntax-literal","syntax-meta","syntax-meta-keyword","syntax-meta-string","syntax-name","syntax-number","syntax-params","syntax-quote","syntax-regexp","syntax-section","syntax-selector-attr","syntax-selector-class","syntax-selector-id","syntax-selector-pseudo","syntax-selector-tag","syntax-string","syntax-strong","syntax-subst","syntax-symbol","syntax-tag","syntax-template-tag","syntax-template-variable","syntax-title","syntax-type","syntax-variable"];BF=new Set(["muted","tool-output","status-idle","tool","tool-status-ok","tool-status-pending","tool-status-cancelled","tool-status-running","tool-status-fail","plan","plan-done","plan-pending"])});function lp(n,e){return n?{...e??{},[aI]:n}:e}function Ul(n){dI=n?[...n]:[]}function qF(n,e){return e.endsWith("*")?n.startsWith(e.slice(0,-1)):n===e}function zF(){return[...jF,...dI]}function tc(n=process.env){let e=zF(),t={};for(let[r,s]of Object.entries(n))s!==void 0&&(e.some(o=>qF(r,o))||(t[r]=s));return t}var UF,aI,WF,jF,dI,nc=q(()=>{"use strict";UF={herdr:["HERDR_PANE_ID","HERDR_TAB_ID","HERDR_WORKSPACE_ID","HERDR_STARTUP_CWD"],tmux:["TMUX_PANE"],zellij:["ZELLIJ_PANE_ID","ZELLIJ_SESSION_NAME"],wezterm:["WEZTERM_PANE"],kitty:["KITTY_WINDOW_ID"],screen:["STY"],iterm2:["ITERM_SESSION_ID"],paseo:["PASEO_TERMINAL_ID","PASEO_ACTIVITY_TOKEN"],hydra:["HYDRA_TAB_LABEL"]},aI="HYDRA_ACP_SESSION",WF=[aI],jF=[...Object.values(UF).flat(),...WF];dI=[]});import*as yI from"fs";import*as Bn from"fs/promises";import*as ei from"path";import{spawn as wI}from"child_process";import{Readable as QF}from"stream";function Sr(){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 sw(n,e=Sr()){if(e)return n[e]}function ow(n){rc=n??(e=>process.stderr.write(e+`
|
|
27
27
|
`))}async function bI(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${Sr()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=Sr();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=D.agentInstallDir(n.agentId,e,n.version),r=ei.resolve(t,n.target.cmd);if(await rw(r))return r;if(await XF({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await rw(r))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await Bn.chmod(r,493).catch(()=>{}),r}async function XF(n){await Bn.mkdir(ei.dirname(n.installDir),{recursive:!0});let e=await Bn.mkdtemp(`${n.installDir}.partial-`);try{rc(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await ZF({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});rc(`hydra-acp: extracting ${n.agentId}`),sc(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await tL(t,e),await Bn.unlink(t).catch(()=>{});try{await Bn.rename(e,n.installDir)}catch(r){let s=r;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await rw(n.installDir)){await Bn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),sc(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw r}rc(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),sc(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Bn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function sc(n,e){if(n)try{n(e)}catch{}}async function ZF(n){let e=eL(n.url),t=ei.join(n.dir,e),r=await fetch(n.url,{redirect:"follow"});if(!r.ok||!r.body)throw new Error(`Failed to download ${n.url}: HTTP ${r.status} ${r.statusText}`);let s=Number(r.headers.get("content-length")??"0"),o=yI.createWriteStream(t),i=QF.fromWeb(r.body);sc(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:s});let a=0,d=Date.now(),c=0,l=2e3,u=150;return i.on("data",f=>{a+=f.length;let p=Date.now();p-c>=u&&(c=p,sc(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:s})),p-d>=l&&(d=p,rc(gI(n.agentId,a,s)))}),await new Promise((f,p)=>{i.on("error",p),o.on("error",p),o.on("finish",()=>f()),i.pipe(o)}),rc(gI(n.agentId,a,s,!0)),sc(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:s}),t}function gI(n,e,t,r=!1){let s=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${r?"downloaded":"downloading"} ${n} ${s}/${i} MB (${a}%)`}return`hydra-acp: ${r?"downloaded":"downloading"} ${n} ${s} MB`}function eL(n){let e=new URL(n);return ei.posix.basename(e.pathname)||"archive"}async function tL(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await nw("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await nL("unzip")){await nw("unzip",["-q",n,"-d",e]);return}await nw("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function nw(n,e){return new Promise((t,r)=>{let s=wI(n,e,{stdio:["ignore","ignore","inherit"]});s.on("error",r),s.on("exit",(o,i)=>{if(o===0){t();return}r(new Error(`${n} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function nL(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",r=wI(t,[n],{stdio:"ignore"});r.on("error",()=>e(!1)),r.on("exit",s=>e(s===0))})}async function rw(n){try{return await Bn.access(n),!0}catch{return!1}}var rc,oc=q(()=>{"use strict";ke();rc=n=>{process.stderr.write(n+`
|
|
28
28
|
`)}});import{statSync as rL}from"fs";import{delimiter as sL,join as oL}from"path";function kI(n){try{return rL(n).isFile()}catch{return!1}}function aL(n){let e=(n.PATHEXT??iL).split(";").map(r=>r.trim()).filter(r=>r.length>0),t=[];for(let r of e)for(let s of[r,r.toLowerCase(),r.toUpperCase()])t.includes(s)||t.push(s);return t}function dL(n,e){let t=n.toLowerCase();return e.some(r=>t.endsWith(r.toLowerCase()))}function cL(n,e={}){if((e.platform??process.platform)!=="win32")return n;let r=e.env??process.env,s=aL(r);if(dL(n,s))return n;if(/[\\/]/.test(n)){for(let i of s){let a=n+i;if(kI(a))return a}return n}let o=r.PATH??r.Path??"";for(let i of o.split(sL).filter(a=>a.length>0))for(let a of s){let d=oL(i,n+a);if(kI(d))return d}return n}function vI(n){if(lL.test(n))throw new Error(`cannot pass ${JSON.stringify(n)} through cmd.exe: it contains a quote, a percent sign, or a newline, none of which can be escaped unambiguously`);return/[\s&|<>^()]/.test(n)?`"${n}"`:n}function ic(n,e,t={}){let r=t.platform??process.platform,s=cL(n,t);return r!=="win32"||!/\.(cmd|bat)$/i.test(s)?{command:s,args:[...e],shell:!1}:{command:vI(s),args:e.map(vI),shell:!0}}var iL,lL,pp=q(()=>{"use strict";iL=".COM;.EXE;.BAT;.CMD";lL=/["%\r\n]/});import*as or from"fs/promises";import*as $s from"path";import{delimiter as uL}from"path";import{spawn as fL}from"child_process";function dw(n){aw=n??(e=>process.stderr.write(e+`
|
|
29
29
|
`))}async function xI(n){let e=Sr();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=D.agentNpmInstallDir(n.agentId,e,n.version),r=yL(n.packageSpec),s=wL(r),o={installDir:t,packageName:r,hint:n.bin,basename:s},i=$s.join(t,"node_modules",".bin",n.bin);if(await da(i))return i;if(await da(t)){let u=await SI(o);if(u)return u.binPath}await pL({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await SI(o);if(a)return a.binPath;let d=await CI(t,r),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[s]:[],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 pL(n){await or.mkdir($s.dirname(n.installDir),{recursive:!0});let e=await or.mkdtemp(`${n.installDir}.partial-`);try{aw(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),iw(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await gL({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await or.rename(e,n.installDir)}catch(t){let r=t;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await da(n.installDir)){await or.rm(e,{recursive:!0,force:!0}).catch(()=>{}),iw(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}aw(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),iw(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await or.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function iw(n,e){if(n)try{n(e)}catch{}}function gL(n){return II(n,0)}async function II(n,e){try{await new Promise((t,r)=>{let s=n.registry?["--registry",n.registry]:[],o=ic("npm",["install","--no-audit","--no-fund","--silent",...s,n.packageSpec]),i;try{i=fL(o.command,o.args,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:o.shell,windowsHide:!0})}catch(d){r(d);return}let a="";i.stdout?.on("data",d=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",d=>{a=(a+d).slice(-4096)}),i.on("error",d=>{if(d.code==="ENOENT"){let l=(process.env.PATH??process.env.Path??"").split(uL).filter(u=>u.length>0);r(new Error(`npm not found on PATH: tried to run ${JSON.stringify(o.command)}${o.shell?" through a shell":""} against ${l.length} PATH entries. Install Node.js / npm, or use a binary-distributed agent.`));return}r(d)}),i.on("exit",(d,c)=>{if(d===0){t();return}let l=d!==null?`exit code ${d}`:`signal ${c??"unknown"}`,u=a.trim();r(new Error(u?`npm install ${n.packageSpec} failed (${l})
|
|
30
30
|
stderr: ${u}`:`npm install ${n.packageSpec} failed (${l})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<hL)return await new Promise(s=>setTimeout(s,mL*(e+1))),II(n,e+1);throw t}}function yL(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let s=n.slice(t+1).indexOf("@");return s===-1?n:n.slice(0,t+1+s)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function wL(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function CI(n,e){let t=$s.join(n,"node_modules",e,"package.json");try{let r=await or.readFile(t,"utf8"),s=JSON.parse(r);return typeof s.bin=="string"||typeof s.bin=="object"&&s.bin!==null&&!Array.isArray(s.bin)?s.bin:void 0}catch{return}}async function SI(n){let e=$s.join(n.installDir,"node_modules",".bin"),t=$s.join(e,n.hint);if(await da(t))return{binName:n.hint,binPath:t};let r=await CI(n.installDir,n.packageName);if(typeof r=="object"&&r!==null){let s=Object.keys(r);if(s.length===1){let o=s[0],i=$s.join(e,o);if(await da(i))return{binName:o,binPath:i}}else if(s.length>1){for(let o of[n.hint,n.basename])if(s.includes(o)){let i=$s.join(e,o);if(await da(i))return{binName:o,binPath:i}}}}if(n.basename!==n.hint){let s=$s.join(e,n.basename);if(await da(s))return{binName:n.basename,binPath:s}}}async function da(n){try{return await or.access(n),!0}catch{return!1}}var aw,hL,mL,cw=q(()=>{"use strict";ke();oc();pp();aw=n=>{process.stderr.write(n+`
|
|
31
|
-
`)};hL=5,mL=25});import*as EI from"fs/promises";import*as mp from"path";import{z as Ce}from"zod";function PI(n){return n.installId??n.id}function uw(n){let e=n.extendsChain;return e&&e.length>0?e[e.length-1]:n.id}function xr(n,e){if(n)for(let t of e.extendsChain??[e.id]){let r=n[t];if(r!==void 0)return{value:r,from:t}}}function MI(n){return n&&Object.fromEntries(Object.entries(n).map(([e,t])=>[e,mt(t)]))}function lw(n,e){return{id:n,name:e.name??n,description:e.description,version:"local",distribution:{exec:{command:mt(e.command??n),args:e.args?.map(mt),env:MI(e.env)}}}}function _I(n,e){let t=e.args?.map(mt),r=MI(e.env),s=o=>({...o,...t?{args:t}:{},...r?{env:{...o.env,...r}}:{}});return{...n.npx?{npx:s(n.npx)}:{},...n.uvx?{uvx:s(n.uvx)}:{},...n.exec?{exec:s(n.exec)}:{},...n.binary?{binary:Object.fromEntries(Object.entries(n.binary).map(([o,i])=>[o,i&&s(i)]))}:{}}}function RL(n,e){let t=r=>({...r,args:[...r.args??[],...e]});return{...n.npx?{npx:t(n.npx)}:{},...n.uvx?{uvx:t(n.uvx)}:{},...n.exec?{exec:t(n.exec)}:{},...n.binary?{binary:Object.fromEntries(Object.entries(n.binary).map(([r,s])=>[r,s&&t(s)]))}:{}}}function AL(n,e,t){let r=e.command!==void 0;return{...t,id:n,name:e.name??t.name,description:e.description??t.description,version:r?"local":t.version,distribution:r?lw(n,e).distribution:_I(t.distribution,e),installId:r?n:t.installId??t.id,extendsChain:[n,...t.extendsChain??[t.id]]}}function TL(n){let e=n.lastIndexOf("@"),r=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return r.length>0?`pin-${r}`:"pinned"}function fw(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),r=t===-1?e:e.slice(t+1),s=r.lastIndexOf("@");return s<=0?r:r.slice(0,s)}async function dc(n){let e=typeof n.resolvedLocalAgents=="function"?await n.resolvedLocalAgents():typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let r=new Set(e.map(i=>i.id)),s=[...e,...t.agents.filter(i=>!r.has(i.id))],o=await Promise.all(s.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await pw(i),...i.extendsChain?{extendsChain:i.extendsChain}:{},source:r.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function pw(n){let e=Sr();if(!e)return"no";let t=n.version??"current",r=PI(n);if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=sw(n.distribution.binary,e);if(s?.cmd){let o=mp.resolve(D.agentInstallDir(r,e,t),s.cmd);if(await TI(o))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,o=s.bin??fw(n)??s.package,i=D.agentNpmInstallDir(r,e,t),a=mp.join(i,"node_modules",".bin",o);if(await TI(a))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function TI(n){try{return await EI.access(n),!0}catch{return!1}}async function Ir(n,e=[],t={}){let r=n.version??"current",s=PI(n);if(n.distribution.npx){let o=n.distribution.npx,i=e.length>0?e:o.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",o.package,...i],env:o.env??{},version:r,installId:s};let a=o.bin??fw(n)??o.package,d=t.onInstallProgress;return{command:await xI({agentId:s,version:r,packageSpec:o.package,bin:a,registry:t.npmRegistry,onProgress:d?l=>d({source:"npm",...l}):void 0}),args:i,env:o.env??{},version:r,installId:s}}if(n.distribution.binary){let o=sw(n.distribution.binary);if(!o)throw new Error(`Agent ${n.id} has no binary distribution for ${Sr()??"this platform"}.`);let i=t.onInstallProgress,a=await bI({agentId:s,version:r,target:o,onProgress:i?c=>i({source:"binary",...c}):void 0}),d=e.length>0?e:o.args??[];return{command:a,args:d,env:o.env??{},version:r,installId:s}}if(n.distribution.uvx){let o=n.distribution.uvx,i=e.length>0?e:o.args??[];return{command:"uvx",args:[o.package,...i],env:o.env??{},version:r,installId:s}}if(n.distribution.exec){let o=n.distribution.exec,i=e.length>0?e:o.args??[];return{command:o.command,args:i,env:o.env??{},version:r,installId:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}var bL,ac,kL,vL,SL,xL,IL,CL,RI,AI,hp,Os=q(()=>{"use strict";ke();rt();es();oc();cw();bL=Ce.object({package:Ce.string(),bin:Ce.string().optional(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),ac=Ce.object({archive:Ce.string().url().optional(),cmd:Ce.string().optional(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),kL=Ce.object({"darwin-aarch64":ac.optional(),"darwin-x86_64":ac.optional(),"linux-aarch64":ac.optional(),"linux-x86_64":ac.optional(),"windows-x86_64":ac.optional(),"windows-aarch64":ac.optional()}),vL=Ce.object({package:Ce.string(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),SL=Ce.object({command:Ce.string(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),xL=Ce.object({command:Ce.string().optional(),url:Ce.string().optional(),description:Ce.string().optional()}),IL=Ce.object({npx:bL.optional(),binary:kL.optional(),uvx:vL.optional(),exec:SL.optional()}),CL=Ce.object({id:Ce.string(),name:Ce.string(),version:Ce.string().optional(),description:Ce.string().optional(),authors:Ce.array(Ce.string()).optional(),license:Ce.string().optional(),icon:Ce.string().optional(),repository:Ce.string().optional(),website:Ce.string().optional(),distribution:IL,onboarding:xL.optional(),requiredEnv:Ce.array(Ce.string().min(1)).optional()}),RI=8;AI=Ce.object({version:Ce.string(),agents:Ce.array(CL),extensions:Ce.array(Ce.unknown()).optional()}),hp=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){let r=this.options.onStaleFallback;if(r)try{r(t,Date.now()-e.fetchedAt)}catch{}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}setConfig(e){this.config=e}async getAgent(e){return this.resolveAgent(e,[])}async resolveAgent(e,t){let r=this.findLocalDef(e);if(r){if(r.def.extends===void 0)return{...lw(r.id,r.def),extendsChain:[r.id]};if(t.includes(r.id))throw new Error(`agent ${r.id}: extends cycle (${[...t,r.id].join(" -> ")})`);if(t.length+1>=RI)throw new Error(`agent ${r.id}: extends chain deeper than ${RI} (${[...t,r.id].join(" -> ")})`);let c=await this.resolveAgent(r.def.extends,[...t,r.id]);if(!c)throw new Error(`agent ${r.id}: extends ${JSON.stringify(r.def.extends)}, which is not a known agent`);return this.applyOverride(AL(r.id,r.def,c))}let s=await this.load(),o=s.agents.find(c=>c.id===e);if(o)return this.applyOverride(o);let i=s.agents.find(c=>fw(c)===e);if(i)return this.applyOverride(i);let a=e.toLowerCase(),d=s.agents.find(c=>c.id.toLowerCase()===`${a}-acp`);if(d)return this.applyOverride(d);if(a.length>0){let c=s.agents.filter(l=>l.id.toLowerCase().startsWith(a));if(c.length===1)return this.applyOverride(c[0])}}findLocalDef(e){let t=this.config.agents??{},r=t[e];if(r)return{id:e,def:r};let s=e.toLowerCase();for(let[o,i]of Object.entries(t))if(o.toLowerCase()===`${s}-acp`)return{id:o,def:i}}localAgents(){return Object.entries(this.config.agents??{}).filter(([,e])=>e.extends===void 0).map(([e,t])=>lw(e,t))}async resolvedLocalAgents(){let e=[];for(let t of Object.keys(this.config.agents??{}))try{let r=await this.resolveAgent(t,[]);r&&e.push(r)}catch(r){this.options.onResolveError?.(t,r)}return e}applyOverride(e){let t=e.extendsChain?e:{...e,extendsChain:[e.id]},r=this.config.agentOverrides?.[t.id];if(!r)return t;let s=t.distribution,o=t.version,i=t.installId;return r.packageSpec&&s.npx&&(o=TL(r.packageSpec),i=t.id,s={...s,npx:{...s.npx,package:r.packageSpec}}),r.extraArgs?.length&&(s=RL(s,r.extraArgs)),r.env&&Object.keys(r.env).length>0&&(s=_I(s,{env:r.env})),s===t.distribution?t:{...t,version:o,installId:i,distribution:s}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,r=this.config.registry.ttlHours*60*60*1e3;return t<r}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(),r=AI.parse(t),s={fetchedAt:Date.now(),raw:t,data:r},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(r)).catch(()=>{}),s}async readDiskCache(){let e=await jt(D.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=AI.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await nn(D.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}}});var G,jl=q(()=>{"use strict";G={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 yt}from"zod";var $I,EL,OI,FI,LI,hw=q(()=>{"use strict";$I=yt.object({protocolVersion:yt.number().optional(),clientCapabilities:yt.record(yt.unknown()).optional(),clientInfo:yt.object({name:yt.string(),version:yt.string().optional()}).optional()}),EL=yt.enum(["full","pending_only","none","after_message"]),OI=yt.object({cwd:yt.string(),mcpServers:yt.array(yt.unknown()).optional(),_meta:yt.record(yt.unknown()).optional()}),FI=yt.object({upstreamSessionId:yt.string(),agentId:yt.string(),cwd:yt.string(),title:yt.string().optional(),agentArgs:yt.array(yt.string()).optional()}),LI=yt.object({sessionId:yt.string(),historyPolicy:EL.default("full"),afterMessageId:yt.string().optional(),afterSeq:yt.number().optional(),clientId:yt.string().optional(),clientInfo:yt.object({name:yt.string(),version:yt.string().optional()}).optional(),_meta:yt.record(yt.unknown()).optional()})});import{z as ye}from"zod";function gp(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.workspace!==void 0&&(t.workspaceInfo=n.workspace),n.workspaceError!==void 0&&(t.workspaceError=n.workspaceError),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.armedTasks!==void 0&&(t.armedTasks=n.armedTasks),n.armedSince!==void 0&&(t.armedSince=n.armedSince),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),e.armedTaskList!==void 0&&(t.armedTaskList=e.armedTaskList)),t}function BI(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ql(n._meta,gp(n))};return n.title!==void 0&&(e.title=n.title),e}var NI,DI,mw,BV,PL,HV,gw=q(()=>{"use strict";cc();NI=ye.object({sessionId:ye.string()}),DI=ye.object({cwd:ye.string().optional(),cursor:ye.string().optional()}),mw=ye.object({used:ye.number().optional(),size:ye.number().optional(),costAmount:ye.number().optional(),costCurrency:ye.string().optional()}),BV=ye.object({sessionId:ye.string(),upstreamSessionId:ye.string().optional(),cwd:ye.string(),workspace:ye.object({path:ye.string(),sourceCwd:ye.string(),label:ye.string(),provider:ye.string(),snapshot:ye.string().optional(),vcs:ye.record(ye.string(),ye.string()).optional()}).optional(),workspaceError:ye.string().optional(),title:ye.string().optional(),agentId:ye.string().optional(),currentModel:ye.string().optional(),currentUsage:mw.optional(),importedFromMachine:ye.string().optional(),importedFromUpstreamSessionId:ye.string().optional(),parentSessionId:ye.string().optional(),forkedFromSessionId:ye.string().optional(),forkedFromMessageId:ye.string().optional(),originatingClient:ye.object({name:ye.string(),version:ye.string().optional()}).optional(),interactive:ye.boolean().optional(),priority:ye.number().int().nonnegative().optional(),updatedAt:ye.string(),attachedClients:ye.number().int().nonnegative(),status:ye.enum(["warm","cold"]).default("warm"),busy:ye.boolean().default(!1),awaitingInput:ye.boolean().default(!1),turnStartedAt:ye.number().optional(),armedTasks:ye.number().int().nonnegative().optional(),armedSince:ye.number().int().positive().optional(),compactionState:ye.any().optional(),agentPid:ye.number().int().positive().optional(),forkSynthesisState:ye.enum(["running","failed"]).optional(),_meta:ye.record(ye.unknown()).optional()}),PL=ye.object({sessionId:ye.string(),cwd:ye.string(),title:ye.string().optional(),updatedAt:ye.string().optional(),_meta:ye.record(ye.unknown()).optional()}),HV=ye.object({sessions:ye.array(PL),nextCursor:ye.string().optional()})});function ML(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,r]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof r!="string")return;e[t]=r}return e}function Pn(n){if(!n)return{};let e=n[ut];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,r={};if(typeof t.upstreamSessionId=="string"&&(r.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(r.agentId=t.agentId),typeof t.cwd=="string"&&(r.cwd=t.cwd),t.workspace!==null&&typeof t.workspace=="object"&&!Array.isArray(t.workspace)){let s=t.workspace,o={};typeof s.label=="string"&&(o.label=s.label),typeof s.from=="string"&&(o.from=s.from),s.required===!0&&(o.required=!0),s.adopt===!0&&(o.adopt=!0),typeof s.provider=="string"&&(o.provider=s.provider),r.workspace=o}if(t.workspaceInfo!==null&&typeof t.workspaceInfo=="object"&&!Array.isArray(t.workspaceInfo)){let s=t.workspaceInfo;if(typeof s.path=="string"&&typeof s.sourceCwd=="string"&&typeof s.label=="string"&&typeof s.provider=="string"){let o={path:s.path,sourceCwd:s.sourceCwd,label:s.label,provider:s.provider};if(typeof s.snapshot=="string"&&(o.snapshot=s.snapshot),s.vcs!==null&&typeof s.vcs=="object"&&!Array.isArray(s.vcs)){let i={};for(let[a,d]of Object.entries(s.vcs))typeof d=="string"&&(i[a]=d);o.vcs=i}r.workspaceInfo=o}}if(typeof t.workspaceError=="string"&&(r.workspaceError=t.workspaceError),typeof t.clientId=="string"&&(r.clientId=t.clientId),typeof t.readonly=="boolean"&&(r.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(r.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(r.dripSpeed=t.dripSpeed),typeof t.historyLimit=="number"&&Number.isFinite(t.historyLimit)&&t.historyLimit>=0&&(r.historyLimit=t.historyLimit),(t.toolContent==="inline"||t.toolContent==="references")&&(r.toolContent=t.toolContent),t.detachStatus==="detached"&&(r.detachStatus=t.detachStatus),typeof t.title=="string"&&(r.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(s=>typeof s=="string")&&(r.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(s=>typeof s=="string")&&(r.transformers=t.transformers),t.resume){let s=FI.safeParse(t.resume);s.success&&(r.resume=s.data)}if(typeof t.model=="string"&&(r.model=t.model),typeof t.currentModel=="string"&&(r.currentModel=t.currentModel),typeof t.currentMode=="string"&&(r.currentMode=t.currentMode),t.currentUsage){let s=mw.safeParse(t.currentUsage);s.success&&(r.currentUsage=s.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(r.turnStartedAt=t.turnStartedAt),typeof t.armedTasks=="number"&&t.armedTasks>=0&&(r.armedTasks=t.armedTasks),typeof t.armedSince=="number"&&t.armedSince>0&&(r.armedSince=t.armedSince),Array.isArray(t.armedTaskList)){let s=[];for(let o of t.armedTaskList){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;typeof i.label!="string"||typeof i.since!="number"||s.push({label:i.label,since:i.since,...typeof i.taskId=="string"?{taskId:i.taskId}:{},...typeof i.taskType=="string"?{taskType:i.taskType}:{},...typeof i.toolCallId=="string"?{toolCallId:i.toolCallId}:{}})}r.armedTaskList=s}if(Array.isArray(t.availableCommands)){let s=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),s.push(a)}s.length>0&&(r.availableCommands=s)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let s=t.prompt,o={};typeof s.queueing=="boolean"&&(o.queueing=s.queueing),typeof s.cancelling=="boolean"&&(o.cancelling=s.cancelling),typeof s.updating=="boolean"&&(o.updating=s.updating),typeof s.amending=="boolean"&&(o.amending=s.amending),typeof s.pipelining=="boolean"&&(o.pipelining=s.pipelining),r.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let s=t.agents,o={};typeof s.list=="boolean"&&(o.list=s.list),typeof s.installProgress=="boolean"&&(o.installProgress=s.installProgress),r.agents=o}if(typeof t.mcpStdin=="boolean"&&(r.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(r.interactive=t.interactive),typeof t.ancillary=="boolean"&&(r.ancillary=t.ancillary),t.salvaged&&typeof t.salvaged=="object"&&!Array.isArray(t.salvaged)){let s=t.salvaged;typeof s.reason=="string"&&typeof s.supersededMessageId=="string"&&(r.salvaged={reason:s.reason,supersededMessageId:s.supersededMessageId})}if(Array.isArray(t.queue)){let s=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),s.push({messageId:i.messageId,originator:d,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}s.length>0&&(r.queue=s)}if(Array.isArray(t.availableModes)){let s=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),s.push(a)}s.length>0&&(r.availableModes=s)}if(Array.isArray(t.availableModels)){let s=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),s.push(a)}s.length>0&&(r.availableModels=s)}if((t.status==="warm"||t.status==="cold")&&(r.status=t.status),typeof t.busy=="boolean"&&(r.busy=t.busy),typeof t.awaitingInput=="boolean"&&(r.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(r.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(r.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(r.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(r.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(r.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(r.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(r.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let s=t.originatingClient;r.originatingClient={name:s.name,...typeof s.version=="string"?{version:s.version}:{}}}if(t.agentCapabilities!==void 0&&(r.agentCapabilities=t.agentCapabilities),t.env!==void 0){let s=ML(t.env);s!==void 0&&(r.env=s)}return r}function Fs(n,e){if(typeof e!="number"||!Number.isFinite(e)||!n||typeof n!="object"||Array.isArray(n))return n;let t=n,r=t._meta&&typeof t._meta=="object"&&!Array.isArray(t._meta)?t._meta:{},s=r[ut],o=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return typeof o.recordedAt=="number"?n:{...t,_meta:{...r,[ut]:{...o,recordedAt:e}}}}function Ls(n,e){if(typeof e!="number"||!Number.isFinite(e)||!n||typeof n!="object"||Array.isArray(n))return n;let t=n,r=t._meta&&typeof t._meta=="object"&&!Array.isArray(t._meta)?t._meta:{},s=r[ut],o=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return typeof o.seq=="number"?n:{...t,_meta:{...r,[ut]:{...o,seq:e}}}}function yp(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e[ut];if(!t||typeof t!="object")return;let r=t.seq;return typeof r=="number"&&Number.isFinite(r)?r:void 0}function HI(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e[ut];if(!t||typeof t!="object")return;let r=t.recordedAt;return typeof r=="number"&&Number.isFinite(r)?r:void 0}function ql(n,e){return{...n??{},[ut]:e}}var ut,cc=q(()=>{"use strict";hw();gw();ut="hydra-acp"});import{z as ue}from"zod";var UI,wp,WI,KV,GV,JV,jI,VV,qI,YV,zI,QV,KI,XV,ZV,GI=q(()=>{"use strict";UI=ue.object({sessionId:ue.string(),prompt:ue.array(ue.unknown()),_meta:ue.record(ue.unknown()).optional()}),wp=ue.object({sessionId:ue.string()}),WI=ue.object({clientId:ue.string(),name:ue.string().optional(),version:ue.string().optional()}),KV=ue.object({sessionId:ue.string(),messageId:ue.string(),originator:WI,prompt:ue.array(ue.unknown()),position:ue.number().int().nonnegative(),queueDepth:ue.number().int().positive(),enqueuedAt:ue.number()}),GV=ue.object({sessionId:ue.string(),messageId:ue.string(),prompt:ue.array(ue.unknown())}),JV=ue.object({sessionId:ue.string(),messageId:ue.string(),reason:ue.enum(["started","cancelled","abandoned"])}),jI=ue.object({sessionId:ue.string(),messageId:ue.string()}),VV=ue.object({cancelled:ue.boolean(),reason:ue.enum(["ok","not_found","already_running"])}),qI=ue.object({sessionId:ue.string(),messageId:ue.string(),prompt:ue.array(ue.unknown())}),YV=ue.object({updated:ue.boolean(),reason:ue.enum(["ok","not_found","already_running"])}),zI=ue.object({sessionId:ue.string(),targetMessageId:ue.string(),prompt:ue.array(ue.unknown()),replaceQueue:ue.boolean().optional(),onTargetCompleted:ue.enum(["reject","send_anyway"]).optional()}),QV=ue.object({amended:ue.boolean(),reason:ue.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ue.string().optional()}),KI=ue.object({sessionId:ue.string(),prompt:ue.array(ue.unknown()),_meta:ue.object({steering:ue.object({idleBehavior:ue.literal("promptRequired").optional()}).optional()}).optional()}),XV=ue.object({outcome:ue.enum(["injected","startedNewTurn","promptRequired","failed"]),reason:ue.literal("noRunningTurn").optional(),detached:ue.boolean().optional()}),ZV=ue.object({sessionId:ue.string(),cancelledMessageId:ue.string(),newMessageId:ue.string(),prompt:ue.array(ue.unknown()),originator:WI,amendedAt:ue.number()})});import{z as ti}from"zod";var JI,bp,lc,VI=q(()=>{"use strict";JI=ti.object({agentId:ti.string(),version:ti.string(),source:ti.enum(["binary","npm"]),phase:ti.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ti.number().optional(),totalBytes:ti.number().optional(),packageSpec:ti.string().optional()}),bp="hydra-acp/agents/install_progress",lc={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var fn=q(()=>{"use strict";jl();hw();cc();gw();GI();VI()});import{nanoid as _L}from"nanoid";var yw,pn,bo=q(()=>{"use strict";fn();yw=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},pn=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;anyNotificationHandlers=[];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 r=this.bufferedNotifications.get(e);if(r){this.bufferedNotifications.delete(e);for(let s of r)try{t(s.params,s.method)}catch{}}}drainBuffered(e){let r=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),r}onAnyNotification(e){this.anyNotificationHandlers.push(e)}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 yw;let r=_L(),s={jsonrpc:"2.0",id:r,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(r,{resolve:d=>i(d),reject:a}),this.stream.send(s).catch(d=>{this.pending.delete(r),a(d)})});return{id:r,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let r={jsonrpc:"2.0",method:e,params:t};return this.stream.send(r)}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:G.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let r=await t(e.params,e.method),s={jsonrpc:"2.0",id:e.id,result:r};await this.stream.send(s).catch(()=>{})}catch(r){let s=r;await this.sendError(e.id,{code:s.code??G.InternalError,message:s.message,data:s.data}).catch(()=>{})}}handleNotification(e){for(let s of this.anyNotificationHandlers)try{s(e.params,e.method)}catch{}let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let r=this.bufferedNotifications.get(e.method);if(!r){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let s=this.bufferedNotifications.keys().next().value;s!==void 0&&this.bufferedNotifications.delete(s)}r=[],this.bufferedNotifications.set(e.method,r)}r.push(e),r.length>n.MAX_BUFFERED_PER_METHOD&&r.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let r of this.orphanErrorHandlers)try{r({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let r=new Error(e.error.message);r.code=e.error.code,r.data=e.error.data,t.reject(r)}else t.resolve(e.result)}async sendError(e,t){let r={jsonrpc:"2.0",id:e,error:t};await this.stream.send(r)}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 XI from"os";function ri(){return XI.hostname()}function Sp(){let n=new Set;n.add(ri());let e=process.env.HYDRA_ACP_LOCAL_HOSTS;if(e)for(let t of e.split(",")){let r=t.trim();r&&n.add(r)}return n}var zl=q(()=>{"use strict"});function ww(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Array.isArray(n.availableModels)}function nC(n){return Array.isArray(n)&&n.some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.id===tC)}function uc(n){if(!n)return;if(ww(n)||ww(n.models))return Ns;let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){for(let[t,r]of Object.entries(e))if(t!=="hydra-acp"&&ww(r))return Ns}if(nC(n.configOptions))return bw}function rC(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n.sessionUpdate;if(e==="_hydra_current_model_update")return Ns;if(e==="config_option_update"&&nC(n.configOptions))return bw}function ZI(n){return typeof n=="object"&&n!==null&&n.code===G.MethodNotFound}function eC(n,e,t,r){let s={...r??{}};return delete s.sessionId,delete s.modelId,delete s.configId,delete s.value,n===Ns?{...s,sessionId:e,modelId:t}:{...s,sessionId:e,configId:tC,value:t}}function DL(n){return n===Ns?bw:Ns}async function si(n){let{request:e,sessionId:t,modelId:r,extraParams:s,logger:o}=n,i=n.verb??Ns;try{let a=await e(i,eC(i,t,r,s));return{verb:i,result:a}}catch(a){if(!ZI(a))throw a;let d=DL(i);o?.info(`agent does not implement ${i} (MethodNotFound); retrying model change via ${d} modelId=${JSON.stringify(r)}`);try{let c=await e(d,eC(d,t,r,s));return{verb:d,result:c}}catch(c){throw ZI(c)?a:c}}}var Ns,bw,tC,Kl=q(()=>{"use strict";jl();Ns="session/set_model",bw="session/set_config_option",tC="model"});async function ca(n){let{agent:e,upstreamSessionId:t,persistedMode:r,agentReportedMode:s,advertisedModes:o,logger:i}=n;if(!r)return s;if(r===s)return r;if(o&&o.length>0&&!o.some(a=>a.id===r)){let a=o.map(d=>d.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(r)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(s)}`),s}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(r)} to agent (agentReported=${JSON.stringify(s)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:r}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(r)}`),r}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(r)} (${a.message}); session will use ${JSON.stringify(s)}`),s}}async function la(n){let{agent:e,upstreamSessionId:t,persistedModel:r,agentReportedModel:s,modelVerb:o,logger:i}=n;if(!r)return{modelId:s};if(r===s)return{modelId:r};try{i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(r)} to agent (agentReported=${JSON.stringify(s)})`);let{verb:a,result:d}=await si({request:(c,l)=>e.connection.request(c,l),sessionId:t,modelId:r,...o?{verb:o}:{},logger:i});return i?.info(`resurrect: ${a} accepted, effectiveModel=${JSON.stringify(r)}`),{modelId:r,result:d}}catch(a){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(r)} (${a.message}); session will use ${JSON.stringify(s)}`),{modelId:s}}}var kw=q(()=>{"use strict";Kl()});function ko(n){return`${n.name}:${n.localId}`}function Ds(n){let e=n.indexOf(":");if(e===-1)return;let t=n.slice(0,e),r=n.slice(e+1);if(!(t.length===0||r.length===0))return{name:t,localId:r}}var Gl=q(()=>{"use strict"});import{createHmac as BL}from"crypto";function HL(n,e){return BL("sha256",n).update(e).digest("hex")}function vw(n,e){let t=JSON.stringify(e),r=HL(n.secret,t);fetch(n.callbackUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Hydra-Turn-Notify-Signature":r},body:t}).catch(()=>{})}var sC=q(()=>{"use strict"});function oC(n){return n!==void 0&&UL.has(n)}function Sw(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let r=t.path;typeof r=="string"&&r.length>0&&e.push(r)}return e}function Ip(n){return Sw(n)[0]}var UL,iC,xp,Jl=q(()=>{"use strict";UL=new Set(["edit","delete","move"]);iC="edit",xp=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 dC from"fs/promises";function VL(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var WL,jL,fc,qL,zL,KL,GL,JL,aC,Cp,cC=q(()=>{"use strict";WL=64*1024*1024,jL=1*1024*1024,fc=64*1024,qL=6e4,zL=100,KL=1e3,GL=64*1024,JL=256*1024,aC=20;Cp=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??WL,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(jL,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 r=Math.max(0,Math.min(t,fc));if(r===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let s=e,o=0,i=this.oldestAvailable;s<i&&(o=i-s,s=i);let a=this.writeCursor-s;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:s};return o>0&&(u.gap=o),this.closed&&(u.eof=!0),u}let d=Math.min(a,r),l={bytes:this.sliceFromRing(s,d),nextCursor:s+d};return o>0&&(l.gap=o),this.closed&&s+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,fc)),r=this.oldestAvailable,s=this.writeCursor-t,o=Math.max(r,s),i=s<r;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,fc)),r=this.oldestAvailable,s=r>0,o=r,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:s}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let r=Math.max(0,Math.min(t,qL));return r===0?Promise.resolve("timeout"):new Promise(s=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),s(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,s("timeout")},r)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,r=e.cursor,s=r??t,o=0;r!==void 0&&r<t&&(o=t-r,s=t),s>this.writeCursor&&(s=this.writeCursor);let i=this.sliceFromRing(s,this.writeCursor-s),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(VL(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??zL,KL)),f=Math.max(1,Math.min(e.maxBytes??GL,JL)),p=Math.max(0,Math.min(e.contextBefore??0,aC)),m=Math.max(0,Math.min(e.contextAfter??0,aC)),h=[],g=[],w=[],b=0,k=!1,S=0,I=0,x=(P,$)=>{for(let W of w)W.remaining>0&&(W.match.after===void 0&&(W.match.after=[]),W.match.after.push({cursor:P,line:$}),W.remaining--,b+=$.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(c.test($)!==l&&h.length<u){let W={cursor:P,line:$};if(p>0&&g.length>0){W.before=g.slice();for(let Z of W.before)b+=Z.line.length}b+=$.length,h.push(W),m>0&&w.push({match:W,remaining:m})}if(p>0)for(g.push({cursor:P,line:$});g.length>p;)g.shift();let J=h.length>=u&&w.length===0,Y=b>=f;return J||Y};for(let P=0;P<i.length;P++){if(i[P]!==10)continue;let $=i.subarray(S,P).toString("utf8"),F=s+S;if(S=P+1,I=S,x(F,$)){k=!0;break}}if(!k&&S<i.length&&this.closed){let P=i.subarray(S).toString("utf8"),$=s+S;x($,P)&&(k=!0),I=i.length}let A=Math.min(s+I,this.writeCursor),_={matches:h,truncated:k,nextCursor:A,scannedBytes:I};return o>0&&(_.gap=o),this.closed&&A>=this.writeCursor&&(_.eof=!0),_}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let r of t)r.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let r=this.currentCapacityBytes;for(;r<t&&r<this.maxCapacityBytes;)r=Math.min(this.maxCapacityBytes,r*2);if(r===this.currentCapacityBytes)return;let s=Buffer.alloc(r);this.storage.copy(s,0,0,this.writeCursor),this.storage=s,this.currentCapacityBytes=r}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let r=this.writeCursor%this.currentCapacityBytes,s=this.currentCapacityBytes-r;t<=s?e.copy(this.storage,r,0,t):(e.copy(this.storage,r,0,s),e.copy(this.storage,0,s,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let r=Buffer.alloc(t),s=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-s);return this.storage.copy(r,0,s,s+o),o<t&&this.storage.copy(r,o,0,t-o),r}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let r=this.fileCapBytes-this.fileBytesWritten;if(r<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let s=e.length<=r?e:e.subarray(0,r);this.fileBytesWritten+=s.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>dC.appendFile(t,s)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var pc,_6,lC=q(()=>{"use strict";pc=[{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:"workspace",name:"hydra workspace",argsHint:"<start [name] [--clean] | sync | merge | apply | stop | detach | clean [--deep] | discard | status>",description:"Move this session into an isolated workspace so its edits cannot collide with other work, then land or discard them. `start` copies your uncommitted changes in and leaves the real tree untouched; `start --clean` leaves them behind so the workspace begins at the last commit. `stop` merges and returns; `discard` throws the work away and returns; `detach` returns without merging, leaving the workspace and its branch intact; `merge` lands the work without leaving; `apply` also stays, but delivers the work as ONE staged, uncommitted changeset instead of as the agent's commits, so you review and commit it yourself, with no fast-forward needed, which is what makes it work once the source has moved on; `clean` throws away everything done in the workspace and stays there, putting it back exactly as `start --clean` would have made it (add `--deep` to rebuild dependencies and carried config files too, rather than keeping them); `sync` pulls the source's committed history INTO the workspace, so you can test against what you will land onto, and because landing is fast-forward-only, syncing is also how you recover once the source has moved on. `start <name>` naming a workspace another live session is already in JOINS it instead of making a second one, so two sessions can share a checkout deliberately: edits interleave, `stop` behaves as `detach` while anyone else is still there, and the work lands when the last of them leaves."},{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] [prompt]",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). A prompt is sent to the fork as its first turn once it's ready."},{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."}],_6=new Map(pc.map(n=>[n.verb,n]))});function uC(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function hc(n,e){return mc(n,e.map(t=>t.modelId))}function mc(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=uC(n),r=e.filter(o=>uC(o)===t);if(r.length===1)return{kind:"resolved",modelId:r[0],requested:n};if(r.length>1)return{kind:"ambiguous",requested:n,candidates:r};let s=n.toLowerCase();if(s.length>0){let o=e.filter(i=>i.toLowerCase().includes(s));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}var Rp=q(()=>{"use strict"});function ZL(n){if(!n||n.status!=="completed"||n.sessionUpdate!=="tool_call"&&n.sessionUpdate!=="tool_call_update")return!1;let e=n._meta,t=e!==null&&typeof e=="object"&&QL in e;return n.title===YL||t}function e1(n){if(!n||n.sessionUpdate!=="agent_message_chunk")return!1;let e=n.content;return!e||typeof e!="object"||Array.isArray(e)?!1:e.text===XL}function fC(n){return ZL(n)||e1(n)}var YL,QL,XL,pC=q(()=>{"use strict";YL="Compact conversation",QL="contextCompaction",XL=`
|
|
31
|
+
`)};hL=5,mL=25});import*as EI from"fs/promises";import*as mp from"path";import{z as Ce}from"zod";function PI(n){return n.installId??n.id}function uw(n){let e=n.extendsChain;return e&&e.length>0?e[e.length-1]:n.id}function xr(n,e){if(n)for(let t of e.extendsChain??[e.id]){let r=n[t];if(r!==void 0)return{value:r,from:t}}}function MI(n){return n&&Object.fromEntries(Object.entries(n).map(([e,t])=>[e,mt(t)]))}function lw(n,e){return{id:n,name:e.name??n,description:e.description,version:"local",distribution:{exec:{command:mt(e.command??n),args:e.args?.map(mt),env:MI(e.env)}}}}function _I(n,e){let t=e.args?.map(mt),r=MI(e.env),s=o=>({...o,...t?{args:t}:{},...r?{env:{...o.env,...r}}:{}});return{...n.npx?{npx:s(n.npx)}:{},...n.uvx?{uvx:s(n.uvx)}:{},...n.exec?{exec:s(n.exec)}:{},...n.binary?{binary:Object.fromEntries(Object.entries(n.binary).map(([o,i])=>[o,i&&s(i)]))}:{}}}function RL(n,e){let t=r=>({...r,args:[...r.args??[],...e]});return{...n.npx?{npx:t(n.npx)}:{},...n.uvx?{uvx:t(n.uvx)}:{},...n.exec?{exec:t(n.exec)}:{},...n.binary?{binary:Object.fromEntries(Object.entries(n.binary).map(([r,s])=>[r,s&&t(s)]))}:{}}}function AL(n,e,t){let r=e.command!==void 0;return{...t,id:n,name:e.name??t.name,description:e.description??t.description,version:r?"local":t.version,distribution:r?lw(n,e).distribution:_I(t.distribution,e),installId:r?n:t.installId??t.id,extendsChain:[n,...t.extendsChain??[t.id]]}}function TL(n){let e=n.lastIndexOf("@"),r=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return r.length>0?`pin-${r}`:"pinned"}function fw(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),r=t===-1?e:e.slice(t+1),s=r.lastIndexOf("@");return s<=0?r:r.slice(0,s)}async function dc(n){let e=typeof n.resolvedLocalAgents=="function"?await n.resolvedLocalAgents():typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let r=new Set(e.map(i=>i.id)),s=[...e,...t.agents.filter(i=>!r.has(i.id))],o=await Promise.all(s.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await pw(i),...i.extendsChain?{extendsChain:i.extendsChain}:{},source:r.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function pw(n){let e=Sr();if(!e)return"no";let t=n.version??"current",r=PI(n);if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=sw(n.distribution.binary,e);if(s?.cmd){let o=mp.resolve(D.agentInstallDir(r,e,t),s.cmd);if(await TI(o))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,o=s.bin??fw(n)??s.package,i=D.agentNpmInstallDir(r,e,t),a=mp.join(i,"node_modules",".bin",o);if(await TI(a))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function TI(n){try{return await EI.access(n),!0}catch{return!1}}async function Ir(n,e=[],t={}){let r=n.version??"current",s=PI(n);if(n.distribution.npx){let o=n.distribution.npx,i=e.length>0?e:o.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",o.package,...i],env:o.env??{},version:r,installId:s};let a=o.bin??fw(n)??o.package,d=t.onInstallProgress;return{command:await xI({agentId:s,version:r,packageSpec:o.package,bin:a,registry:t.npmRegistry,onProgress:d?l=>d({source:"npm",...l}):void 0}),args:i,env:o.env??{},version:r,installId:s}}if(n.distribution.binary){let o=sw(n.distribution.binary);if(!o)throw new Error(`Agent ${n.id} has no binary distribution for ${Sr()??"this platform"}.`);let i=t.onInstallProgress,a=await bI({agentId:s,version:r,target:o,onProgress:i?c=>i({source:"binary",...c}):void 0}),d=e.length>0?e:o.args??[];return{command:a,args:d,env:o.env??{},version:r,installId:s}}if(n.distribution.uvx){let o=n.distribution.uvx,i=e.length>0?e:o.args??[];return{command:"uvx",args:[o.package,...i],env:o.env??{},version:r,installId:s}}if(n.distribution.exec){let o=n.distribution.exec,i=e.length>0?e:o.args??[];return{command:o.command,args:i,env:o.env??{},version:r,installId:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}var bL,ac,kL,vL,SL,xL,IL,CL,RI,AI,hp,Os=q(()=>{"use strict";ke();rt();es();oc();cw();bL=Ce.object({package:Ce.string(),bin:Ce.string().optional(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),ac=Ce.object({archive:Ce.string().url().optional(),cmd:Ce.string().optional(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),kL=Ce.object({"darwin-aarch64":ac.optional(),"darwin-x86_64":ac.optional(),"linux-aarch64":ac.optional(),"linux-x86_64":ac.optional(),"windows-x86_64":ac.optional(),"windows-aarch64":ac.optional()}),vL=Ce.object({package:Ce.string(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),SL=Ce.object({command:Ce.string(),args:Ce.array(Ce.string()).optional(),env:Ce.record(Ce.string()).optional()}),xL=Ce.object({command:Ce.string().optional(),url:Ce.string().optional(),description:Ce.string().optional()}),IL=Ce.object({npx:bL.optional(),binary:kL.optional(),uvx:vL.optional(),exec:SL.optional()}),CL=Ce.object({id:Ce.string(),name:Ce.string(),version:Ce.string().optional(),description:Ce.string().optional(),authors:Ce.array(Ce.string()).optional(),license:Ce.string().optional(),icon:Ce.string().optional(),repository:Ce.string().optional(),website:Ce.string().optional(),distribution:IL,onboarding:xL.optional(),requiredEnv:Ce.array(Ce.string().min(1)).optional()}),RI=8;AI=Ce.object({version:Ce.string(),agents:Ce.array(CL),extensions:Ce.array(Ce.unknown()).optional()}),hp=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){let r=this.options.onStaleFallback;if(r)try{r(t,Date.now()-e.fetchedAt)}catch{}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}setConfig(e){this.config=e}async getAgent(e){return this.resolveAgent(e,[])}async resolveAgent(e,t){let r=this.findLocalDef(e);if(r){if(r.def.extends===void 0)return{...lw(r.id,r.def),extendsChain:[r.id]};if(t.includes(r.id))throw new Error(`agent ${r.id}: extends cycle (${[...t,r.id].join(" -> ")})`);if(t.length+1>=RI)throw new Error(`agent ${r.id}: extends chain deeper than ${RI} (${[...t,r.id].join(" -> ")})`);let c=await this.resolveAgent(r.def.extends,[...t,r.id]);if(!c)throw new Error(`agent ${r.id}: extends ${JSON.stringify(r.def.extends)}, which is not a known agent`);return this.applyOverride(AL(r.id,r.def,c))}let s=await this.load(),o=s.agents.find(c=>c.id===e);if(o)return this.applyOverride(o);let i=s.agents.find(c=>fw(c)===e);if(i)return this.applyOverride(i);let a=e.toLowerCase(),d=s.agents.find(c=>c.id.toLowerCase()===`${a}-acp`);if(d)return this.applyOverride(d);if(a.length>0){let c=s.agents.filter(l=>l.id.toLowerCase().startsWith(a));if(c.length===1)return this.applyOverride(c[0])}}findLocalDef(e){let t=this.config.agents??{},r=t[e];if(r)return{id:e,def:r};let s=e.toLowerCase();for(let[o,i]of Object.entries(t))if(o.toLowerCase()===`${s}-acp`)return{id:o,def:i}}localAgents(){return Object.entries(this.config.agents??{}).filter(([,e])=>e.extends===void 0).map(([e,t])=>lw(e,t))}async resolvedLocalAgents(){let e=[];for(let t of Object.keys(this.config.agents??{}))try{let r=await this.resolveAgent(t,[]);r&&e.push(r)}catch(r){this.options.onResolveError?.(t,r)}return e}applyOverride(e){let t=e.extendsChain?e:{...e,extendsChain:[e.id]},r=this.config.agentOverrides?.[t.id];if(!r)return t;let s=t.distribution,o=t.version,i=t.installId;return r.packageSpec&&s.npx&&(o=TL(r.packageSpec),i=t.id,s={...s,npx:{...s.npx,package:r.packageSpec}}),r.extraArgs?.length&&(s=RL(s,r.extraArgs)),r.env&&Object.keys(r.env).length>0&&(s=_I(s,{env:r.env})),s===t.distribution?t:{...t,version:o,installId:i,distribution:s}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,r=this.config.registry.ttlHours*60*60*1e3;return t<r}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(),r=AI.parse(t),s={fetchedAt:Date.now(),raw:t,data:r},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(r)).catch(()=>{}),s}async readDiskCache(){let e=await jt(D.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=AI.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await nn(D.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}}});var G,jl=q(()=>{"use strict";G={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 yt}from"zod";var $I,EL,OI,FI,LI,hw=q(()=>{"use strict";$I=yt.object({protocolVersion:yt.number().optional(),clientCapabilities:yt.record(yt.unknown()).optional(),clientInfo:yt.object({name:yt.string(),version:yt.string().optional()}).optional()}),EL=yt.enum(["full","pending_only","none","after_message"]),OI=yt.object({cwd:yt.string(),mcpServers:yt.array(yt.unknown()).optional(),_meta:yt.record(yt.unknown()).optional()}),FI=yt.object({upstreamSessionId:yt.string(),agentId:yt.string(),cwd:yt.string(),title:yt.string().optional(),agentArgs:yt.array(yt.string()).optional()}),LI=yt.object({sessionId:yt.string(),historyPolicy:EL.default("full"),afterMessageId:yt.string().optional(),afterSeq:yt.number().optional(),clientId:yt.string().optional(),clientInfo:yt.object({name:yt.string(),version:yt.string().optional()}).optional(),_meta:yt.record(yt.unknown()).optional()})});import{z as ye}from"zod";function gp(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.workspace!==void 0&&(t.workspaceInfo=n.workspace),n.workspaceError!==void 0&&(t.workspaceError=n.workspaceError),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.armedTasks!==void 0&&(t.armedTasks=n.armedTasks),n.armedSince!==void 0&&(t.armedSince=n.armedSince),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),e.armedTaskList!==void 0&&(t.armedTaskList=e.armedTaskList)),t}function BI(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ql(n._meta,gp(n))};return n.title!==void 0&&(e.title=n.title),e}var NI,DI,mw,BV,PL,HV,gw=q(()=>{"use strict";cc();NI=ye.object({sessionId:ye.string()}),DI=ye.object({cwd:ye.string().optional(),cursor:ye.string().optional()}),mw=ye.object({used:ye.number().optional(),size:ye.number().optional(),costAmount:ye.number().optional(),costCurrency:ye.string().optional()}),BV=ye.object({sessionId:ye.string(),upstreamSessionId:ye.string().optional(),cwd:ye.string(),workspace:ye.object({path:ye.string(),sourceCwd:ye.string(),label:ye.string(),provider:ye.string(),snapshot:ye.string().optional(),vcs:ye.record(ye.string(),ye.string()).optional()}).optional(),workspaceError:ye.string().optional(),title:ye.string().optional(),agentId:ye.string().optional(),currentModel:ye.string().optional(),currentUsage:mw.optional(),importedFromMachine:ye.string().optional(),importedFromUpstreamSessionId:ye.string().optional(),parentSessionId:ye.string().optional(),forkedFromSessionId:ye.string().optional(),forkedFromMessageId:ye.string().optional(),originatingClient:ye.object({name:ye.string(),version:ye.string().optional()}).optional(),interactive:ye.boolean().optional(),priority:ye.number().int().nonnegative().optional(),updatedAt:ye.string(),attachedClients:ye.number().int().nonnegative(),status:ye.enum(["warm","cold"]).default("warm"),busy:ye.boolean().default(!1),awaitingInput:ye.boolean().default(!1),turnStartedAt:ye.number().optional(),armedTasks:ye.number().int().nonnegative().optional(),armedSince:ye.number().int().positive().optional(),compactionState:ye.any().optional(),agentPid:ye.number().int().positive().optional(),forkSynthesisState:ye.enum(["running","failed"]).optional(),_meta:ye.record(ye.unknown()).optional()}),PL=ye.object({sessionId:ye.string(),cwd:ye.string(),title:ye.string().optional(),updatedAt:ye.string().optional(),_meta:ye.record(ye.unknown()).optional()}),HV=ye.object({sessions:ye.array(PL),nextCursor:ye.string().optional()})});function ML(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,r]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof r!="string")return;e[t]=r}return e}function Pn(n){if(!n)return{};let e=n[ut];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,r={};if(typeof t.upstreamSessionId=="string"&&(r.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(r.agentId=t.agentId),typeof t.cwd=="string"&&(r.cwd=t.cwd),t.workspace!==null&&typeof t.workspace=="object"&&!Array.isArray(t.workspace)){let s=t.workspace,o={};typeof s.label=="string"&&(o.label=s.label),typeof s.from=="string"&&(o.from=s.from),s.required===!0&&(o.required=!0),s.adopt===!0&&(o.adopt=!0),typeof s.provider=="string"&&(o.provider=s.provider),r.workspace=o}if(t.workspaceInfo!==null&&typeof t.workspaceInfo=="object"&&!Array.isArray(t.workspaceInfo)){let s=t.workspaceInfo;if(typeof s.path=="string"&&typeof s.sourceCwd=="string"&&typeof s.label=="string"&&typeof s.provider=="string"){let o={path:s.path,sourceCwd:s.sourceCwd,label:s.label,provider:s.provider};if(typeof s.snapshot=="string"&&(o.snapshot=s.snapshot),s.vcs!==null&&typeof s.vcs=="object"&&!Array.isArray(s.vcs)){let i={};for(let[a,d]of Object.entries(s.vcs))typeof d=="string"&&(i[a]=d);o.vcs=i}r.workspaceInfo=o}}if(typeof t.workspaceError=="string"&&(r.workspaceError=t.workspaceError),typeof t.clientId=="string"&&(r.clientId=t.clientId),typeof t.readonly=="boolean"&&(r.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(r.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(r.dripSpeed=t.dripSpeed),typeof t.historyLimit=="number"&&Number.isFinite(t.historyLimit)&&t.historyLimit>=0&&(r.historyLimit=t.historyLimit),(t.toolContent==="inline"||t.toolContent==="references")&&(r.toolContent=t.toolContent),t.detachStatus==="detached"&&(r.detachStatus=t.detachStatus),typeof t.title=="string"&&(r.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(s=>typeof s=="string")&&(r.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(s=>typeof s=="string")&&(r.transformers=t.transformers),t.resume){let s=FI.safeParse(t.resume);s.success&&(r.resume=s.data)}if(typeof t.model=="string"&&(r.model=t.model),typeof t.currentModel=="string"&&(r.currentModel=t.currentModel),typeof t.currentMode=="string"&&(r.currentMode=t.currentMode),t.currentUsage){let s=mw.safeParse(t.currentUsage);s.success&&(r.currentUsage=s.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(r.turnStartedAt=t.turnStartedAt),typeof t.armedTasks=="number"&&t.armedTasks>=0&&(r.armedTasks=t.armedTasks),typeof t.armedSince=="number"&&t.armedSince>0&&(r.armedSince=t.armedSince),Array.isArray(t.armedTaskList)){let s=[];for(let o of t.armedTaskList){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;typeof i.label!="string"||typeof i.since!="number"||s.push({label:i.label,since:i.since,...typeof i.taskId=="string"?{taskId:i.taskId}:{},...typeof i.taskType=="string"?{taskType:i.taskType}:{},...typeof i.toolCallId=="string"?{toolCallId:i.toolCallId}:{}})}r.armedTaskList=s}if(Array.isArray(t.availableCommands)){let s=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),s.push(a)}s.length>0&&(r.availableCommands=s)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let s=t.prompt,o={};typeof s.queueing=="boolean"&&(o.queueing=s.queueing),typeof s.cancelling=="boolean"&&(o.cancelling=s.cancelling),typeof s.updating=="boolean"&&(o.updating=s.updating),typeof s.amending=="boolean"&&(o.amending=s.amending),typeof s.pipelining=="boolean"&&(o.pipelining=s.pipelining),r.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let s=t.agents,o={};typeof s.list=="boolean"&&(o.list=s.list),typeof s.installProgress=="boolean"&&(o.installProgress=s.installProgress),r.agents=o}if(typeof t.mcpStdin=="boolean"&&(r.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(r.interactive=t.interactive),typeof t.ancillary=="boolean"&&(r.ancillary=t.ancillary),t.salvaged&&typeof t.salvaged=="object"&&!Array.isArray(t.salvaged)){let s=t.salvaged;typeof s.reason=="string"&&typeof s.supersededMessageId=="string"&&(r.salvaged={reason:s.reason,supersededMessageId:s.supersededMessageId})}if(Array.isArray(t.queue)){let s=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),s.push({messageId:i.messageId,originator:d,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}s.length>0&&(r.queue=s)}if(Array.isArray(t.availableModes)){let s=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),s.push(a)}s.length>0&&(r.availableModes=s)}if(Array.isArray(t.availableModels)){let s=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),s.push(a)}s.length>0&&(r.availableModels=s)}if((t.status==="warm"||t.status==="cold")&&(r.status=t.status),typeof t.busy=="boolean"&&(r.busy=t.busy),typeof t.awaitingInput=="boolean"&&(r.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(r.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(r.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(r.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(r.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(r.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(r.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(r.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let s=t.originatingClient;r.originatingClient={name:s.name,...typeof s.version=="string"?{version:s.version}:{}}}if(t.agentCapabilities!==void 0&&(r.agentCapabilities=t.agentCapabilities),t.env!==void 0){let s=ML(t.env);s!==void 0&&(r.env=s)}return r}function Fs(n,e){if(typeof e!="number"||!Number.isFinite(e)||!n||typeof n!="object"||Array.isArray(n))return n;let t=n,r=t._meta&&typeof t._meta=="object"&&!Array.isArray(t._meta)?t._meta:{},s=r[ut],o=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return typeof o.recordedAt=="number"?n:{...t,_meta:{...r,[ut]:{...o,recordedAt:e}}}}function Ls(n,e){if(typeof e!="number"||!Number.isFinite(e)||!n||typeof n!="object"||Array.isArray(n))return n;let t=n,r=t._meta&&typeof t._meta=="object"&&!Array.isArray(t._meta)?t._meta:{},s=r[ut],o=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return typeof o.seq=="number"?n:{...t,_meta:{...r,[ut]:{...o,seq:e}}}}function yp(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e[ut];if(!t||typeof t!="object")return;let r=t.seq;return typeof r=="number"&&Number.isFinite(r)?r:void 0}function HI(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e[ut];if(!t||typeof t!="object")return;let r=t.recordedAt;return typeof r=="number"&&Number.isFinite(r)?r:void 0}function ql(n,e){return{...n??{},[ut]:e}}var ut,cc=q(()=>{"use strict";hw();gw();ut="hydra-acp"});import{z as ue}from"zod";var UI,wp,WI,KV,GV,JV,jI,VV,qI,YV,zI,QV,KI,XV,ZV,GI=q(()=>{"use strict";UI=ue.object({sessionId:ue.string(),prompt:ue.array(ue.unknown()),_meta:ue.record(ue.unknown()).optional()}),wp=ue.object({sessionId:ue.string()}),WI=ue.object({clientId:ue.string(),name:ue.string().optional(),version:ue.string().optional()}),KV=ue.object({sessionId:ue.string(),messageId:ue.string(),originator:WI,prompt:ue.array(ue.unknown()),position:ue.number().int().nonnegative(),queueDepth:ue.number().int().positive(),enqueuedAt:ue.number()}),GV=ue.object({sessionId:ue.string(),messageId:ue.string(),prompt:ue.array(ue.unknown())}),JV=ue.object({sessionId:ue.string(),messageId:ue.string(),reason:ue.enum(["started","cancelled","abandoned"])}),jI=ue.object({sessionId:ue.string(),messageId:ue.string()}),VV=ue.object({cancelled:ue.boolean(),reason:ue.enum(["ok","not_found","already_running"])}),qI=ue.object({sessionId:ue.string(),messageId:ue.string(),prompt:ue.array(ue.unknown())}),YV=ue.object({updated:ue.boolean(),reason:ue.enum(["ok","not_found","already_running"])}),zI=ue.object({sessionId:ue.string(),targetMessageId:ue.string(),prompt:ue.array(ue.unknown()),replaceQueue:ue.boolean().optional(),onTargetCompleted:ue.enum(["reject","send_anyway"]).optional()}),QV=ue.object({amended:ue.boolean(),reason:ue.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ue.string().optional()}),KI=ue.object({sessionId:ue.string(),prompt:ue.array(ue.unknown()),_meta:ue.object({steering:ue.object({idleBehavior:ue.literal("promptRequired").optional()}).optional()}).optional()}),XV=ue.object({outcome:ue.enum(["injected","startedNewTurn","promptRequired","failed"]),reason:ue.literal("noRunningTurn").optional(),detached:ue.boolean().optional()}),ZV=ue.object({sessionId:ue.string(),cancelledMessageId:ue.string(),newMessageId:ue.string(),prompt:ue.array(ue.unknown()),originator:WI,amendedAt:ue.number()})});import{z as ti}from"zod";var JI,bp,lc,VI=q(()=>{"use strict";JI=ti.object({agentId:ti.string(),version:ti.string(),source:ti.enum(["binary","npm"]),phase:ti.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ti.number().optional(),totalBytes:ti.number().optional(),packageSpec:ti.string().optional()}),bp="hydra-acp/agents/install_progress",lc={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var fn=q(()=>{"use strict";jl();hw();cc();gw();GI();VI()});import{nanoid as _L}from"nanoid";var yw,pn,ko=q(()=>{"use strict";fn();yw=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},pn=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;anyNotificationHandlers=[];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 r=this.bufferedNotifications.get(e);if(r){this.bufferedNotifications.delete(e);for(let s of r)try{t(s.params,s.method)}catch{}}}drainBuffered(e){let r=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),r}onAnyNotification(e){this.anyNotificationHandlers.push(e)}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 yw;let r=_L(),s={jsonrpc:"2.0",id:r,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(r,{resolve:d=>i(d),reject:a}),this.stream.send(s).catch(d=>{this.pending.delete(r),a(d)})});return{id:r,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let r={jsonrpc:"2.0",method:e,params:t};return this.stream.send(r)}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:G.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let r=await t(e.params,e.method),s={jsonrpc:"2.0",id:e.id,result:r};await this.stream.send(s).catch(()=>{})}catch(r){let s=r;await this.sendError(e.id,{code:s.code??G.InternalError,message:s.message,data:s.data}).catch(()=>{})}}handleNotification(e){for(let s of this.anyNotificationHandlers)try{s(e.params,e.method)}catch{}let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let r=this.bufferedNotifications.get(e.method);if(!r){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let s=this.bufferedNotifications.keys().next().value;s!==void 0&&this.bufferedNotifications.delete(s)}r=[],this.bufferedNotifications.set(e.method,r)}r.push(e),r.length>n.MAX_BUFFERED_PER_METHOD&&r.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let r of this.orphanErrorHandlers)try{r({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let r=new Error(e.error.message);r.code=e.error.code,r.data=e.error.data,t.reject(r)}else t.resolve(e.result)}async sendError(e,t){let r={jsonrpc:"2.0",id:e,error:t};await this.stream.send(r)}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 XI from"os";function ri(){return XI.hostname()}function Sp(){let n=new Set;n.add(ri());let e=process.env.HYDRA_ACP_LOCAL_HOSTS;if(e)for(let t of e.split(",")){let r=t.trim();r&&n.add(r)}return n}var zl=q(()=>{"use strict"});function ww(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Array.isArray(n.availableModels)}function nC(n){return Array.isArray(n)&&n.some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.id===tC)}function uc(n){if(!n)return;if(ww(n)||ww(n.models))return Ns;let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){for(let[t,r]of Object.entries(e))if(t!=="hydra-acp"&&ww(r))return Ns}if(nC(n.configOptions))return bw}function rC(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n.sessionUpdate;if(e==="_hydra_current_model_update")return Ns;if(e==="config_option_update"&&nC(n.configOptions))return bw}function ZI(n){return typeof n=="object"&&n!==null&&n.code===G.MethodNotFound}function eC(n,e,t,r){let s={...r??{}};return delete s.sessionId,delete s.modelId,delete s.configId,delete s.value,n===Ns?{...s,sessionId:e,modelId:t}:{...s,sessionId:e,configId:tC,value:t}}function DL(n){return n===Ns?bw:Ns}async function si(n){let{request:e,sessionId:t,modelId:r,extraParams:s,logger:o}=n,i=n.verb??Ns;try{let a=await e(i,eC(i,t,r,s));return{verb:i,result:a}}catch(a){if(!ZI(a))throw a;let d=DL(i);o?.info(`agent does not implement ${i} (MethodNotFound); retrying model change via ${d} modelId=${JSON.stringify(r)}`);try{let c=await e(d,eC(d,t,r,s));return{verb:d,result:c}}catch(c){throw ZI(c)?a:c}}}var Ns,bw,tC,Kl=q(()=>{"use strict";jl();Ns="session/set_model",bw="session/set_config_option",tC="model"});async function ca(n){let{agent:e,upstreamSessionId:t,persistedMode:r,agentReportedMode:s,advertisedModes:o,logger:i}=n;if(!r)return s;if(r===s)return r;if(o&&o.length>0&&!o.some(a=>a.id===r)){let a=o.map(d=>d.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(r)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(s)}`),s}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(r)} to agent (agentReported=${JSON.stringify(s)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:r}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(r)}`),r}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(r)} (${a.message}); session will use ${JSON.stringify(s)}`),s}}async function la(n){let{agent:e,upstreamSessionId:t,persistedModel:r,agentReportedModel:s,modelVerb:o,logger:i}=n;if(!r)return{modelId:s};if(r===s)return{modelId:r};try{i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(r)} to agent (agentReported=${JSON.stringify(s)})`);let{verb:a,result:d}=await si({request:(c,l)=>e.connection.request(c,l),sessionId:t,modelId:r,...o?{verb:o}:{},logger:i});return i?.info(`resurrect: ${a} accepted, effectiveModel=${JSON.stringify(r)}`),{modelId:r,result:d}}catch(a){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(r)} (${a.message}); session will use ${JSON.stringify(s)}`),{modelId:s}}}var kw=q(()=>{"use strict";Kl()});function Ds(n){return`${n.name}:${n.localId}`}function Bs(n){let e=n.indexOf(":");if(e===-1)return;let t=n.slice(0,e),r=n.slice(e+1);if(!(t.length===0||r.length===0))return{name:t,localId:r}}var Gl=q(()=>{"use strict"});import{createHmac as BL}from"crypto";function HL(n,e){return BL("sha256",n).update(e).digest("hex")}function vw(n,e){let t=JSON.stringify(e),r=HL(n.secret,t);fetch(n.callbackUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Hydra-Turn-Notify-Signature":r},body:t}).catch(()=>{})}var sC=q(()=>{"use strict"});function oC(n){return n!==void 0&&UL.has(n)}function Sw(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let r=t.path;typeof r=="string"&&r.length>0&&e.push(r)}return e}function Ip(n){return Sw(n)[0]}var UL,iC,xp,Jl=q(()=>{"use strict";UL=new Set(["edit","delete","move"]);iC="edit",xp=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 dC from"fs/promises";function VL(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var WL,jL,fc,qL,zL,KL,GL,JL,aC,Cp,cC=q(()=>{"use strict";WL=64*1024*1024,jL=1*1024*1024,fc=64*1024,qL=6e4,zL=100,KL=1e3,GL=64*1024,JL=256*1024,aC=20;Cp=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??WL,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(jL,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 r=Math.max(0,Math.min(t,fc));if(r===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let s=e,o=0,i=this.oldestAvailable;s<i&&(o=i-s,s=i);let a=this.writeCursor-s;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:s};return o>0&&(u.gap=o),this.closed&&(u.eof=!0),u}let d=Math.min(a,r),l={bytes:this.sliceFromRing(s,d),nextCursor:s+d};return o>0&&(l.gap=o),this.closed&&s+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,fc)),r=this.oldestAvailable,s=this.writeCursor-t,o=Math.max(r,s),i=s<r;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,fc)),r=this.oldestAvailable,s=r>0,o=r,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:s}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let r=Math.max(0,Math.min(t,qL));return r===0?Promise.resolve("timeout"):new Promise(s=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),s(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,s("timeout")},r)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,r=e.cursor,s=r??t,o=0;r!==void 0&&r<t&&(o=t-r,s=t),s>this.writeCursor&&(s=this.writeCursor);let i=this.sliceFromRing(s,this.writeCursor-s),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(VL(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??zL,KL)),f=Math.max(1,Math.min(e.maxBytes??GL,JL)),p=Math.max(0,Math.min(e.contextBefore??0,aC)),m=Math.max(0,Math.min(e.contextAfter??0,aC)),h=[],g=[],w=[],b=0,k=!1,S=0,I=0,x=(P,$)=>{for(let W of w)W.remaining>0&&(W.match.after===void 0&&(W.match.after=[]),W.match.after.push({cursor:P,line:$}),W.remaining--,b+=$.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(c.test($)!==l&&h.length<u){let W={cursor:P,line:$};if(p>0&&g.length>0){W.before=g.slice();for(let Z of W.before)b+=Z.line.length}b+=$.length,h.push(W),m>0&&w.push({match:W,remaining:m})}if(p>0)for(g.push({cursor:P,line:$});g.length>p;)g.shift();let J=h.length>=u&&w.length===0,Y=b>=f;return J||Y};for(let P=0;P<i.length;P++){if(i[P]!==10)continue;let $=i.subarray(S,P).toString("utf8"),F=s+S;if(S=P+1,I=S,x(F,$)){k=!0;break}}if(!k&&S<i.length&&this.closed){let P=i.subarray(S).toString("utf8"),$=s+S;x($,P)&&(k=!0),I=i.length}let A=Math.min(s+I,this.writeCursor),_={matches:h,truncated:k,nextCursor:A,scannedBytes:I};return o>0&&(_.gap=o),this.closed&&A>=this.writeCursor&&(_.eof=!0),_}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let r of t)r.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let r=this.currentCapacityBytes;for(;r<t&&r<this.maxCapacityBytes;)r=Math.min(this.maxCapacityBytes,r*2);if(r===this.currentCapacityBytes)return;let s=Buffer.alloc(r);this.storage.copy(s,0,0,this.writeCursor),this.storage=s,this.currentCapacityBytes=r}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let r=this.writeCursor%this.currentCapacityBytes,s=this.currentCapacityBytes-r;t<=s?e.copy(this.storage,r,0,t):(e.copy(this.storage,r,0,s),e.copy(this.storage,0,s,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let r=Buffer.alloc(t),s=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-s);return this.storage.copy(r,0,s,s+o),o<t&&this.storage.copy(r,o,0,t-o),r}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let r=this.fileCapBytes-this.fileBytesWritten;if(r<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let s=e.length<=r?e:e.subarray(0,r);this.fileBytesWritten+=s.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>dC.appendFile(t,s)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var pc,_6,lC=q(()=>{"use strict";pc=[{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:"workspace",name:"hydra workspace",argsHint:"<start [name] [--clean] | sync | merge | apply | stop | detach | clean [--deep] | discard | status>",description:"Move this session into an isolated workspace so its edits cannot collide with other work, then land or discard them. `start` copies your uncommitted changes in and leaves the real tree untouched; `start --clean` leaves them behind so the workspace begins at the last commit. `stop` merges and returns; `discard` throws the work away and returns; `detach` returns without merging, leaving the workspace and its branch intact; `merge` lands the work without leaving; `apply` also stays, but delivers the work as ONE staged, uncommitted changeset instead of as the agent's commits, so you review and commit it yourself, with no fast-forward needed, which is what makes it work once the source has moved on; `clean` throws away everything done in the workspace and stays there, putting it back exactly as `start --clean` would have made it (add `--deep` to rebuild dependencies and carried config files too, rather than keeping them); `sync` pulls the source's committed history INTO the workspace, so you can test against what you will land onto, and because landing is fast-forward-only, syncing is also how you recover once the source has moved on. `start <name>` naming a workspace another live session is already in JOINS it instead of making a second one, so two sessions can share a checkout deliberately: edits interleave, `stop` behaves as `detach` while anyone else is still there, and the work lands when the last of them leaves."},{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] [prompt]",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). A prompt is sent to the fork as its first turn once it's ready."},{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."}],_6=new Map(pc.map(n=>[n.verb,n]))});function uC(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function hc(n,e){return mc(n,e.map(t=>t.modelId))}function mc(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=uC(n),r=e.filter(o=>uC(o)===t);if(r.length===1)return{kind:"resolved",modelId:r[0],requested:n};if(r.length>1)return{kind:"ambiguous",requested:n,candidates:r};let s=n.toLowerCase();if(s.length>0){let o=e.filter(i=>i.toLowerCase().includes(s));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}var Rp=q(()=>{"use strict"});function ZL(n){if(!n||n.status!=="completed"||n.sessionUpdate!=="tool_call"&&n.sessionUpdate!=="tool_call_update")return!1;let e=n._meta,t=e!==null&&typeof e=="object"&&QL in e;return n.title===YL||t}function e1(n){if(!n||n.sessionUpdate!=="agent_message_chunk")return!1;let e=n.content;return!e||typeof e!="object"||Array.isArray(e)?!1:e.text===XL}function fC(n){return ZL(n)||e1(n)}var YL,QL,XL,pC=q(()=>{"use strict";YL="Compact conversation",QL="contextCompaction",XL=`
|
|
32
32
|
|
|
33
33
|
Compacting completed.`});function mC(n){if(n.length===0)return n;let e=new Map,t=new Map,r=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=xw(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 o1){if(!hC(c[u]))continue;let f=r.get(l);f===void 0?r.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 s=[],o=null,i=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=xw(d);if(!c||typeof c.sessionUpdate!="string"){s.push(d),o=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){o&&o.kind===l?(r1(s,o.outIndex,t1(c.content)),n1(s,o.outIndex,d.seq)):(s.push(d),o={outIndex:s.length-1,kind:l});continue}if(o=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)?s1(d,t.get(u)??[]):d,p=u===void 0?void 0:r.get(u);if(p!==void 0)for(let[m,h]of p)hC(xw(f)?.[m])||(f=i1(f,m,h));s.push(f);continue}if(l==="plan"){i!==null?s[i]=d:(s.push(d),i=s.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(i=null),s.push(d)}return s}function xw(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function t1(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function n1(n,e,t){let r=n[e];r===void 0||typeof t!="number"||r.seq!==void 0&&r.seq>=t||(n[e]={...r,seq:t})}function r1(n,e,t){if(t.length===0)return;let r=n[e];if(r===void 0)return;let s=r.params??{},o=s.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";n[e]={...r,params:{...s,update:{...o,content:{...i,text:a+t}}}}}function s1(n,e){let t=n.params??{},r=t.update??{};return{...n,params:{...t,update:{...r,content:e}}}}function hC(n){return n==null||typeof n!="object"?!1:Array.isArray(n)?n.length>0:Object.keys(n).length>0}function i1(n,e,t){let r=n.params??{},s=r.update??{};return{...n,params:{...r,update:{...s,[e]:t}}}}var o1,gC=q(()=>{"use strict";o1=["rawInput","locations"]});function gc(n,e={}){let t=e.maxChars??4e5,r=Iw(n),s=[],o="",i=e.toolOutput?.maxTotal??0,a=()=>{o.length!==0&&(s.push(`Assistant: ${o}`),o="")};for(let d of n){if(d.method!=="session/update")continue;let l=d.params?.update;if(!l||typeof l.sessionUpdate!="string")continue;let u=l.sessionUpdate;if(u==="prompt_received"){a();let f=Tw(l.prompt).trim();f.length>0&&s.push(`User: ${f}`)}else if(u==="agent_message_chunk"){let f=Ew(l.content);f.length>0&&(o+=f)}else if(u==="tool_call"){if(a(),s.push(Aw(l,r)),e.toolOutput!==void 0){let f=Rw(l),p=f!==void 0?r.get(f)?.output:void 0;if(p!==void 0&&i>0){let m=Math.min(e.toolOutput.maxPerCall,i),h=p.length<=m?p:`${p.slice(0,m)}\u2026[${p.length-m} more chars]`;s.push(`Output: ${h}`),i-=Math.min(h.length,m)}}}else u==="turn_complete"&&a()}return a(),p1(s.join(`
|
|
34
34
|
`),t)}function Iw(n){let e=new Map;for(let t of n){if(t.method!=="session/update")continue;let s=t.params?.update;if(!s)continue;let o=s.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;let i=Rw(s);if(i===void 0)continue;let a=e.get(i);if(a===void 0&&(a={name:"(unnamed)",rawInput:{}},e.set(i,a)),a.name==="(unnamed)"){let c=d1(s,o);c!==void 0&&(a.name=c)}if(a.kind===void 0&&typeof s.kind=="string"&&s.kind.length>0&&(a.kind=s.kind),a.output===void 0){let c=Ap(s);c!==void 0&&(a.output=c)}let d=s.rawInput;d&&typeof d=="object"&&!Array.isArray(d)&&Object.assign(a.rawInput,d)}for(let t of e.values())t.name=Cw(t);return e}function Cw(n){return a1(n)?n.kind??"(unnamed)":n.name}function a1(n){for(let e of wC){let t=n.rawInput[e];if(!(typeof t!="string"||t.length===0)&&(t===n.name||n.name.length>=12&&t.startsWith(n.name)))return!0}return!1}function d1(n,e){let t=Vl(n);if(t!==void 0)return t;if(typeof n.name=="string"&&n.name.length>0)return n.name;if(e==="tool_call"&&typeof n.title=="string"&&n.title.length>0)return n.title}function Rw(n){let e=n.toolCallId;if(typeof e=="string"&&e.length>0)return e}function Ap(n){let e=c1(n);if(e!==void 0)return e;let t=n.rawOutput;if(typeof t=="string")return t.length>0?t:void 0;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t.output;if(typeof r=="string")return r.length>0?r:void 0}}function c1(n){let e=n._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let r=t.toolResponse;if(typeof r=="string")return r.length>0?r:void 0;if(!r||typeof r!="object")return;let{stdout:s,stderr:o}=r,i=[];if(typeof s=="string"&&s.length>0&&i.push(s),typeof o=="string"&&o.length>0&&i.push(`[stderr] ${o}`),i.length!==0)return i.join(`
|
|
@@ -40,11 +40,11 @@ Compacting completed.`});function mC(n){if(n.length===0)return n;let e=new Map,t
|
|
|
40
40
|
`)}`}function kC(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 h1(n,e,t,r){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:s,open:o}=m1(n),i=0,a=[];if(e>0&&s.length>0){let l=s.filter(p=>p.startEntryIndex>=t).length,u=Math.max(l,r),f=Math.min(u,e,s.length);i=f,a=f>0?s.slice(-f):[]}let d=a.length>0?vC(a):"",c=o?vC([o]):"";return{closedText:d,openText:c,keptCount:i}}function vC(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 r of t.tools)e.push(r)}return e.join(`
|
|
41
41
|
`)}function m1(n){let e=[],t=null,r=Iw(n);for(let o=0;o<n.length;o++){let i=n[o];if(i.method!=="session/update")continue;let d=i.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Tw(d.prompt).trim(),agent:"",tools:[],startEntryIndex:o};else if(c==="agent_message_chunk"&&t!==null){let l=Ew(d.content);l.length>0&&(t.agent+=l)}else c==="tool_call"&&t!==null?t.tools.push(Aw(d,r)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}var bC,SC=q(()=>{"use strict";Tp();bC="(untitled)"});function IC(n,e){let t=n??[],r=(e??0)>0,s=[],o=new Set,i=t[0];i&&o.add(i.upstreamSessionId);for(let d=1;d<t.length;d++){let c=t[d],l=t[d-1],u={upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,...c.startedAt!==void 0?{at:c.startedAt}:{},...c.endedAt!==void 0?{endedAt:c.endedAt}:{},...c.cost!==void 0?{cost:c.cost}:{},...c.usedAtStart!==void 0?{usedAfter:c.usedAtStart}:{},...l.usedAtEnd!==void 0?{usedBefore:l.usedAtEnd}:{},...c.reason!==void 0?{reason:c.reason}:{},...c.runId!==void 0?{runId:c.runId}:{}};c.reason===void 0&&(c.agentId!==l.agentId?u.inferredReason="agent-swap":o.has(c.upstreamSessionId)?u.inferredReason="rollback":r||(u.notCompaction=!0)),o.add(c.upstreamSessionId),s.push(u)}let a=s.filter(d=>d.reason==="compaction");return{rotations:s,compactions:a,runs:g1(a),unknownCount:s.filter(d=>d.reason===void 0&&d.inferredReason===void 0&&!d.notCompaction).length}}function g1(n){let e=[],t;for(let r of n){let s=e[e.length-1];if(s!==void 0&&r.runId!==void 0&&r.runId===t){s.swaps++,s.upstreamSessionId=r.upstreamSessionId,s.current=r.endedAt===void 0,r.cost!==void 0&&(s.cost=(s.cost??0)+r.cost),r.usedAfter!==void 0&&(s.usedAfter=r.usedAfter);continue}e.push({...r.at!==void 0?{at:r.at}:{},upstreamSessionId:r.upstreamSessionId,swaps:1,...r.cost!==void 0?{cost:r.cost}:{},...r.usedBefore!==void 0?{usedBefore:r.usedBefore}:{},...r.usedAfter!==void 0?{usedAfter:r.usedAfter}:{},current:r.endedAt===void 0}),t=r.runId}return e}function y1(n){if(!n)return"unknown time";let e=Date.parse(n);return Number.isNaN(e)?"unknown time":`${new Date(e).toISOString().slice(0,16)}Z`}function xC(n){if(n<1e3)return String(n);let e=n/1e3;return e<100?`${e.toFixed(1)}k`:`${Math.round(e)}k`}function w1(n){return n.usedBefore===void 0||n.usedAfter===void 0?"":` ${xC(n.usedBefore)} \u2192 ${xC(n.usedAfter)}`}function CC(n){let{runs:e,unknownCount:t}=n,r=[];if(e.length>0){r.push(e.length===1?"Compacted 1 time:":`Compacted ${e.length} times:`);for(let s of e){let o=w1(s),i=s.cost!==void 0?` $${s.cost.toFixed(2)}`:"",a=s.current?" (current)":"",d=s.swaps>1?` (${s.swaps} swaps)`:"";r.push(` ${y1(s.at)} ${s.upstreamSessionId}${o}${i}${d}${a}`)}}if(t>0){let s=t===1?"rotation":"rotations";r.push(e.length>0?`${t} earlier ${s}, cause not recorded; the count above is a lower bound.`:`No compactions on record. ${t} ${s} predate reason tracking, and any of them may have been a compaction.`)}return r}var RC=q(()=>{"use strict"});import*as oi from"path";function b1(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mw(n,e,t){if(e.length===0||e===t)return{text:n,rewritten:[]};let r=e.endsWith("/")?e.slice(0,-1):e,s=t.endsWith("/")?t.slice(0,-1):t,o=[],i=new RegExp(`${b1(r)}/(?![/\\s])`,"g");return{text:n.replace(i,(d,c)=>{let l=n.slice(c+d.length),u=l.search(/[\s"'`,;:)\]}]|$/);return o.push(`${r}/${l.slice(0,u<0?void 0:u)}`),`${s}/`}),rewritten:o}}function _w(n,e){if(e.length===0)return!1;let t=e.endsWith("/")?e.slice(0,-1):e;return n.includes(t)}function AC(n){let e=[];return e.push("[workspace] You have LEFT the isolated workspace."),e.push(`- Your working directory is now ${n.sourceCwd}`),e.push(n.removed?`- The workspace at ${n.formerWorkspacePath} has been removed. Paths under it from earlier in this conversation no longer exist.`:`- The workspace at ${n.formerWorkspacePath} still exists but is NO LONGER YOURS. Editing anything under it is wasted: that work will not reach ${n.sourceCwd}.`),e.push("- Earlier turns refer to files by their workspace paths. Treat those as referring to the same files under your current working directory, and prefer repo-relative paths from here on."),e.join(`
|
|
42
42
|
`)}function TC(n){let e=[];e.push(n.reassert===!0?"[workspace] Reminder: you are NOT working in the directory that path names.":"[workspace] Before anything else, note where you are working:"),e.push(`- Your working directory is ${n.workspacePath}`),e.push(`- It is an isolated copy of ${n.sourceCwd}`),e.push(`- Any absolute path under ${n.sourceCwd} refers to the matching file under your working directory. Do not read or write ${n.sourceCwd} directly.`),e.push("- Prefer repo-relative paths (`src/foo.ts`). They are identical in both trees, so they cannot be misread.");for(let t of n.notes)e.push(`- ${t}`);return e.join(`
|
|
43
|
-
`)}function EC(n,e,t){return n.length===0||!oi.isAbsolute(n)||Ep(n,t)?!1:Ep(n,e)}function Ep(n,e){let t=oi.relative(oi.resolve(e),oi.resolve(n));return!(t.length===0||t.startsWith("..")||oi.isAbsolute(t))}var PC=q(()=>{"use strict"});import*as
|
|
43
|
+
`)}function EC(n,e,t){return n.length===0||!oi.isAbsolute(n)||Ep(n,t)?!1:Ep(n,e)}function Ep(n,e){let t=oi.relative(oi.resolve(e),oi.resolve(n));return!(t.length===0||t.startsWith("..")||oi.isAbsolute(t))}var PC=q(()=>{"use strict"});import*as Hs from"fs/promises";async function Ql(n,e){let t=D.queueFile(n);if(e.length===0){await Hs.unlink(t).catch(()=>{});return}await Hs.mkdir(D.sessionDir(n),{recursive:!0});let r=e.map(s=>JSON.stringify(s)).join(`
|
|
44
44
|
`)+`
|
|
45
|
-
`;await
|
|
46
|
-
`))if(s.trim())try{let o=JSON.parse(s);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&r.push(o)}catch{}return r}async function _C(n){let e=D.queueFile(n);await
|
|
47
|
-
`).map(t=>t.trim()).filter(t=>t!=="");return e.length===0?"":e[e.length-1]}function jC(n){let e=n;if(e?.code!==G.InternalError)return;let t=e.data?.details;return`${typeof e.message=="string"?e.message:""} ${typeof t=="string"?t:""}`.toLowerCase()}function F1(n){let e=jC(n);return e!==void 0&&O1.some(t=>e.includes(t))}function N1(n){let e=jC(n);return e!==void 0&&L1.some(t=>e.includes(t))}function Qn(n,e){return n.code=e,n}function B1(n,e,t){return t?.run_in_background===!0?!1:e?.toolName==="Monitor"||n==="Monitor"||typeof e?.toolResponse?.taskId=="string"}function H1(n){return typeof n!="string"?void 0:/Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(n)?.[1]}function U1(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n.claudeCode;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r={};return t.toolName!==void 0&&(r.toolName=t.toolName),t.toolResponse&&typeof t.toolResponse=="object"&&(r.toolResponse=t.toolResponse),r}function Lw(n,e){if(n!=="session/update")return!1;let r=(e??{}).update?.sessionUpdate;return typeof r=="string"&&D1.has(r)}function W1(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 j1(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 q1(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 Xl(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t,s=typeof r.modelId=="string"&&r.modelId.trim()||typeof r.value=="string"&&r.value.trim()||typeof r.id=="string"&&r.id.trim()||void 0;if(!s)continue;let o={modelId:s};typeof r.name=="string"&&r.name.length>0&&(o.name=r.name),typeof r.description=="string"&&r.description.length>0&&(o.description=r.description),e.push(o)}return e}function Mp(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t,s=typeof r.value=="string"&&r.value.trim()||typeof r.id=="string"&&r.id.trim()||void 0;if(!s)continue;let o={id:s};typeof r.name=="string"&&r.name.length>0&&(o.name=r.name),typeof r.description=="string"&&r.description.length>0&&(o.description=r.description),e.push(o)}return e}function Bw(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t,s=typeof r.value=="string"&&r.value.trim()||typeof r.id=="string"&&r.id.trim()||void 0;if(!s)continue;let o=typeof r.name=="string"&&r.name.trim()?r.name.trim():s,i={value:s,name:o};typeof r.description=="string"&&r.description.length>0&&(i.description=r.description),e.push(i)}return e}function z1(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="_hydra_available_modes_update")return null;let r=t.availableModes;if(!Array.isArray(r))return[];let s=[];for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),s.push(a)}return s}function K1(n,e){let r=(e??{}).update??{},s=r.sessionUpdate;if(s==="agent_message_chunk"){let o=r.content??{};typeof o.text=="string"&&(n.chunks.push(o.text),n.messageChars+=o.text.length);return}if(s==="agent_thought_chunk"){let o=r.content??{};typeof o.text=="string"&&(n.thinkingChars+=o.text.length);return}if(s==="tool_call"){n.toolCalls++;return}if(s==="usage_update"){typeof r.used=="number"&&(n.lastUsed=r.used),typeof r.size=="number"&&(n.lastSize=r.size);return}}function G1(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let r=t.availableCommands??t.commands;if(!Array.isArray(r))return[];let s=[];for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),s.push(a)}return s}function J1(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:
|
|
45
|
+
`;await Hs.writeFile(t,r,"utf8")}async function MC(n){let e=D.queueFile(n),t;try{t=await Hs.readFile(e,"utf8")}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[];for(let s of t.split(`
|
|
46
|
+
`))if(s.trim())try{let o=JSON.parse(s);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&r.push(o)}catch{}return r}async function _C(n){let e=D.queueFile(n);await Hs.unlink(e).catch(()=>{})}var $w=q(()=>{"use strict";ke()});import{customAlphabet as BC}from"nanoid";import*as WC from"fs/promises";function Us(){return`m_${UC()}`}function st(n){let e=Bs(n)?.localId??n;return e.startsWith(sn)?e.slice(sn.length):e}function A1(n){let e=n?.update;if(!e||typeof e!="object"||e.sessionUpdate!=="usage_update")return!1;let t=e._meta;if(!t||typeof t!="object")return!1;let r=t["_claude/origin"];if(!r||typeof r!="object")return!1;let s=r.kind;return typeof s=="string"&&R1.has(s)}function OC(n){let e=n?.update;return!!e&&typeof e=="object"&&e.sessionUpdate==="usage_update"}function T1(n){let e=n?.update;return!!e&&typeof e=="object"&&e.sessionUpdate==="tool_call_update"}function E1(n,e){return e===void 0?!1:n.some(t=>{if(!t||typeof t!="object")return!1;let r=t.id;return typeof r=="string"&&r.trim()!==""&&r.trim()!==e})}function P1(n){let e=n.split(`
|
|
47
|
+
`).map(t=>t.trim()).filter(t=>t!=="");return e.length===0?"":e[e.length-1]}function jC(n){let e=n;if(e?.code!==G.InternalError)return;let t=e.data?.details;return`${typeof e.message=="string"?e.message:""} ${typeof t=="string"?t:""}`.toLowerCase()}function F1(n){let e=jC(n);return e!==void 0&&O1.some(t=>e.includes(t))}function N1(n){let e=jC(n);return e!==void 0&&L1.some(t=>e.includes(t))}function Qn(n,e){return n.code=e,n}function B1(n,e,t){return t?.run_in_background===!0?!1:e?.toolName==="Monitor"||n==="Monitor"||typeof e?.toolResponse?.taskId=="string"}function H1(n){return typeof n!="string"?void 0:/Command running in background with ID: ([A-Za-z0-9_-]+)/.exec(n)?.[1]}function U1(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n.claudeCode;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r={};return t.toolName!==void 0&&(r.toolName=t.toolName),t.toolResponse&&typeof t.toolResponse=="object"&&(r.toolResponse=t.toolResponse),r}function Lw(n,e){if(n!=="session/update")return!1;let r=(e??{}).update?.sessionUpdate;return typeof r=="string"&&D1.has(r)}function W1(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 j1(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 q1(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 Xl(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t,s=typeof r.modelId=="string"&&r.modelId.trim()||typeof r.value=="string"&&r.value.trim()||typeof r.id=="string"&&r.id.trim()||void 0;if(!s)continue;let o={modelId:s};typeof r.name=="string"&&r.name.length>0&&(o.name=r.name),typeof r.description=="string"&&r.description.length>0&&(o.description=r.description),e.push(o)}return e}function Mp(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t,s=typeof r.value=="string"&&r.value.trim()||typeof r.id=="string"&&r.id.trim()||void 0;if(!s)continue;let o={id:s};typeof r.name=="string"&&r.name.length>0&&(o.name=r.name),typeof r.description=="string"&&r.description.length>0&&(o.description=r.description),e.push(o)}return e}function Bw(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t,s=typeof r.value=="string"&&r.value.trim()||typeof r.id=="string"&&r.id.trim()||void 0;if(!s)continue;let o=typeof r.name=="string"&&r.name.trim()?r.name.trim():s,i={value:s,name:o};typeof r.description=="string"&&r.description.length>0&&(i.description=r.description),e.push(i)}return e}function z1(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="_hydra_available_modes_update")return null;let r=t.availableModes;if(!Array.isArray(r))return[];let s=[];for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),s.push(a)}return s}function K1(n,e){let r=(e??{}).update??{},s=r.sessionUpdate;if(s==="agent_message_chunk"){let o=r.content??{};typeof o.text=="string"&&(n.chunks.push(o.text),n.messageChars+=o.text.length);return}if(s==="agent_thought_chunk"){let o=r.content??{};typeof o.text=="string"&&(n.thinkingChars+=o.text.length);return}if(s==="tool_call"){n.toolCalls++;return}if(s==="usage_update"){typeof r.used=="number"&&(n.lastUsed=r.used),typeof r.size=="number"&&(n.lastSize=r.size);return}}function G1(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let r=t.availableCommands??t.commands;if(!Array.isArray(r))return[];let s=[];for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),s.push(a)}return s}function J1(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:Us()}}}function V1(n,e){if(n.length<=e)return n;let t=n.length-e;for(let r=t;r>=0;r--)if(n[r]?.params?.update?.sessionUpdate==="prompt_received")return n.slice(r);return n.slice(t)}function Y1(n,e){for(let t=n.length-1;t>=0;t--)if(n[t]?.seq===e)return t;return-1}function _p(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t];if(!r||r.method!=="session/update")continue;if(r.params?.update?.messageId===e)return t}return-1}function LC(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 Q1(n){let e=X1(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=Z1(n.resolver),t}function X1(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 r={kind:t},s=e.optionId;typeof s=="string"&&(r.optionId=s);let o=e.reason;return typeof o=="string"&&(r.reason=o),r}function Z1(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 ua(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function NC(n,e){return n.map(t=>{if(t&&typeof t=="object"&&typeof t.text=="string"){let r=t;return{...r,text:e(r.text)}}return t})}function Nw(n,e){let t=n.findIndex(o=>o&&typeof o=="object"&&typeof o.text=="string");if(t<0)return n;let r=n[t],s=[...n];return s[t]={...r,text:`${e}${r.text}`},s}function Dw(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function tN(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function DC(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(s=>s.value.length)),r=n.options.map(s=>{let o=s.value===n.currentValue?"\u25B6":"\xB7",i=s.name&&s.name!==s.value,a=i?s.value.padEnd(t):s.value;return i?` ${o} ${a} ${s.name}`:` ${o} ${a}`});return`${e}
|
|
48
48
|
${r.join(`
|
|
49
49
|
`)}`}function Hw(n,e){for(let t of n.split(/\r?\n/)){let r=t.trim();if(r)return r.length>e?`${r.slice(0,e)}\u2026`:r}}var HC,UC,Ow,k1,v1,S1,x1,sn,$C,I1,Pp,C1,R1,Fw,M1,_1,$1,yc,O1,L1,FC,D1,eN,ir=q(()=>{"use strict";Gl();kw();sC();Jl();cC();lC();Rp();Kl();pC();gC();SC();RC();PC();$w();fn();cc();HC="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",UC=BC(HC,16),Ow=BC(HC,16),k1=20,v1=20,S1=5,x1=32,sn="hydra_session_";$C=["start","merge","apply","sync","stop","detach","discard","clean","status"],I1=1e3,Pp=300*1e3,C1=64,R1=new Set(["task-notification","peer","coordinator","observer","observer-activity"]);Fw=120;M1=128,_1=new Set(["local_bash"]),$1=1e3,yc=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;modelVerb=Ns;modelVerbConfirmed=!1;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;agentTurnInFlight=!1;swapInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleWorkspaceSnapshotHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getUpstreamGenerationsHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;lastUnsolicitedCancelAt=0;cancelReopenStreak=0;static UNSOLICITED_REOPEN_WINDOW_MS=1e4;static UNSOLICITED_REOPEN_LIMIT=3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}_titleSeedPending=!0;_upstreamRespawned=!1;promptStartedAt;turnRanTool=!1;unsolicitedTurn;pendingSteerDetach;supersededAutonomousTurn;autonomousSalvage;lastBackgroundTask;toolLabels=new Map;armedTasks=new Map;lastArmedBroadcast;liveBackgroundTasks=new Map;sawBackgroundTaskLevel=!1;sawTurnComplete=!1;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;orphanTimeoutMs;orphanTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;lastSeq=0;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;persistWatermarkHook;uncompactHook;forkHook;mcpServersConfig;forwardedEnv;workspace;workspaceError;workspaceNotes=[];workspaceHook;workspacePreambleSent=!1;formerWorkspace;departureNoteSent=!1;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new xp;filesEditedSeen=new Set;openToolCalls=new Map;agentChangeHandlers=[];retiringGenerationCost;retiringGenerationUsed;rotationLifetimeCost;agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];configOptionsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;costLedgerProbe;get persistableUsage(){if(!(!this._currentUsage&&!this.cumulativeCost))return{...this._currentUsage??{},...this.cumulativeCost?{cumulativeCost:this.cumulativeCost}:{cumulativeCost:void 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;pendingTurnNotifiers=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${sn}${UC()}`,this.cwd=e.cwd,this.workspace=e.workspace,this.workspaceError=e.workspaceError,this.workspaceHook=e.workspaceHook,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.scheduleWorkspaceSnapshotHook=e.scheduleWorkspaceSnapshot,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getUpstreamGenerationsHook=e.getUpstreamGenerations,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.reloadsUpstreamLedger&&this.armCostLedgerProbe(),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]),e.agentConfigOptions&&e.agentConfigOptions.length>0&&(this.agentAdvertisedConfigOptions=[...e.agentConfigOptions]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.orphanTimeoutMs=e.orphanTimeoutMs??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.persistWatermarkHook=e.persistWatermarkHook,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._titleSeedPending=!1),e.upstreamRespawned&&(this._upstreamRespawned=!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??I1,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.resetModelVerb(e.modelVerb),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:"_hydra_available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"_hydra_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,t){this.resetBackgroundTaskLevel(),t?.respawn&&(this._upstreamRespawned=!0),e.connection.onNotification("session/update",r=>{if(this.internalPromptCapture){K1(this.internalPromptCapture,r);return}this.maybeEmitToolEdges(r),this.runResponseChain(r)}),e.connection.onNotification("_claude/sdkMessage",r=>{this.applyBackgroundTaskLevel(r)}),e.connection.onRequest("session/request_permission",async r=>{let s=await this.runAgentRequestChain("session/request_permission",r),o=LC(s.shortCircuit?r:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:o??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:o??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(r=>{this.handleOrphanError(r)}),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,r=0,s="session/update"){let o=e,i=s==="session/update"?this.injectCumulativeCost(e):e,a=`response:${s}`;for(let l=r;l<this.transformChain.length;l++){let u=this.transformChain[l];if(t.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${Ow()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:s,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(h){this.logger?.warn(`transformer ${u.name} error on ${a}: ${h.message}`);continue}let m=p?.action??"continue";if(m==="stop")return;if(m==="processing"){let h=l,g=i,w=new Set(t),b=s;await new Promise(k=>{let S=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(g,new Set([...w,u.name]),h+1,b).then(()=>k()).catch(()=>k()))},Pp);typeof S.unref=="function"&&S.unref(),this.pendingClaims.set(f,{resolve:()=>k(),timer:S,transformerName:u.name,method:b,envelope:g,chainIdx:h,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(i=p.payload),t.add(u.name)}if(s!=="session/update")return;this.noteAgentActivity(i),fC(i.update)&&this.armRecallInPlace().catch(l=>{this.logger?.warn(`armRecallInPlace failed: ${l.message}`)});let d=G1(i);if(d!==null){this.setAgentAdvertisedCommands(d);return}let c=z1(i);if(c!==null){this.setAgentAdvertisedModes(c);return}if(this.noteModelVerbHint(rC(i.update),"session/update"),this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(o)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}async armRecallInPlace(){if(!this.historyStore)return;let e=await this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0);if(!(e<=(this._summarizedThroughEntry??0))){if(this._summarizedThroughEntry=e,this.persistWatermarkHook)try{this.persistWatermarkHook(e)}catch(t){this.logger?.warn(`armRecallInPlace: persistWatermarkHook failed: ${t.message}`)}this.broadcastQueueNotification("hydra-acp/context_self_compacted",{sessionId:this.sessionId})}}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let r of this.clients.values()){if(e&&r.clientId===e)continue;let s={clientId:r.clientId};r.clientInfo?.name&&(s.name=r.clientInfo.name),r.clientInfo?.version&&(s.version=r.clientInfo.version),t.push(s)}return t}get turnStartedAt(){return this.promptStartedAt}get inUnsolicitedTurn(){return this.unsolicitedTurn!==void 0}get agentPid(){return this.agent.pid}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return await this.quiesceBlocker()===void 0}async quiesceBlocker(){if(this.agentTurnInFlight)return"the agent is still working; wait for the current turn to finish, then try again";if(this.unsolicitedTurn!==void 0)return"the agent is part-way through a turn it started by itself; wait for it to finish or interrupt it (^C), then try again";if(this.internalPromptCapture!==void 0)return"hydra is driving the agent right now (compaction seed or transcript injection); this clears by itself, so try again in a moment";if(this.modelChangeInFlight)return"a model change is still settling; try again in a moment";if(this.modeChangeInFlight)return"a mode change is still settling; try again in a moment";let e=this.pendingOneShotBackgroundTasks();if(e.length>0)return`${e.length} background task(s) still running (${e.join(", ")}); a swap would kill the agent process and abandon them. Wait for them to finish, or cancel them, then try again`;let t=await this.openToolCallIdsInHistory();if(t.length>0)return`${t.length} tool call(s) from an earlier turn never reported a result, so the session still reads as busy. ^C closes an abandoned chain; failing that it clears as new history accumulates`}isQuiescedSync(){return!(this.promptInFlight||this.unsolicitedTurn!==void 0||this.modeChangeInFlight||this.modelChangeInFlight)}async swapIntoWorkspace(e){await this.swapUpstream({...e.synopsis!==void 0?{artifact:e.synopsis}:{},note:e.note,framing:"swap",...e.title!==void 0?{title:e.title}:{},tailK:8,tailFloor:4,summarizedThroughEntry:e.historyLength,newCwd:e.cwd,reason:e.workspace!==void 0?"workspace-enter":"workspace-leave"}),this.workspace=e.workspace,e.left!==void 0?(this.formerWorkspace={path:e.left.path,sourceCwd:e.cwd,removed:e.left.removed},this.departureNoteSent=!1):this.formerWorkspace=void 0}async swapUpstream(e){let t=await this.quiesceBlocker();if(t!==void 0)throw new Error(`session is not quiesced for swap: ${t}`);if(this.swapInFlight)throw new Error("a swap is already in progress for this session");this.swapInFlight=!0;try{await this.doSwapUpstream(e)}finally{this.swapInFlight=!1}}async doSwapUpstream(e){this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let t=this.agentId,r=e.newAgentId??this.agentId,s=r!==this.agentId,o=e.reason!==void 0&&e.reason!=="compaction"?e.reason:s?"agent-swap":"compaction",i=e.newCwd??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:i,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:f});if(this.accumulateAndResetCost(),this.cwd=i,this.wireAgent(p.agent,{respawn:!0}),!s){let F=await la({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(F.result,"model"),await ca({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})}p.agent.connection.drainBuffered("session/update");let m=[];if(this.historyStore)try{m=await this.historyStore.load(this.sessionId)}catch(F){this.logger?.warn(`swapUpstream: historyStore.load failed: ${F.message}`)}let h=Pw({...e.artifact!==void 0?{synopsis:e.artifact}:{},...e.note!==void 0?{note:e.note}:{},...e.framing!==void 0?{framing:e.framing}:{},title:e.title,tail:m,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{},recallArmed:(e.summarizedThroughEntry??this._summarizedThroughEntry??0)>0});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};let g,w;try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:h}]});let F=this.internalPromptCapture;g=F.lastUsed,w=F.lastSize,this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${h.length} toolCalls=${F.toolCalls} thinkingChars=${F.thinkingChars} messageChars=${F.messageChars} used=${F.lastUsed??"?"} size=${F.lastSize??"?"} reply=${JSON.stringify(F.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}g!==void 0&&(this.maybeApplyAgentUsage({update:{sessionUpdate:"usage_update",used:g,...w!==void 0?{size:w}:{}}}),this.broadcastCurrentUsage());let b=this.upstreamSessionId,k=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let S=this.agent;if(this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,this.resetModelVerb(p.modelVerb),s&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[]),this.agentAdvertisedConfigOptions=p.initialConfigOptions??[]),this.broadcastMergedCommands(),this.broadcastConfigOptions(),this.notifyAgentChange("swapUpstream",o,e.runId,g),e.summarizedThroughEntry!==void 0&&this.persistWatermarkHook)try{this.persistWatermarkHook(e.summarizedThroughEntry)}catch(F){this.logger?.warn(`swapUpstream: persistWatermarkHook failed: ${F.message}`)}if(!s&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:b,...k!==void 0?{previousSummarizedThroughEntry:k}:{},...e.runId!==void 0?{runId:e.runId}:{}})}catch(F){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${F.message}`)}let I=await this.retireAgent(S,s?"agent switch":e.reason==="workspace-enter"||e.reason==="workspace-leave"?"workspace move":"compaction swap");this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:b,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),s||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),s&&this.broadcastAgentSwitch(t,r);let x=I.length>0?`
|
|
50
50
|
Stopped ${I.length} background task(s) with the previous agent: ${I.join(", ")}. Re-arm anything still needed.
|
|
@@ -56,7 +56,7 @@ Compaction completed.
|
|
|
56
56
|
|
|
57
57
|
`),this.departureNoteSent=!0}return s}applyWorkspacePromptRewrite(e){let t=this.workspace;if(t===void 0)return this.applyDepartedPromptRewrite(e);let r=!1,s=NC(e,i=>_w(i,t.sourceCwd)?(r=!0,Mw(i,t.sourceCwd,t.path).text):i);if(!this.workspacePreambleSent||r){let i=TC({workspacePath:t.path,sourceCwd:t.sourceCwd,notes:this.workspaceNotes,...this.workspacePreambleSent?{reassert:!0}:{}});s=Nw(s,`${i}
|
|
58
58
|
|
|
59
|
-
`),this.workspacePreambleSent=!0}return s}async prompt(e,t,r,s){let o=this.clients.get(e);if(!o)throw Qn(new Error("client not attached"),G.SessionNotFound);if(this.closing)throw Qn(new Error("session is closing; new prompts cannot be accepted"),G.SessionClosing);let i=Hs();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Pn((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0,this.cancelOrphanTimer();for(let d of this.interactiveHandlers)try{d(!0)}catch{}}return this.enqueueUserPrompt(o,t,i,r,s)}broadcastPromptReceived(e){this.closeUnsolicitedTurn("superseded",`prompt:${e.messageId}`);let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),e.originator.fromSession&&(t.fromSession=e.originator.fromSession),e.originator.fromSessionTitle&&(t.fromSessionTitle=e.originator.fromSessionTitle),e.originator.fromLabel&&(t.fromLabel=e.originator.fromLabel),e.originator.depth!==void 0&&(t.depth=e.originator.depth),this.promptStartedAt=Date.now(),this.turnRanTool=!1,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let r=ua(e.prompt);r.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:r},_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 s={};typeof e.costAmount=="number"&&(s.amount=e.costAmount),typeof e.costCurrency=="string"&&(s.currency=e.costCurrency),t.cost=s}if(Object.keys(t).length<=1)return;t._meta={"hydra-acp":{upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}};let r={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:r,recordedAt:Date.now()}).catch(()=>{})}originatorNeedsTurnComplete(e){return e.wasAmend===!0||e.wasSteer===!0}broadcastTurnComplete(e,t,r,s){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Hs()};o!==void 0&&(i.stopReason=o);let a=Pn(t?._meta).salvaged;a!==void 0&&(i._meta={[ut]:{salvaged:a}}),this.supersededAutonomousTurn=void 0;let d=this.amendInProgress;if(d&&r!==void 0&&d.cancelledMessageId===r&&(i._meta={[ut]:{...a!==void 0?{salvaged:a}:{},amended:{cancelledMessageId:d.cancelledMessageId,newMessageId:d.newMessageId}}}),this.promptStartedAt=void 0,this.sawTurnComplete=!0,this.scheduleWorkspaceSnapshotHook?.(),r!==void 0&&o!==void 0){this.recordTerminal(r,o);let c=this.pendingTurnNotifiers.get(r);c&&(this.pendingTurnNotifiers.delete(r),vw(c,{sessionId:this.sessionId,messageId:c.originalMessageId,stopReason:o,deliveredAt:Date.now(),...r!==c.originalMessageId?{amendedTo:r}:{}}))}o==="cancelled"||o==="error"||o==="refusal"?this.closeOpenToolCalls(o):this.armOpenToolCalls(),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},s?void 0:e),d&&r!==void 0&&d.cancelledMessageId===r&&this.broadcastPromptAmended(d)}noteAgentActivity(e){if(!(this.closing||this.closed)){if(A1(e)||this.steerCausedTurnTerminal(e)){if(this.unsolicitedTurn!==void 0){this.closeUnsolicitedTurn("completed");return}this.salvageSupersededTerminal();return}this.pendingSteerDetach!==void 0&&this.currentEntry?.messageId===this.pendingSteerDetach.messageId&&OC(e)&&(this.pendingSteerDetach=void 0),!Lw("session/update",e)&&(this.noteBackgroundTaskArming(e),this.unsolicitedTurn===void 0&&(this.promptInFlight||!this.sawTurnComplete||T1(e)||this.openUnsolicitedTurn()))}}steerCausedTurnTerminal(e){return this.unsolicitedTurn?.steerCaused!==!0?!1:OC(e)}noteBackgroundTaskArming(e){let t=e?.update;if(!t||typeof t!="object")return;let r=typeof t.toolCallId=="string"?t.toolCallId:void 0;if(r===void 0)return;let s=t.rawInput,o=U1(t._meta);this.rememberToolLabel(r,t,s,o),this.noteBackgroundTaskStopped(t,s,o);let i=typeof o?.toolResponse?.taskId=="string"?o.toolResponse.taskId:H1(t.rawOutput);if(!(i!==void 0||s!==void 0&&s.run_in_background===!0))return;let d=this.toolLabels.get(r)?.label??"background task";this.lastBackgroundTask={toolCallId:r,label:d};let c=Date.now(),l=this.armedTasks.get(r),u=i??l?.taskId,f=B1(t.title,o,s)||l?.repeating===!0;this.armedTasks.set(r,{label:d,...u!==void 0?{taskId:u}:{},repeating:f,armedAt:l?.armedAt??c}),this.onArmedTasksChanged()}applyBackgroundTaskLevel(e){let t=e?.message;if(!t||t.subtype!=="background_tasks_changed")return;let r=t.tasks;if(!Array.isArray(r))return;let s=Date.now(),o=new Map;for(let a of r){let d=a,c=typeof d?.task_id=="string"?d.task_id:void 0;c!==void 0&&o.set(c,{taskType:typeof d?.task_type=="string"?d.task_type:"unknown",description:typeof d?.description=="string"?d.description:"",firstSeen:this.liveBackgroundTasks.get(c)?.firstSeen??s})}let i=[...this.liveBackgroundTasks.keys()].filter(a=>!o.has(a));this.liveBackgroundTasks=o,this.sawBackgroundTaskLevel=!0,this.logger?.info(`session ${this.sessionId} background level: ${o.size} live`+(i.length>0?` (ended: ${i.join(", ")})`:"")),this.onArmedTasksChanged()}get armedBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.entries()].map(([e,t])=>({taskId:e,label:t.description||t.taskType,taskType:t.taskType,since:t.firstSeen})):[...this.armedTasks.entries()].map(([e,t])=>({toolCallId:e,label:t.label,...t.taskId!==void 0?{taskId:t.taskId}:{},since:t.armedAt}))}pendingOneShotBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.values()].filter(e=>_1.has(e.taskType)).map(e=>e.description||e.taskType):[...this.armedTasks.values()].filter(e=>!e.repeating).map(e=>e.label)}get armedSince(){let e;if(this.sawBackgroundTaskLevel){for(let t of this.liveBackgroundTasks.values())(e===void 0||t.firstSeen<e)&&(e=t.firstSeen);return e}for(let t of this.armedTasks.values())(e===void 0||t.armedAt<e)&&(e=t.armedAt);return e}onArmedTasksChanged(){let e=this.armedBackgroundTasks,t=e.length,r=this.armedSince,s=e.map(o=>o.taskId??o.toolCallId??o.label).sort().join("\0");s===this.lastArmedBroadcast?.key&&r===this.lastArmedBroadcast?.since||this.closed||(this.lastArmedBroadcast={key:s,since:r},this.broadcastQueueNotification("hydra-acp/session/armed_tasks_updated",{sessionId:this.sessionId,count:t,...r!==void 0?{since:r}:{},tasks:e}),this.dispatchIdle())}async retireAgent(e,t){return await e.kill().catch(()=>{}),this.resetBackgroundTaskLevel(),this.discardArmedTasks(t)}resetBackgroundTaskLevel(){this.liveBackgroundTasks.clear(),this.sawBackgroundTaskLevel=!1}discardArmedTasks(e){if(this.armedTasks.size===0)return[];let t=[...this.armedTasks.values()].map(r=>r.label);for(let[r,s]of this.armedTasks)s.openToolCall===!0&&this.openToolCalls.delete(r);return this.armedTasks.clear(),this.logger?.info(`session ${this.sessionId} discarded ${t.length} armed task(s) on ${e}: ${t.join(", ")}`),this.onArmedTasksChanged(),t}noteBackgroundTaskStopped(e,t,r){if(!(r?.toolName==="TaskStop"||e.title==="TaskStop"))return;let o=t?.task_id;if(typeof o!="string"||o.length===0)return;let i=!1;for(let[a,d]of this.armedTasks)d.taskId===o&&(this.armedTasks.delete(a),i=!0);i&&this.onArmedTasksChanged()}rememberToolLabel(e,t,r,s){let o=r!==void 0&&typeof r.description=="string"&&r.description?r.description:void 0;if(o!==void 0)this.toolLabels.set(e,{label:o.slice(0,Fw),fromDescription:!0});else if(this.toolLabels.get(e)?.fromDescription!==!0){let i=typeof t.title=="string"&&t.title?t.title:typeof s?.toolName=="string"&&s.toolName?s.toolName:void 0;i!==void 0&&this.toolLabels.set(e,{label:i.slice(0,Fw),fromDescription:!1})}for(;this.toolLabels.size>M1;){let i=this.toolLabels.keys().next().value;if(i===void 0)break;this.toolLabels.delete(i)}}openUnsolicitedTurn(){let e=Date.now();if(this.lastUnsolicitedCancelAt!==0&&e-this.lastUnsolicitedCancelAt<=n.UNSOLICITED_REOPEN_WINDOW_MS?this.cancelReopenStreak+=1:this.cancelReopenStreak=0,this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak>=n.UNSOLICITED_REOPEN_LIMIT){this.escalateUnresponsiveCancel();return}let t=this.lastBackgroundTask,r=!1;for(let[i,a]of this.armedTasks)a.repeating||a.openToolCall===!0||(this.armedTasks.delete(i),r=!0);r&&this.onArmedTasksChanged();let s={messageId:Hs(),startedAt:e,cause:t,steerCaused:this.pendingSteerDetach!==void 0};this.pendingSteerDetach=void 0,this.unsolicitedTurn=s,this.promptStartedAt=e,this.logger?.info(`session ${this.sessionId} agent resumed with no prompt in flight`+(t?` (after ${t.label})`:""));let o={unsolicited:!0};t&&(o.cause=t),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"_hydra_turn_started",messageId:s.messageId,_meta:{"hydra-acp":o}}})}async holdForUnsolicitedTurn(e){if(this.unsolicitedTurn===void 0){this.logger?.info(`session ${this.sessionId} queue hold skipped for ${e.messageId} (no unsolicited turn open)`);return}let t=Date.now(),r=this.unsolicitedTurn.cause;this.logger?.info(`session ${this.sessionId} holding ${e.messageId} behind unsolicited turn ${this.unsolicitedTurn.messageId}`+(r?` cause=${JSON.stringify(r.label)}`:"")),this.broadcastQueueNotification("hydra-acp/prompt_queue/held",{sessionId:this.sessionId,messageId:e.messageId,reason:"agent_resumed",...r?{cause:r}:{}});let s="turn_ended";for(;;){if(this.closing||this.closed){s="closing";break}if(e.cancelled){s="cancelled";break}if(this.unsolicitedTurn===void 0){s="turn_ended";break}await new Promise(i=>{let a=setTimeout(i,$1);typeof a.unref=="function"&&a.unref()})}let o=Date.now()-t;this.logger?.info(`session ${this.sessionId} released ${e.messageId} reason=${s} heldMs=${o}`),this.broadcastQueueNotification("hydra-acp/prompt_queue/released",{sessionId:this.sessionId,messageId:e.messageId,reason:s,heldMs:o})}closeUnsolicitedTurn(e,t){let r=this.unsolicitedTurn;if(r===void 0)return;let s=Date.now()-r.startedAt;this.unsolicitedTurn=void 0,this.promptStartedAt=void 0,e==="cancelled"?this.lastUnsolicitedCancelAt=Date.now():(this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak=0),this.logger?.info(`session ${this.sessionId} unsolicited turn ${r.messageId} closed reason=${e} durationMs=${s}`+(t?` by=${t}`:"")+(r.cause?` cause=${JSON.stringify(r.cause.label)}`:"")),e==="superseded"&&(this.supersededAutonomousTurn={turnMessageId:r.messageId,cause:r.cause,supersededAt:Date.now()}),this.recordCurrentUsageSnapshot(),!this.closed&&(e==="cancelled"?this.closeOpenToolCalls("cancelled"):e==="completed"&&this.armOpenToolCalls(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"_hydra_turn_ended",messageId:Hs(),startedMessageId:r.messageId,durationMs:s,_meta:{"hydra-acp":{unsolicited:!0,reason:e}}}}))}salvageSupersededTerminal(){let e=this.supersededAutonomousTurn;if(e===void 0)return;this.supersededAutonomousTurn=void 0;let t=this.autonomousSalvage;t!==void 0&&(this.autonomousSalvage=void 0,this.logger?.warn(`session ${this.sessionId} salvaged session/prompt from autonomous terminal (superseded turn ${e.turnMessageId}, ${Date.now()-e.supersededAt}ms earlier)`+(e.cause?` cause=${JSON.stringify(e.cause.label)}`:"")),t({stopReason:"end_turn",_meta:{[ut]:{salvaged:{reason:"autonomous_terminal",supersededMessageId:e.turnMessageId}}}}))}async awaitPromptResponse(e){if(this.supersededAutonomousTurn===void 0)return e;try{return await new Promise((t,r)=>{this.autonomousSalvage=t,e.then(t,r)})}finally{this.autonomousSalvage=void 0}}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>C1;){let r=this.recentlyTerminal.keys().next().value;if(r===void 0)break;this.recentlyTerminal.delete(r)}}registerTurnNotify(e,t,r){let s=this.recentlyTerminal.get(e);if(s)return{alreadyTerminal:!0,stopReason:s.stopReason};for(this.pendingTurnNotifiers.set(e,{callbackUrl:t,secret:r,registeredAt:Date.now(),originalMessageId:e});this.pendingTurnNotifiers.size>x1;){let o=this.pendingTurnNotifiers.keys().next().value;if(o===void 0)break;this.pendingTurnNotifiers.delete(o)}return{alreadyTerminal:!1}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let r={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",r)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(r=>r.messageId===e&&r.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 r=this.visibleQueueDepth(),s=t?.position??Math.max(0,r-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:s,queueDepth:r,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}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 r of this.clients.values())r.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 r of this.promptQueue)r.kind!=="user"||r.cancelled||e.push({messageId:r.messageId,originator:r.originator,prompt:r.prompt,position:t++,enqueuedAt:r.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let r={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(r.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(r.version=t.originator.clientInfo.version);let s={kind:"user",messageId:t.messageId,originator:r,clientId:r.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(s),this.broadcastQueueAdded(s)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(s=>s.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let r=this.promptQueue[t];return r.cancelled=!0,this.promptQueue.splice(t,1),r.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),r.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let r=this.promptQueue.find(s=>s.messageId===e);return!r||r.kind!=="user"?{updated:!1,reason:"not_found"}:(r.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let r=this.clients.get(e);if(!r)throw Qn(new Error("client not attached"),G.SessionNotFound);let{targetMessageId:s,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===s&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(r,o,s,i);let d=this.promptQueue.find(l=>l.messageId===s&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=o,this.broadcastQueueUpdated(s,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:s};let c=this.recentlyTerminal.get(s);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(r,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,r,s){let o=Hs(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),s){let c=[];for(let l of this.promptQueue){if(l.kind==="user"&&!l.cancelled){l.cancelled=!0,this.broadcastQueueRemoved(l.messageId,"cancelled"),l.resolve({stopReason:"cancelled"});continue}c.push(l)}this.promptQueue=c}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:r,position:1}),this.amendInProgress={cancelledMessageId:r,newMessageId:o};let d=this.pendingTurnNotifiers.get(r);return d&&(this.pendingTurnNotifiers.delete(r),this.pendingTurnNotifiers.set(o,d)),this.cancelExtensionDispatch(r,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}async steer(e,t){let r=this.clients.get(e);if(!r)throw Qn(new Error("client not attached"),G.SessionNotFound);let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled;if(s&&this.agent.steeringSupported){this.pendingSteerDetach={messageId:this.currentEntry.messageId};let o;try{o=await this.forwardRequest("_session/steering",t)}catch(d){throw this.pendingSteerDetach=void 0,d}let i=o?.outcome,a=i==="injected"||i==="startedNewTurn"||i==="promptRequired"||i==="failed"?o:{outcome:"failed"};return a.outcome!=="startedNewTurn"&&(this.pendingSteerDetach=void 0),a.outcome==="injected"&&this.recordSteerAsUserMessageChunk(t.prompt,e),a.outcome==="startedNewTurn"?{...a,detached:!0}:a}return s?(this.amendOnHead(r,t.prompt,this.currentEntry.messageId,!1),{outcome:"startedNewTurn"}):t._meta?.steering?.idleBehavior==="promptRequired"?{outcome:"promptRequired",reason:"noRunningTurn"}:(this.prompt(e,{sessionId:t.sessionId,prompt:t.prompt},void 0,{steerOriginated:!0}).catch(o=>{this.logger?.warn(`steer-originated prompt failed to enqueue: ${o.message}`)}),{outcome:"startedNewTurn"})}recordSteerAsUserMessageChunk(e,t){let r=ua(e);r.length!==0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:r},_meta:{"hydra-acp":{steered:!0}}}},t)}enqueueAmendmentAsFollowUp(e,t){let r=Hs(),s={clientId:e.clientId};e.clientInfo?.name&&(s.name=e.clientInfo.name),e.clientInfo?.version&&(s.version=e.clientInfo.version);let o={kind:"user",messageId:r,originator:s,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),r}async cancel(e){if(!this.clients.get(e))throw Qn(new Error("client not attached"),G.SessionNotFound);this.logger?.info(`session ${this.sessionId} session/cancel from ${e} promptInFlight=${this.promptInFlight} agentTurnInFlight=${this.agentTurnInFlight} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length}`),this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),this.closeUnsolicitedTurn("cancelled"),this.agentTurnInFlight||this.closeOpenToolCalls("cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(r=>r.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,r=new Set,s=0,o="request"){let i=this.rewriteForAgent(t);for(let a=s;a<this.transformChain.length;a++){let d=this.transformChain[a];if(r.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${Ow()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return o==="notification"?void 0:u?.payload??Dw(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(i=u.payload),r.add(d.name);continue}if(f==="processing"){let p=a,m=i,h=new Set(r);return new Promise(g=>{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,m,new Set([...h,d.name]),p+1,o).then(g).catch(()=>g(o==="notification"?void 0:Dw(e))))},Pp);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:g,timer:w,transformerName:d.name,method:e,envelope:m,chainIdx:p,originatedBy:h,side:"request",tailKind:o})})}r.add(d.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async forwardModelChange(e,t){let r=await si({request:(s,o)=>this.forwardRequest(s,o),sessionId:this.sessionId,modelId:e,verb:this.modelVerb,extraParams:t,logger:this.logger});return this.modelVerb=r.verb,this.modelVerbConfirmed=!0,r.result}noteModelVerbHint(e,t){e===void 0||this.modelVerbConfirmed||e===this.modelVerb||(this.logger?.info(`model verb for agent ${this.agentId} inferred as ${e} from ${t} (was ${this.modelVerb})`),this.modelVerb=e)}resetModelVerb(e){this.modelVerb=e??Ns,this.modelVerbConfirmed=!1}async runAgentRequestChain(e,t,r=new Set,s=0){let o=t,i=`request:${e}`;for(let a=s;a<this.transformChain.length;a++){let d=this.transformChain[a];if(r.has(d.name)||!d.intercepts.has(i))continue;let c=`t_${Ow()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(f){this.logger?.warn(`transformer ${d.name} error on ${i}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??tN(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(o=l.payload),r.add(d.name);continue}if(u==="processing"){let f=a,p=o,m=new Set(r),h=e;return new Promise(g=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.runAgentRequestChain(h,p,new Set([...m,d.name]),f+1).then(g).catch(()=>g({shortCircuit:!1,envelope:p})))},Pp);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:b=>g({shortCircuit:!0,payload:b}),timer:w,transformerName:d.name,method:h,envelope:p,chainIdx:f,originatedBy:m,side:"agent-request"})})}r.add(d.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let r=this.pendingClaims.get(e);return r?(clearTimeout(r.timer),this.pendingClaims.delete(e),r.resolve(t),!0):!1}keepAliveClaim(e,t){let r=this.pendingClaims.get(e);if(!r)return!1;clearTimeout(r.timer);let s=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Pp,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:r.transformerName}),r.side==="response")this.runResponseChain(r.envelope,new Set([...r.originatedBy,r.transformerName]),r.chainIdx+1).then(()=>r.resolve(void 0)).catch(()=>r.resolve(void 0));else if(r.side==="agent-request")this.runAgentRequestChain(r.method,r.envelope,new Set([...r.originatedBy,r.transformerName]),r.chainIdx+1).then(r.resolve).catch(()=>r.resolve({shortCircuit:!1,envelope:r.envelope}));else{let i=r.tailKind??"request";this.forwardRequest(r.method,r.envelope,new Set([...r.originatedBy,r.transformerName]),r.chainIdx+1,i).then(r.resolve).catch(()=>r.resolve(i==="notification"?void 0:Dw(r.method)))}},s);return typeof o.unref=="function"&&o.unref(),r.timer=o,!0}async emitToChain(e,t,r){let s=this.transformChain.findIndex(a=>a.name===e),o=s>=0?s+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(r,i,o);return}return this.forwardRequest(t,r,i,o)}async emitToQueue(e,t){let r=this.transformChain.findIndex(c=>c.name===e),s=r>=0?r+1:0,o=(t??{}).prompt??[],i=Hs(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((c,l)=>{let u={kind:"user",messageId:i,originator:d,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:s,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){let t=this.turnStartedAt!==void 0;this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1} by=${e.by??"unknown"} midTurn=${t} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length} awaitingPermission=${this.hasPermissionFlag}`),t&&this.logger?.warn(`session ${this.sessionId} closed mid-turn by=${e.by??"unknown"}; the in-flight turn will not settle and the agent is being killed`),this.cancelIdleTimer(),this.cancelOrphanTimer();for(let r of this.pendingClaims.values())clearTimeout(r.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._titleSeedPending=!1,this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let r of this.titleHandlers)try{r(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(!this._titleSeedPending||Pn((e??{})._meta).ancillary===!0||this.promptCarriesSentBy(e))return;let s=ua((e??{}).prompt),o=Hw(s,200);!o||o.startsWith("/")||(this._titleSeedPending=!1,this.setTitle(o))}maybeApplyAgentModel(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="_hydra_current_model_update")return!1;let s=Xl(r.availableModels);s.length>0&&this.setAgentAdvertisedModels(s);let o=typeof r.currentModel=="string"?r.currentModel:typeof r.model=="string"?r.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="config_option_update")return!1;let s=r.configOptions;if(!Array.isArray(s))return!0;for(let i of s)this.applyOneConfigOptionEntry(i);let o=new Set(s.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i&&i!=="model"&&i!=="mode"&&i!=="agent"));return this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id)),this.fireConfigOptionsHandlers(),!0}applyAgentConfigOptionResponse(e,t){let r=e?.configOptions;if(!Array.isArray(r))return!1;let s=JSON.stringify(this.agentAdvertisedConfigOptions);for(let o of r){let i=o?.id;i==="model"||i==="mode"||i==="agent"||this.applyOneConfigOptionEntry(o)}if(E1(r,t)){let o=new Set(r.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i));this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id))}return JSON.stringify(this.agentAdvertisedConfigOptions)!==s}applyOneConfigOptionEntry(e){if(!e||typeof e!="object")return;let t=e;if(t.id==="model"){let h=Xl(t.options);h.length>0&&this.setAgentAdvertisedModels(h);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(w)}`),this.applyModelChange(w))}return}if(t.id==="mode"){let h=Mp(t.options);h.length>0&&this.setAgentAdvertisedModes(h);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(w)}`),this.applyModeChange(w))}return}if(typeof t.id!="string"||!t.id.trim())return;let r=t.id.trim(),s=Bw(t.options);if(s.length===0)return;let o=t.name,i=typeof o=="string"&&o.trim()?o.trim():r,a=t.category,d=typeof a=="string"&&a.trim()?a.trim():"other",c=t.description,l=typeof c=="string"&&c.trim()?c.trim():void 0,u=t.currentValue,f=typeof u=="string"&&u.trim()?u.trim():s[0].value,p={id:r,name:i,category:d,type:"select",currentValue:f,options:s,...l?{description:l}:{}},m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===r);m>=0?this.agentAdvertisedConfigOptions[m]=p:this.agentAdvertisedConfigOptions.push(p)}maybeApplyAgentMode(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="current_mode_update")return!1;let s=typeof r.currentModeId=="string"?r.currentModeId:typeof r.currentMode=="string"?r.currentMode:typeof r.mode=="string"?r.mode:void 0;if(s===void 0)return!0;let o=s.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="usage_update")return!1;let s={...this._currentUsage??{}},o=!1;if(typeof r.used=="number"&&s.used!==r.used&&(s.used=r.used,o=!0),typeof r.size=="number"&&s.size!==r.size&&(s.size=r.size,o=!0),r.cost&&typeof r.cost=="object"){let a=r.cost;typeof a.amount=="number"&&(this.reconcileCostLedger(a.amount)&&(o=!0),s.costAmount!==a.amount&&(s.costAmount=a.amount,o=!0)),typeof a.currency=="string"&&s.costCurrency!==a.currency&&(s.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=s;let i=this.persistableUsage??s;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}armCostLedgerProbe(){let e=this._currentUsage?.costAmount;typeof e=="number"&&e>0&&(this.costLedgerProbe=e)}reconcileCostLedger(e){let t=this.costLedgerProbe;return t===void 0||(this.costLedgerProbe=void 0,e>=t-1e-6)?!1:(this.cumulativeCost+=t,!0)}notifyAgentChange(e,t,r,s){let o=this.retiringGenerationCost;this.retiringGenerationCost=void 0;let i=this.retiringGenerationUsed;this.retiringGenerationUsed=void 0;let a=this.rotationLifetimeCost;this.rotationLifetimeCost=void 0;for(let d of this.agentChangeHandlers)try{d({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId,...o!==void 0?{retiredCost:o}:{},...a!==void 0?{lifetimeCost:a}:{},...i!==void 0?{retiredUsed:i}:{},...s!==void 0?{startedUsed:s}:{},...t!==void 0?{reason:t}:{},...r!==void 0?{runId:r}:{}})}catch(c){this.logger?.warn(`${e}: agentChange handler failed: ${c.message}`)}}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e,this.retiringGenerationCost=e);let t=this._currentUsage?.used;typeof t=="number"&&t>0&&(this.retiringGenerationUsed=t),this.rotationLifetimeCost=this.cumulativeCost;let r={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=r;for(let s of this.usageHandlers)try{s(r)}catch{}this.broadcastCurrentUsage()}broadcastCurrentUsage(){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}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:t})}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let r=t.update;if(r.sessionUpdate!=="usage_update"||!r.cost||typeof r.cost!="object")return e;let s=r.cost;return typeof s.amount!="number"?e:{...t,update:{...r,cost:{...s,amount:this.cumulativeCost+s.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(W1(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(j1(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(",")}]`),q1(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)}onConfigOptionsChange(e){this.configOptionsHandlers.push(e)}extraConfigOptionValues(){return Object.fromEntries(this.agentAdvertisedConfigOptions.map(e=>[e.id,e.currentValue]))}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 r of this.priorityHandlers)try{r(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 s of this.modelHandlers)try{s(t)}catch{}}let r={sessionUpdate:"_hydra_current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(r.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r}),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 s of this.modeHandlers)try{s(t)}catch{}}let r={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(r.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let s=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}}));this.currentModel&&!s.some(i=>i.value===this.currentModel)&&s.unshift({value:this.currentModel,name:this.currentModel});let o=this.currentModel||s[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:s})}if(this.agentAdvertisedModes.length>0){let s=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}}));this.currentMode&&!s.some(i=>i.value===this.currentMode)&&s.unshift({value:this.currentMode,name:this.currentMode});let o=this.currentMode||s[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:s})}let r=(this.availableAgentsFn?.()??[]).map(s=>({value:s.id,name:s.name??s.id,...s.description!==void 0?{description:s.description}:{}}));return r.some(s=>s.value===this.agentId)||r.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:r}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}}),this.fireConfigOptionsHandlers()}fireConfigOptionsHandlers(){for(let e of this.configOptionsHandlers)try{e(this.agentAdvertisedConfigOptions)}catch{}}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let r=t.update,s=Array.isArray(r.configOptions)?[...r.configOptions]:[];if(s.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...r,configOptions:[...s,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let r of pc){if(t.get(r.verb)!=="__hydra__")continue;let s=r.argsHint?`${r.verb} ${r.argsHint}`:r.verb;e.push({name:s,description:`Alias for '/hydra ${r.verb}': ${r.description}`})}if(this.extensionCommands)for(let{name:r,command:s}of this.extensionCommands.list()){let o=s.verb?`hydra ${r} ${s.verb}`:`hydra ${r}`,a={name:s.argsHint?`${o} ${s.argsHint}`:o};s.description&&(a.description=s.description),e.push(a);let d=r.startsWith("hydra-acp-")?r.slice(10):r;if(r.startsWith("hydra-acp-")&&d.length>0){let c=s.verb?`hydra ${d} ${s.verb}`:`hydra ${d}`,u={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(u.description=s.description),e.push(u)}if(d.length>0&&t.get(d)===r){let c=s.verb?`${d} ${s.verb}`:d,u={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(u.description=s.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=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name),d=a.startsWith("/")?a.slice(1):a;d&&e.add(d)}let r=new Map;for(let i of pc)e.has(i.verb)||r.set(i.verb,"__hydra__");if(!this.extensionCommands)return r;let s=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||r.has(a))continue;let d=s.get(a);d===void 0?s.set(a,i):d!==i&&s.set(a,"__conflict__")}for(let[i,a]of s)a!=="__conflict__"&&r.set(i,a);return r}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}agentKnowsSlashCommand(e){let t=s=>s.startsWith("/")?s.slice(1):s,r=t(e);if(!r)return!1;for(let s of this.agentAdvertisedCommands)if(t(s.name.split(/\s+/)[0]??"")===r)return!0;return!1}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="session_info_update"||typeof r.title!="string"||this._upstreamRespawned)return;let s=r.title.trim();if(!(!s||s===this.title)){this.title=s,this._firstPromptSeeded=!0,this._titleSeedPending=!1;for(let o of this.titleHandlers)try{o(s)}catch{}}}async handleSlashCommand(e,t){let s=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=s?.[1]??"",i=(s?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(pc.some(u=>u.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return this.runAgentCommandInline(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"workspace":return this.runWorkspaceCommand(i);case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(i,t):this.runForkCommand(i);default:{let u=new Error(`no dispatcher for /hydra verb ${o}`);throw u.code=G.InternalError,u}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let d=`hydra-acp-${o}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,i,t):this.runExtensionCommand(d,i);let c=pc.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: ${o} (known: ${c.join(", ")})`);throw l.code=G.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(`extension:${e}`,()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,r){let s=this.extensionCommands?.get(e);if(!s)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!s.commands.some(m=>m.verb===i)){let m=s.commands.map(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${m||"(none)"})`)}let d={sessionId:this.sessionId,verb:i,args:a};r!==void 0&&(d.messageId=r);let c=()=>{},l=new Promise(m=>{c=m});r!==void 0&&this.inFlightExtensionDispatches.set(r,{extensionName:e,connection:s.connection,cancel:m=>c({stopReason:"cancelled",reason:m})});let u,f=!1;try{let m=s.connection.request("hydra-acp/commands/invoke",d),h=await Promise.race([m,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return f=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=h}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{r!==void 0&&!f&&this.inFlightExtensionDispatches.delete(r)}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 r=this.inFlightExtensionDispatches.get(e);if(!r)return!1;this.inFlightExtensionDispatches.delete(e);try{r.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(s){this.logger?.warn(`notify commands/cancel to ${r.extensionName} failed: ${s.message}`)}return r.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
59
|
+
`),this.workspacePreambleSent=!0}return s}async prompt(e,t,r,s){let o=this.clients.get(e);if(!o)throw Qn(new Error("client not attached"),G.SessionNotFound);if(this.closing)throw Qn(new Error("session is closing; new prompts cannot be accepted"),G.SessionClosing);let i=Us();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Pn((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0,this.cancelOrphanTimer();for(let d of this.interactiveHandlers)try{d(!0)}catch{}}return this.enqueueUserPrompt(o,t,i,r,s)}broadcastPromptReceived(e){this.closeUnsolicitedTurn("superseded",`prompt:${e.messageId}`);let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),e.originator.fromSession&&(t.fromSession=e.originator.fromSession),e.originator.fromSessionTitle&&(t.fromSessionTitle=e.originator.fromSessionTitle),e.originator.fromLabel&&(t.fromLabel=e.originator.fromLabel),e.originator.depth!==void 0&&(t.depth=e.originator.depth),this.promptStartedAt=Date.now(),this.turnRanTool=!1,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let r=ua(e.prompt);r.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:r},_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 s={};typeof e.costAmount=="number"&&(s.amount=e.costAmount),typeof e.costCurrency=="string"&&(s.currency=e.costCurrency),t.cost=s}if(Object.keys(t).length<=1)return;t._meta={"hydra-acp":{upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}};let r={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:r,recordedAt:Date.now()}).catch(()=>{})}originatorNeedsTurnComplete(e){return e.wasAmend===!0||e.wasSteer===!0}broadcastTurnComplete(e,t,r,s){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Us()};o!==void 0&&(i.stopReason=o);let a=Pn(t?._meta).salvaged;a!==void 0&&(i._meta={[ut]:{salvaged:a}}),this.supersededAutonomousTurn=void 0;let d=this.amendInProgress;if(d&&r!==void 0&&d.cancelledMessageId===r&&(i._meta={[ut]:{...a!==void 0?{salvaged:a}:{},amended:{cancelledMessageId:d.cancelledMessageId,newMessageId:d.newMessageId}}}),this.promptStartedAt=void 0,this.sawTurnComplete=!0,this.scheduleWorkspaceSnapshotHook?.(),r!==void 0&&o!==void 0){this.recordTerminal(r,o);let c=this.pendingTurnNotifiers.get(r);c&&(this.pendingTurnNotifiers.delete(r),vw(c,{sessionId:this.sessionId,messageId:c.originalMessageId,stopReason:o,deliveredAt:Date.now(),...r!==c.originalMessageId?{amendedTo:r}:{}}))}o==="cancelled"||o==="error"||o==="refusal"?this.closeOpenToolCalls(o):this.armOpenToolCalls(),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},s?void 0:e),d&&r!==void 0&&d.cancelledMessageId===r&&this.broadcastPromptAmended(d)}noteAgentActivity(e){if(!(this.closing||this.closed)){if(A1(e)||this.steerCausedTurnTerminal(e)){if(this.unsolicitedTurn!==void 0){this.closeUnsolicitedTurn("completed");return}this.salvageSupersededTerminal();return}this.pendingSteerDetach!==void 0&&this.currentEntry?.messageId===this.pendingSteerDetach.messageId&&OC(e)&&(this.pendingSteerDetach=void 0),!Lw("session/update",e)&&(this.noteBackgroundTaskArming(e),this.unsolicitedTurn===void 0&&(this.promptInFlight||!this.sawTurnComplete||T1(e)||this.openUnsolicitedTurn()))}}steerCausedTurnTerminal(e){return this.unsolicitedTurn?.steerCaused!==!0?!1:OC(e)}noteBackgroundTaskArming(e){let t=e?.update;if(!t||typeof t!="object")return;let r=typeof t.toolCallId=="string"?t.toolCallId:void 0;if(r===void 0)return;let s=t.rawInput,o=U1(t._meta);this.rememberToolLabel(r,t,s,o),this.noteBackgroundTaskStopped(t,s,o);let i=typeof o?.toolResponse?.taskId=="string"?o.toolResponse.taskId:H1(t.rawOutput);if(!(i!==void 0||s!==void 0&&s.run_in_background===!0))return;let d=this.toolLabels.get(r)?.label??"background task";this.lastBackgroundTask={toolCallId:r,label:d};let c=Date.now(),l=this.armedTasks.get(r),u=i??l?.taskId,f=B1(t.title,o,s)||l?.repeating===!0;this.armedTasks.set(r,{label:d,...u!==void 0?{taskId:u}:{},repeating:f,armedAt:l?.armedAt??c}),this.onArmedTasksChanged()}applyBackgroundTaskLevel(e){let t=e?.message;if(!t||t.subtype!=="background_tasks_changed")return;let r=t.tasks;if(!Array.isArray(r))return;let s=Date.now(),o=new Map;for(let a of r){let d=a,c=typeof d?.task_id=="string"?d.task_id:void 0;c!==void 0&&o.set(c,{taskType:typeof d?.task_type=="string"?d.task_type:"unknown",description:typeof d?.description=="string"?d.description:"",firstSeen:this.liveBackgroundTasks.get(c)?.firstSeen??s})}let i=[...this.liveBackgroundTasks.keys()].filter(a=>!o.has(a));this.liveBackgroundTasks=o,this.sawBackgroundTaskLevel=!0,this.logger?.info(`session ${this.sessionId} background level: ${o.size} live`+(i.length>0?` (ended: ${i.join(", ")})`:"")),this.onArmedTasksChanged()}get armedBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.entries()].map(([e,t])=>({taskId:e,label:t.description||t.taskType,taskType:t.taskType,since:t.firstSeen})):[...this.armedTasks.entries()].map(([e,t])=>({toolCallId:e,label:t.label,...t.taskId!==void 0?{taskId:t.taskId}:{},since:t.armedAt}))}pendingOneShotBackgroundTasks(){return this.sawBackgroundTaskLevel?[...this.liveBackgroundTasks.values()].filter(e=>_1.has(e.taskType)).map(e=>e.description||e.taskType):[...this.armedTasks.values()].filter(e=>!e.repeating).map(e=>e.label)}get armedSince(){let e;if(this.sawBackgroundTaskLevel){for(let t of this.liveBackgroundTasks.values())(e===void 0||t.firstSeen<e)&&(e=t.firstSeen);return e}for(let t of this.armedTasks.values())(e===void 0||t.armedAt<e)&&(e=t.armedAt);return e}onArmedTasksChanged(){let e=this.armedBackgroundTasks,t=e.length,r=this.armedSince,s=e.map(o=>o.taskId??o.toolCallId??o.label).sort().join("\0");s===this.lastArmedBroadcast?.key&&r===this.lastArmedBroadcast?.since||this.closed||(this.lastArmedBroadcast={key:s,since:r},this.broadcastQueueNotification("hydra-acp/session/armed_tasks_updated",{sessionId:this.sessionId,count:t,...r!==void 0?{since:r}:{},tasks:e}),this.dispatchIdle())}async retireAgent(e,t){return await e.kill().catch(()=>{}),this.resetBackgroundTaskLevel(),this.discardArmedTasks(t)}resetBackgroundTaskLevel(){this.liveBackgroundTasks.clear(),this.sawBackgroundTaskLevel=!1}discardArmedTasks(e){if(this.armedTasks.size===0)return[];let t=[...this.armedTasks.values()].map(r=>r.label);for(let[r,s]of this.armedTasks)s.openToolCall===!0&&this.openToolCalls.delete(r);return this.armedTasks.clear(),this.logger?.info(`session ${this.sessionId} discarded ${t.length} armed task(s) on ${e}: ${t.join(", ")}`),this.onArmedTasksChanged(),t}noteBackgroundTaskStopped(e,t,r){if(!(r?.toolName==="TaskStop"||e.title==="TaskStop"))return;let o=t?.task_id;if(typeof o!="string"||o.length===0)return;let i=!1;for(let[a,d]of this.armedTasks)d.taskId===o&&(this.armedTasks.delete(a),i=!0);i&&this.onArmedTasksChanged()}rememberToolLabel(e,t,r,s){let o=r!==void 0&&typeof r.description=="string"&&r.description?r.description:void 0;if(o!==void 0)this.toolLabels.set(e,{label:o.slice(0,Fw),fromDescription:!0});else if(this.toolLabels.get(e)?.fromDescription!==!0){let i=typeof t.title=="string"&&t.title?t.title:typeof s?.toolName=="string"&&s.toolName?s.toolName:void 0;i!==void 0&&this.toolLabels.set(e,{label:i.slice(0,Fw),fromDescription:!1})}for(;this.toolLabels.size>M1;){let i=this.toolLabels.keys().next().value;if(i===void 0)break;this.toolLabels.delete(i)}}openUnsolicitedTurn(){let e=Date.now();if(this.lastUnsolicitedCancelAt!==0&&e-this.lastUnsolicitedCancelAt<=n.UNSOLICITED_REOPEN_WINDOW_MS?this.cancelReopenStreak+=1:this.cancelReopenStreak=0,this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak>=n.UNSOLICITED_REOPEN_LIMIT){this.escalateUnresponsiveCancel();return}let t=this.lastBackgroundTask,r=!1;for(let[i,a]of this.armedTasks)a.repeating||a.openToolCall===!0||(this.armedTasks.delete(i),r=!0);r&&this.onArmedTasksChanged();let s={messageId:Us(),startedAt:e,cause:t,steerCaused:this.pendingSteerDetach!==void 0};this.pendingSteerDetach=void 0,this.unsolicitedTurn=s,this.promptStartedAt=e,this.logger?.info(`session ${this.sessionId} agent resumed with no prompt in flight`+(t?` (after ${t.label})`:""));let o={unsolicited:!0};t&&(o.cause=t),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"_hydra_turn_started",messageId:s.messageId,_meta:{"hydra-acp":o}}})}async holdForUnsolicitedTurn(e){if(this.unsolicitedTurn===void 0){this.logger?.info(`session ${this.sessionId} queue hold skipped for ${e.messageId} (no unsolicited turn open)`);return}let t=Date.now(),r=this.unsolicitedTurn.cause;this.logger?.info(`session ${this.sessionId} holding ${e.messageId} behind unsolicited turn ${this.unsolicitedTurn.messageId}`+(r?` cause=${JSON.stringify(r.label)}`:"")),this.broadcastQueueNotification("hydra-acp/prompt_queue/held",{sessionId:this.sessionId,messageId:e.messageId,reason:"agent_resumed",...r?{cause:r}:{}});let s="turn_ended";for(;;){if(this.closing||this.closed){s="closing";break}if(e.cancelled){s="cancelled";break}if(this.unsolicitedTurn===void 0){s="turn_ended";break}await new Promise(i=>{let a=setTimeout(i,$1);typeof a.unref=="function"&&a.unref()})}let o=Date.now()-t;this.logger?.info(`session ${this.sessionId} released ${e.messageId} reason=${s} heldMs=${o}`),this.broadcastQueueNotification("hydra-acp/prompt_queue/released",{sessionId:this.sessionId,messageId:e.messageId,reason:s,heldMs:o})}closeUnsolicitedTurn(e,t){let r=this.unsolicitedTurn;if(r===void 0)return;let s=Date.now()-r.startedAt;this.unsolicitedTurn=void 0,this.promptStartedAt=void 0,e==="cancelled"?this.lastUnsolicitedCancelAt=Date.now():(this.lastUnsolicitedCancelAt=0,this.cancelReopenStreak=0),this.logger?.info(`session ${this.sessionId} unsolicited turn ${r.messageId} closed reason=${e} durationMs=${s}`+(t?` by=${t}`:"")+(r.cause?` cause=${JSON.stringify(r.cause.label)}`:"")),e==="superseded"&&(this.supersededAutonomousTurn={turnMessageId:r.messageId,cause:r.cause,supersededAt:Date.now()}),this.recordCurrentUsageSnapshot(),!this.closed&&(e==="cancelled"?this.closeOpenToolCalls("cancelled"):e==="completed"&&this.armOpenToolCalls(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"_hydra_turn_ended",messageId:Us(),startedMessageId:r.messageId,durationMs:s,_meta:{"hydra-acp":{unsolicited:!0,reason:e}}}}))}salvageSupersededTerminal(){let e=this.supersededAutonomousTurn;if(e===void 0)return;this.supersededAutonomousTurn=void 0;let t=this.autonomousSalvage;t!==void 0&&(this.autonomousSalvage=void 0,this.logger?.warn(`session ${this.sessionId} salvaged session/prompt from autonomous terminal (superseded turn ${e.turnMessageId}, ${Date.now()-e.supersededAt}ms earlier)`+(e.cause?` cause=${JSON.stringify(e.cause.label)}`:"")),t({stopReason:"end_turn",_meta:{[ut]:{salvaged:{reason:"autonomous_terminal",supersededMessageId:e.turnMessageId}}}}))}async awaitPromptResponse(e){if(this.supersededAutonomousTurn===void 0)return e;try{return await new Promise((t,r)=>{this.autonomousSalvage=t,e.then(t,r)})}finally{this.autonomousSalvage=void 0}}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>C1;){let r=this.recentlyTerminal.keys().next().value;if(r===void 0)break;this.recentlyTerminal.delete(r)}}registerTurnNotify(e,t,r){let s=this.recentlyTerminal.get(e);if(s)return{alreadyTerminal:!0,stopReason:s.stopReason};for(this.pendingTurnNotifiers.set(e,{callbackUrl:t,secret:r,registeredAt:Date.now(),originalMessageId:e});this.pendingTurnNotifiers.size>x1;){let o=this.pendingTurnNotifiers.keys().next().value;if(o===void 0)break;this.pendingTurnNotifiers.delete(o)}return{alreadyTerminal:!1}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let r={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",r)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(r=>r.messageId===e&&r.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 r=this.visibleQueueDepth(),s=t?.position??Math.max(0,r-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:s,queueDepth:r,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}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 r of this.clients.values())r.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 r of this.promptQueue)r.kind!=="user"||r.cancelled||e.push({messageId:r.messageId,originator:r.originator,prompt:r.prompt,position:t++,enqueuedAt:r.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let r={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(r.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(r.version=t.originator.clientInfo.version);let s={kind:"user",messageId:t.messageId,originator:r,clientId:r.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(s),this.broadcastQueueAdded(s)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(s=>s.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let r=this.promptQueue[t];return r.cancelled=!0,this.promptQueue.splice(t,1),r.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),r.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let r=this.promptQueue.find(s=>s.messageId===e);return!r||r.kind!=="user"?{updated:!1,reason:"not_found"}:(r.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let r=this.clients.get(e);if(!r)throw Qn(new Error("client not attached"),G.SessionNotFound);let{targetMessageId:s,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===s&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(r,o,s,i);let d=this.promptQueue.find(l=>l.messageId===s&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=o,this.broadcastQueueUpdated(s,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:s};let c=this.recentlyTerminal.get(s);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(r,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,r,s){let o=Us(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),s){let c=[];for(let l of this.promptQueue){if(l.kind==="user"&&!l.cancelled){l.cancelled=!0,this.broadcastQueueRemoved(l.messageId,"cancelled"),l.resolve({stopReason:"cancelled"});continue}c.push(l)}this.promptQueue=c}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:r,position:1}),this.amendInProgress={cancelledMessageId:r,newMessageId:o};let d=this.pendingTurnNotifiers.get(r);return d&&(this.pendingTurnNotifiers.delete(r),this.pendingTurnNotifiers.set(o,d)),this.cancelExtensionDispatch(r,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}async steer(e,t){let r=this.clients.get(e);if(!r)throw Qn(new Error("client not attached"),G.SessionNotFound);let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled;if(s&&this.agent.steeringSupported){this.pendingSteerDetach={messageId:this.currentEntry.messageId};let o;try{o=await this.forwardRequest("_session/steering",t)}catch(d){throw this.pendingSteerDetach=void 0,d}let i=o?.outcome,a=i==="injected"||i==="startedNewTurn"||i==="promptRequired"||i==="failed"?o:{outcome:"failed"};return a.outcome!=="startedNewTurn"&&(this.pendingSteerDetach=void 0),a.outcome==="injected"&&this.recordSteerAsUserMessageChunk(t.prompt,e),a.outcome==="startedNewTurn"?{...a,detached:!0}:a}return s?(this.amendOnHead(r,t.prompt,this.currentEntry.messageId,!1),{outcome:"startedNewTurn"}):t._meta?.steering?.idleBehavior==="promptRequired"?{outcome:"promptRequired",reason:"noRunningTurn"}:(this.prompt(e,{sessionId:t.sessionId,prompt:t.prompt},void 0,{steerOriginated:!0}).catch(o=>{this.logger?.warn(`steer-originated prompt failed to enqueue: ${o.message}`)}),{outcome:"startedNewTurn"})}recordSteerAsUserMessageChunk(e,t){let r=ua(e);r.length!==0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:r},_meta:{"hydra-acp":{steered:!0}}}},t)}enqueueAmendmentAsFollowUp(e,t){let r=Us(),s={clientId:e.clientId};e.clientInfo?.name&&(s.name=e.clientInfo.name),e.clientInfo?.version&&(s.version=e.clientInfo.version);let o={kind:"user",messageId:r,originator:s,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),r}async cancel(e){if(!this.clients.get(e))throw Qn(new Error("client not attached"),G.SessionNotFound);this.logger?.info(`session ${this.sessionId} session/cancel from ${e} promptInFlight=${this.promptInFlight} agentTurnInFlight=${this.agentTurnInFlight} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length}`),this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),this.closeUnsolicitedTurn("cancelled"),this.agentTurnInFlight||this.closeOpenToolCalls("cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(r=>r.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,r=new Set,s=0,o="request"){let i=this.rewriteForAgent(t);for(let a=s;a<this.transformChain.length;a++){let d=this.transformChain[a];if(r.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let l=`t_${Ow()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return o==="notification"?void 0:u?.payload??Dw(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(i=u.payload),r.add(d.name);continue}if(f==="processing"){let p=a,m=i,h=new Set(r);return new Promise(g=>{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,m,new Set([...h,d.name]),p+1,o).then(g).catch(()=>g(o==="notification"?void 0:Dw(e))))},Pp);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:g,timer:w,transformerName:d.name,method:e,envelope:m,chainIdx:p,originatedBy:h,side:"request",tailKind:o})})}r.add(d.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async forwardModelChange(e,t){let r=await si({request:(s,o)=>this.forwardRequest(s,o),sessionId:this.sessionId,modelId:e,verb:this.modelVerb,extraParams:t,logger:this.logger});return this.modelVerb=r.verb,this.modelVerbConfirmed=!0,r.result}noteModelVerbHint(e,t){e===void 0||this.modelVerbConfirmed||e===this.modelVerb||(this.logger?.info(`model verb for agent ${this.agentId} inferred as ${e} from ${t} (was ${this.modelVerb})`),this.modelVerb=e)}resetModelVerb(e){this.modelVerb=e??Ns,this.modelVerbConfirmed=!1}async runAgentRequestChain(e,t,r=new Set,s=0){let o=t,i=`request:${e}`;for(let a=s;a<this.transformChain.length;a++){let d=this.transformChain[a];if(r.has(d.name)||!d.intercepts.has(i))continue;let c=`t_${Ow()}`,l;try{l=await d.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(f){this.logger?.warn(`transformer ${d.name} error on ${i}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??tN(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(o=l.payload),r.add(d.name);continue}if(u==="processing"){let f=a,p=o,m=new Set(r),h=e;return new Promise(g=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:d.name}),this.runAgentRequestChain(h,p,new Set([...m,d.name]),f+1).then(g).catch(()=>g({shortCircuit:!1,envelope:p})))},Pp);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:b=>g({shortCircuit:!0,payload:b}),timer:w,transformerName:d.name,method:h,envelope:p,chainIdx:f,originatedBy:m,side:"agent-request"})})}r.add(d.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let r=this.pendingClaims.get(e);return r?(clearTimeout(r.timer),this.pendingClaims.delete(e),r.resolve(t),!0):!1}keepAliveClaim(e,t){let r=this.pendingClaims.get(e);if(!r)return!1;clearTimeout(r.timer);let s=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Pp,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:r.transformerName}),r.side==="response")this.runResponseChain(r.envelope,new Set([...r.originatedBy,r.transformerName]),r.chainIdx+1).then(()=>r.resolve(void 0)).catch(()=>r.resolve(void 0));else if(r.side==="agent-request")this.runAgentRequestChain(r.method,r.envelope,new Set([...r.originatedBy,r.transformerName]),r.chainIdx+1).then(r.resolve).catch(()=>r.resolve({shortCircuit:!1,envelope:r.envelope}));else{let i=r.tailKind??"request";this.forwardRequest(r.method,r.envelope,new Set([...r.originatedBy,r.transformerName]),r.chainIdx+1,i).then(r.resolve).catch(()=>r.resolve(i==="notification"?void 0:Dw(r.method)))}},s);return typeof o.unref=="function"&&o.unref(),r.timer=o,!0}async emitToChain(e,t,r){let s=this.transformChain.findIndex(a=>a.name===e),o=s>=0?s+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(r,i,o);return}return this.forwardRequest(t,r,i,o)}async emitToQueue(e,t){let r=this.transformChain.findIndex(c=>c.name===e),s=r>=0?r+1:0,o=(t??{}).prompt??[],i=Us(),a=`transformer:${e}`,d={clientId:a,name:e};return new Promise((c,l)=>{let u={kind:"user",messageId:i,originator:d,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:s,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){let t=this.turnStartedAt!==void 0;this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1} by=${e.by??"unknown"} midTurn=${t} unsolicitedTurn=${this.unsolicitedTurn!==void 0} queued=${this.promptQueue.length} awaitingPermission=${this.hasPermissionFlag}`),t&&this.logger?.warn(`session ${this.sessionId} closed mid-turn by=${e.by??"unknown"}; the in-flight turn will not settle and the agent is being killed`),this.cancelIdleTimer(),this.cancelOrphanTimer();for(let r of this.pendingClaims.values())clearTimeout(r.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._titleSeedPending=!1,this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let r of this.titleHandlers)try{r(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(!this._titleSeedPending||Pn((e??{})._meta).ancillary===!0||this.promptCarriesSentBy(e))return;let s=ua((e??{}).prompt),o=Hw(s,200);!o||o.startsWith("/")||(this._titleSeedPending=!1,this.setTitle(o))}maybeApplyAgentModel(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="_hydra_current_model_update")return!1;let s=Xl(r.availableModels);s.length>0&&this.setAgentAdvertisedModels(s);let o=typeof r.currentModel=="string"?r.currentModel:typeof r.model=="string"?r.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="config_option_update")return!1;let s=r.configOptions;if(!Array.isArray(s))return!0;for(let i of s)this.applyOneConfigOptionEntry(i);let o=new Set(s.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i&&i!=="model"&&i!=="mode"&&i!=="agent"));return this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id)),this.fireConfigOptionsHandlers(),!0}applyAgentConfigOptionResponse(e,t){let r=e?.configOptions;if(!Array.isArray(r))return!1;let s=JSON.stringify(this.agentAdvertisedConfigOptions);for(let o of r){let i=o?.id;i==="model"||i==="mode"||i==="agent"||this.applyOneConfigOptionEntry(o)}if(E1(r,t)){let o=new Set(r.filter(i=>!!i&&typeof i=="object").map(i=>typeof i.id=="string"?i.id.trim():void 0).filter(i=>!!i));this.agentAdvertisedConfigOptions=this.agentAdvertisedConfigOptions.filter(i=>o.has(i.id))}return JSON.stringify(this.agentAdvertisedConfigOptions)!==s}applyOneConfigOptionEntry(e){if(!e||typeof e!="object")return;let t=e;if(t.id==="model"){let h=Xl(t.options);h.length>0&&this.setAgentAdvertisedModels(h);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(w)}`),this.applyModelChange(w))}return}if(t.id==="mode"){let h=Mp(t.options);h.length>0&&this.setAgentAdvertisedModes(h);let g=t.currentValue;if(typeof g=="string"){let w=g.trim();w&&w!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(w)}`),this.applyModeChange(w))}return}if(typeof t.id!="string"||!t.id.trim())return;let r=t.id.trim(),s=Bw(t.options);if(s.length===0)return;let o=t.name,i=typeof o=="string"&&o.trim()?o.trim():r,a=t.category,d=typeof a=="string"&&a.trim()?a.trim():"other",c=t.description,l=typeof c=="string"&&c.trim()?c.trim():void 0,u=t.currentValue,f=typeof u=="string"&&u.trim()?u.trim():s[0].value,p={id:r,name:i,category:d,type:"select",currentValue:f,options:s,...l?{description:l}:{}},m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===r);m>=0?this.agentAdvertisedConfigOptions[m]=p:this.agentAdvertisedConfigOptions.push(p)}maybeApplyAgentMode(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="current_mode_update")return!1;let s=typeof r.currentModeId=="string"?r.currentModeId:typeof r.currentMode=="string"?r.currentMode:typeof r.mode=="string"?r.mode:void 0;if(s===void 0)return!0;let o=s.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="usage_update")return!1;let s={...this._currentUsage??{}},o=!1;if(typeof r.used=="number"&&s.used!==r.used&&(s.used=r.used,o=!0),typeof r.size=="number"&&s.size!==r.size&&(s.size=r.size,o=!0),r.cost&&typeof r.cost=="object"){let a=r.cost;typeof a.amount=="number"&&(this.reconcileCostLedger(a.amount)&&(o=!0),s.costAmount!==a.amount&&(s.costAmount=a.amount,o=!0)),typeof a.currency=="string"&&s.costCurrency!==a.currency&&(s.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=s;let i=this.persistableUsage??s;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}armCostLedgerProbe(){let e=this._currentUsage?.costAmount;typeof e=="number"&&e>0&&(this.costLedgerProbe=e)}reconcileCostLedger(e){let t=this.costLedgerProbe;return t===void 0||(this.costLedgerProbe=void 0,e>=t-1e-6)?!1:(this.cumulativeCost+=t,!0)}notifyAgentChange(e,t,r,s){let o=this.retiringGenerationCost;this.retiringGenerationCost=void 0;let i=this.retiringGenerationUsed;this.retiringGenerationUsed=void 0;let a=this.rotationLifetimeCost;this.rotationLifetimeCost=void 0;for(let d of this.agentChangeHandlers)try{d({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId,...o!==void 0?{retiredCost:o}:{},...a!==void 0?{lifetimeCost:a}:{},...i!==void 0?{retiredUsed:i}:{},...s!==void 0?{startedUsed:s}:{},...t!==void 0?{reason:t}:{},...r!==void 0?{runId:r}:{}})}catch(c){this.logger?.warn(`${e}: agentChange handler failed: ${c.message}`)}}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e,this.retiringGenerationCost=e);let t=this._currentUsage?.used;typeof t=="number"&&t>0&&(this.retiringGenerationUsed=t),this.rotationLifetimeCost=this.cumulativeCost;let r={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=r;for(let s of this.usageHandlers)try{s(r)}catch{}this.broadcastCurrentUsage()}broadcastCurrentUsage(){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}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:t})}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let r=t.update;if(r.sessionUpdate!=="usage_update"||!r.cost||typeof r.cost!="object")return e;let s=r.cost;return typeof s.amount!="number"?e:{...t,update:{...r,cost:{...s,amount:this.cumulativeCost+s.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(W1(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(j1(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(",")}]`),q1(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)}onConfigOptionsChange(e){this.configOptionsHandlers.push(e)}extraConfigOptionValues(){return Object.fromEntries(this.agentAdvertisedConfigOptions.map(e=>[e.id,e.currentValue]))}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 r of this.priorityHandlers)try{r(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 s of this.modelHandlers)try{s(t)}catch{}}let r={sessionUpdate:"_hydra_current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(r.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r}),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 s of this.modeHandlers)try{s(t)}catch{}}let r={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(r.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let s=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}}));this.currentModel&&!s.some(i=>i.value===this.currentModel)&&s.unshift({value:this.currentModel,name:this.currentModel});let o=this.currentModel||s[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:s})}if(this.agentAdvertisedModes.length>0){let s=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}}));this.currentMode&&!s.some(i=>i.value===this.currentMode)&&s.unshift({value:this.currentMode,name:this.currentMode});let o=this.currentMode||s[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:s})}let r=(this.availableAgentsFn?.()??[]).map(s=>({value:s.id,name:s.name??s.id,...s.description!==void 0?{description:s.description}:{}}));return r.some(s=>s.value===this.agentId)||r.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:r}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}}),this.fireConfigOptionsHandlers()}fireConfigOptionsHandlers(){for(let e of this.configOptionsHandlers)try{e(this.agentAdvertisedConfigOptions)}catch{}}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let r=t.update,s=Array.isArray(r.configOptions)?[...r.configOptions]:[];if(s.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...r,configOptions:[...s,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let r of pc){if(t.get(r.verb)!=="__hydra__")continue;let s=r.argsHint?`${r.verb} ${r.argsHint}`:r.verb;e.push({name:s,description:`Alias for '/hydra ${r.verb}': ${r.description}`})}if(this.extensionCommands)for(let{name:r,command:s}of this.extensionCommands.list()){let o=s.verb?`hydra ${r} ${s.verb}`:`hydra ${r}`,a={name:s.argsHint?`${o} ${s.argsHint}`:o};s.description&&(a.description=s.description),e.push(a);let d=r.startsWith("hydra-acp-")?r.slice(10):r;if(r.startsWith("hydra-acp-")&&d.length>0){let c=s.verb?`hydra ${d} ${s.verb}`:`hydra ${d}`,u={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(u.description=s.description),e.push(u)}if(d.length>0&&t.get(d)===r){let c=s.verb?`${d} ${s.verb}`:d,u={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(u.description=s.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=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name),d=a.startsWith("/")?a.slice(1):a;d&&e.add(d)}let r=new Map;for(let i of pc)e.has(i.verb)||r.set(i.verb,"__hydra__");if(!this.extensionCommands)return r;let s=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||r.has(a))continue;let d=s.get(a);d===void 0?s.set(a,i):d!==i&&s.set(a,"__conflict__")}for(let[i,a]of s)a!=="__conflict__"&&r.set(i,a);return r}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}agentKnowsSlashCommand(e){let t=s=>s.startsWith("/")?s.slice(1):s,r=t(e);if(!r)return!1;for(let s of this.agentAdvertisedCommands)if(t(s.name.split(/\s+/)[0]??"")===r)return!0;return!1}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let r=(e??{}).update??{};if(r.sessionUpdate!=="session_info_update"||typeof r.title!="string"||this._upstreamRespawned)return;let s=r.title.trim();if(!(!s||s===this.title)){this.title=s,this._firstPromptSeeded=!0,this._titleSeedPending=!1;for(let o of this.titleHandlers)try{o(s)}catch{}}}async handleSlashCommand(e,t){let s=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=s?.[1]??"",i=(s?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(pc.some(u=>u.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return this.runAgentCommandInline(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"workspace":return this.runWorkspaceCommand(i);case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();case"fork":return a?this.runForkCommandInline(i,t):this.runForkCommand(i);default:{let u=new Error(`no dispatcher for /hydra verb ${o}`);throw u.code=G.InternalError,u}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let d=`hydra-acp-${o}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,i,t):this.runExtensionCommand(d,i);let c=pc.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: ${o} (known: ${c.join(", ")})`);throw l.code=G.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(`extension:${e}`,()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,r){let s=this.extensionCommands?.get(e);if(!s)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!s.commands.some(m=>m.verb===i)){let m=s.commands.map(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${m||"(none)"})`)}let d={sessionId:this.sessionId,verb:i,args:a};r!==void 0&&(d.messageId=r);let c=()=>{},l=new Promise(m=>{c=m});r!==void 0&&this.inFlightExtensionDispatches.set(r,{extensionName:e,connection:s.connection,cancel:m=>c({stopReason:"cancelled",reason:m})});let u,f=!1;try{let m=s.connection.request("hydra-acp/commands/invoke",d),h=await Promise.race([m,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return f=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=h}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{r!==void 0&&!f&&this.inFlightExtensionDispatches.delete(r)}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 r=this.inFlightExtensionDispatches.get(e);if(!r)return!1;this.inFlightExtensionDispatches.delete(e);try{r.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(s){this.logger?.warn(`notify commands/cancel to ${r.extensionName} failed: ${s.message}`)}return r.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
60
60
|
${e}
|
|
61
61
|
`},_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 r=t.map(s=>{let o=s.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=s.currentModel?` \xB7 ${s.currentModel}`:"",a=s.sessionId===this.sessionId?" \u25C0":"",d=s.title?` ${s.title}`:"";return`\`${o}\` ${s.cwd}${i}${a}${d}`});e=`Sessions (${t.length}):
|
|
62
62
|
${r.join(`
|
|
@@ -97,7 +97,7 @@ ${h}:
|
|
|
97
97
|
`)}
|
|
98
98
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(r==="model"){if(c!==this.currentModel){let u=await this.forwardModelChange(c);this.applyAgentConfigOptionResponse(u,"model")}return this.applyModelChange(c),{stopReason:"end_turn"}}if(r==="mode")return c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"};if(r==="agent")return c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"};let l=await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:r,value:c});return this.applyAgentConfigOptionResponse(l,r)&&this.broadcastConfigOptions(),{stopReason:"end_turn"}}runTitleCommand(e){return this.enqueuePrompt("title",()=>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.runAgentCommandInline(e)}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw Qn(new Error("/hydra agent requires an agent id"),G.InvalidParams);let s=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(s===this.agentId)throw Qn(new Error(`already on agent ${s}`),G.InvalidParams);if(!this.scheduleCompactionHook)return this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"};this.scheduleCompactionHook({targetAgentId:s});let o=this.promptInFlight||this.unsolicitedTurn!==void 0;return this.emitExtensionReply(o?`Agent switch to ${s} scheduled. A turn is still in flight \u2014 the rotation lands on the next idle edge; cancel the turn to make that happen now.`:`Agent switch to ${s} scheduled. The session will rotate to ${s} once synthesis completes.`),{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,by:"/hydra kill"}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt("restart",()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw Qn(new Error("agent restart not configured for this session"),G.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt("compact",()=>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,r=await this.getUpstreamGenerationsHook?.()??[],s=IC(r,t),o=CC(s);if(e==null&&t==null&&o.length===0)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};let i=[];return e==null?i.push(`No compaction in progress. Last summarized through entry: ${t??0}`):(i.push(`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`),e.lastError!==void 0&&i.push(`Last error: ${e.lastError}`)),i.push(`Current upstream: ${this.upstreamSessionId}`),o.length>0&&i.push("",...o),this.emitExtensionReply(i.join(`
|
|
99
99
|
`)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt("uncompact",()=>this.runUncompactCommandInline())}async runWorkspaceCommand(e){if(!this.workspaceHook)return this.emitExtensionReply("Workspaces are not available on this session (no workspace hook configured)."),{stopReason:"end_turn"};let[t="status",...r]=e.split(/\s+/).filter(d=>d.length>0);if(!$C.includes(t))return this.emitExtensionReply(`Unknown workspace verb "${t}". Use one of: ${$C.join(", ")}.`),{stopReason:"end_turn"};let s=r.filter(d=>d.startsWith("--")),o=s.filter(d=>d!=="--clean"&&d!=="--deep");if(o.length>0)return this.emitExtensionReply(`Unknown workspace flag(s) ${o.join(", ")}. Supported: --clean (start), --deep (clean).`),{stopReason:"end_turn"};let i={clean:s.includes("--clean"),deep:s.includes("--deep")};if(i.clean&&t!=="start")return this.emitExtensionReply(`--clean applies to \`start\`, not to \`${t}\`.`),{stopReason:"end_turn"};if(i.deep&&t!=="clean")return this.emitExtensionReply(`--deep applies to \`clean\`, not to \`${t}\`.`),{stopReason:"end_turn"};let a=r.filter(d=>!d.startsWith("--")).join(" ").trim();try{let d=await this.workspaceHook(t,a.length>0?a:void 0,i);this.emitExtensionReply(d)}catch(d){this.emitExtensionReply(`Workspace ${t} failed: ${d instanceof Error?d.message:String(d)}`)}return{stopReason:"end_turn"}}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("fork",()=>this.runForkCommandInline(e,void 0))}async findMessageIdBefore(e){if(!this.historyStore)return;let t=await this.historyStore.load(this.sessionId),r;for(let s of t){if(s.method!=="session/update")continue;let i=s.params?.update?.messageId;if(typeof i=="string"){if(i===e)return r;r=i}}}async runForkCommandInline(e,t){if(!this.forkHook)return this.emitExtensionReply("Fork not configured for this session."),{stopReason:"end_turn"};let r=(e??"").trim(),s=r.match(/^--verbatim(?:\s+([\s\S]*))?$/),o=s?"verbatim":void 0,i=(s?s[1]??"":r).trim();try{let a={};if(o&&(a.mode=o),i!==""&&(a.prompt=i),t&&this.historyStore){let l=await this.findMessageIdBefore(t).catch(()=>{});l&&(a.forkAt=l)}let c=(await this.forkHook(Object.keys(a).length>0?a:void 0)).sessionId.replace(/^hydra_session_/,"");this.emitExtensionReply(i!==""?`Forked to [\`${c}\`](hydra://sessions/${c}) and sent the prompt.`:`Forked to [\`${c}\`](hydra://sessions/${c}).`)}catch(a){this.emitExtensionReply(`Fork failed: ${a instanceof Error?a.message:String(a)}`)}return{stopReason:"end_turn"}}escalateUnresponsiveCancel(){this.cancelReopenStreak=0,this.logger?.warn(`session ${this.sessionId} agent ${this.agentId} reopened an unsolicited turn right after cancel ${n.UNSOLICITED_REOPEN_LIMIT} times in a row; forcing a restart`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,reason:"unresponsive",message:`${this.agentId} kept resuming after repeated cancels; restarting the agent`}),this.forceCancel().catch(e=>{this.logger?.warn(`session ${this.sessionId} forceCancel after unresponsive-cancel escalation failed: ${e instanceof Error?e.message:String(e)}`)})}async forceCancel(){if(this.closed||this.closing)throw Qn(new Error("session is closing"),G.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1,by:"force-cancel"}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,r=await this.buildSwitchTranscript(t),s=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(s.agent,{respawn:!0});let o=this.agent;this.agent=s.agent,this.upstreamSessionId=s.upstreamSessionId,this.agentMeta=s.agentMeta,this.agentCapabilities=s.agentCapabilities,this.resetModelVerb(s.modelVerb),this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=s.initialModel,this.currentMode=s.initialMode,this.setAgentAdvertisedModels(s.initialModels??[]),this.setAgentAdvertisedModes(s.initialModes??[]),this.agentAdvertisedConfigOptions=s.initialConfigOptions??[],await this.retireAgent(o,"agent restart"),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(t,t),this.notifyAgentChange("respawnAgent","restart")}async buildSwitchTranscript(e,t){let r=[],s=await this.getHistorySnapshot();for(let c of s){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 m=ua(u.prompt);m&&r.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let h=u.content?.text;h&&r.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let m=u.status,h=u.title;(m==="completed"||m==="failed")&&r.push({speaker:"tool",text:`${h??"?"} ${m}`})}}if(r.length===0)return"";let o=[],i;for(let c of r)i&&i.speaker===c.speaker?i.text+=c.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:c.speaker,text:c.text});i&&o.push(`<${i.speaker}>: ${i.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 ---",...o,"--- end transcript ---"].join(`
|
|
100
|
-
`)}async seedFromImport(){await this.enqueuePrompt("seed:import",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("seed:fork",async()=>{let t=this.title??"(untitled)",r=[];if(this.historyStore)try{r=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let s=Pw({synopsis:e,title:t,tail:r,tailK:v1,tailFloor:S1,watermark:this._summarizedThroughEntry,recallArmed:(this._summarizedThroughEntry??0)>0});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:s}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${s.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.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 r=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,s={};e.capacityBytes!==void 0&&(s.capacityBytes=e.capacityBytes),r!==void 0&&(s.filePath=r),e.fileCapBytes!==void 0&&(s.fileCapBytes=e.fileCapBytes),s.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_stream_truncated",...r!==void 0?{filePath:r}:{},fileCapBytes:e.fileCapBytes}})};let o=new Cp(s);this.streamBuffer=o,this.streamFilePath=r;let i={capacityBytes:o.capacity};return r!==void 0&&(i.filePath=r),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let r=this.requireStreamBuffer();if(e.length>0){let s=Buffer.from(e,"base64");r.append(s)}return t===!0&&r.close(),{writeCursor:r.writeCursorPos}}async streamRead(e,t,r){let s=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??fc,fc)),i=s.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&r!==void 0&&r>0){let d=await s.waitForData(i.nextCursor,r);(d==="data"||d==="eof")&&(i=s.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let r=this.requireStreamBuffer().tail(e);return{bytes:r.bytes.toString("base64"),startCursor:r.startCursor,endCursor:r.endCursor,truncated:r.truncated}}streamHead(e){let r=this.requireStreamBuffer().head(e);return{bytes:r.bytes.toString("base64"),startCursor:r.startCursor,endCursor:r.endCursor,truncated:r.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=G.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closeUnsolicitedTurn("closed"),e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.cancelOrphanTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.originatorNeedsTurnComplete(this.currentEntry)),this.currentEntry=void 0;let r=this.promptQueue;this.promptQueue=[];for(let o of r){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");let i=this.pendingTurnNotifiers.get(o.messageId);i&&(this.pendingTurnNotifiers.delete(o.messageId),vw(i,{sessionId:this.sessionId,messageId:i.originalMessageId,stopReason:"cancelled",deliveredAt:Date.now(),...o.messageId!==i.originalMessageId?{amendedTo:o.messageId}:{}}));try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear(),this.openToolCalls.clear();let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>_C(s).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>WC.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,r){this._setAttentionFlag(e,t,r,!0)}_setAttentionFlag(e,t,r,s){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(r))return;this.attentionFlags.set(o,{...i,payload:r,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:r});s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,r){let s=`${e}::${t}`;this.attentionFlags.delete(s)&&r&&(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.hasWorkInFlight){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},r=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${r}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()}scheduleOrphanCheck(){this.closed||this.orphanTimeoutMs<=0||this.clients.size>0||this._interactive===!0||this.armOrphanTimer(this.orphanTimeoutMs)}armOrphanTimer(e){this.orphanTimer&&clearTimeout(this.orphanTimer),this.orphanTimer=setTimeout(()=>{this.orphanTimer=void 0,this.checkOrphan()},e),typeof this.orphanTimer.unref=="function"&&this.orphanTimer.unref()}checkOrphan(){if(!this.closed&&!(this.clients.size>0||this._interactive===!0)){if(this.hasWorkInFlight){this.armOrphanTimer(this.orphanTimeoutMs);return}this.logger?.info(`session ${this.sessionId} orphan timeout fired after ${Math.round(this.orphanTimeoutMs/1e3)}s with no attached client and no prompt ever received \u2014 closing`),this.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}cancelOrphanTimer(){this.orphanTimer&&(clearTimeout(this.orphanTimer),this.orphanTimer=void 0)}get currentPromptDepth(){if(this.currentEntry?.kind==="user")return this.currentEntry.originator.depth??0}get hasWorkInFlight(){return this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0||this.armedBackgroundTasks.length>0}onIdle(e,t){let r={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(r),()=>{let s=this.idleHandlers.indexOf(r);s>=0&&this.idleHandlers.splice(s,1),r.timer&&(clearTimeout(r.timer),r.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let r of this.idleHandlers)r.timer&&(clearTimeout(r.timer),r.timer=void 0);return}let t=[...this.idleHandlers];for(let r of t){if(r.debounceMs===0){if(r.once){let s=this.idleHandlers.indexOf(r);s>=0&&this.idleHandlers.splice(s,1)}try{r.fn(this)}catch{}continue}r.timer&&(clearTimeout(r.timer),r.timer=void 0),r.timer=setTimeout(()=>{if(r.timer=void 0,!this.closed&&this.isQuiescedSync()){if(r.once){let s=this.idleHandlers.indexOf(r);s>=0&&this.idleHandlers.splice(s,1)}try{r.fn(this)}catch{}}},r.debounceMs),typeof r.timer.unref=="function"&&r.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}noteRecordedToolCall(e,t){if(e!=="session/update")return;let r=t?.update;if(r===void 0)return;let s=typeof r.toolCallId=="string"?r.toolCallId:"";if(s.length===0)return;let o=typeof r.title=="string"&&r.title!==""?r.title:void 0;if(r.sessionUpdate==="tool_call"){this.turnRanTool=!0,r.status!=="completed"&&r.status!=="failed"&&this.openToolCalls.set(s,{startedAt:Date.now(),...o!==void 0?{title:o}:{}});return}if(r.sessionUpdate!=="tool_call_update")return;if(r.status==="completed"||r.status==="failed"){this.openToolCalls.delete(s),this.disarmOpenToolCall(s);return}let i=this.openToolCalls.get(s);i!==void 0&&o!==void 0&&(i.title=o)}armOpenToolCalls(){let e=!1;for(let[t,r]of this.openToolCalls){if(this.armedTasks.has(t))continue;let s=this.toolLabels.get(t),o=s?.fromDescription===!0?s.label:P1(r.title??s?.label??"").slice(0,Fw);this.armedTasks.set(t,{label:o===""?"running tool":o,repeating:!1,armedAt:r.startedAt,openToolCall:!0}),e=!0}e&&this.onArmedTasksChanged()}disarmOpenToolCall(e){this.armedTasks.get(e)?.openToolCall===!0&&(this.armedTasks.delete(e),this.onArmedTasksChanged())}closeOpenToolCalls(e){if(this.openToolCalls.size===0||this.closed)return;let t=[...this.openToolCalls.keys()];this.openToolCalls.clear();for(let r of t)this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"tool_call_update",toolCallId:r,status:"failed",_meta:{[ut]:{synthetic:!0,closedBy:e}}}});this.logger?.info(`session ${this.sessionId} closed ${t.length} open tool call(s) on ${e}`)}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let r=t,s=typeof r.sessionUpdate=="string"?r.sessionUpdate:"";if(s!=="tool_call"&&s!=="tool_call_update")return;let o=typeof r.toolCallId=="string"&&r.toolCallId.length>0?r.toolCallId:void 0;if(!o)return;let i=typeof r.kind=="string"?r.kind:void 0;this.toolCallKind.note(o,i);let a=this.toolCallKind.effective(o,i);if(a===iC&&Array.isArray(r.locations))for(let l of r.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:o};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p),this.reportIsolationBreach(u,o)}if(s!=="tool_call_update")return;let d=typeof r.status=="string"?r.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,d);let c={toolCallId:o,status:d};a&&(c.kind=a),r.content!==void 0&&(c.content=r.content),Array.isArray(r.locations)&&(c.locations=r.locations),this.notifyChain("tool.completed",c)}notifyChain(e,t){let r=`lifecycle:${e}`;for(let s of this.transformChain)s.intercepts.has(r)&&s.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,r){let s=this.rewriteForClient(t),o=!Lw(e,s),i=o?J1(e,s):s,a=Date.now(),d=o?this.lastSeq=Math.max(this.lastSeq+1,a):void 0,c=o?Ls(Fs(i,a),d):i;if(o){this.noteRecordedToolCall(e,i);let l={method:e,params:i,recordedAt:a,seq:d};if(this.lastRecordedAt=l.recordedAt,this.appendCount+=1,this.historyStore){let u=this.historyStore;u.append(this.sessionId,l).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,u.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let u of this.broadcastHandlers)try{u(l)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let l of this.clients.values())r&&l.clientId===r||l.connection.notify(e,c).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw Qn(new Error("no clients attached to handle permission request"),G.PermissionDenied);let r=this.rewriteForClient(e),s=LC(r),o=Hs(),{toolCall:i,options:a}=r??{};return new Promise((d,c)=>{let l=!1,u=[],f=0,p,m=this.sessionId,h=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),b())},g=b=>b?.code===G.MethodNotFound;function w(b){if(l)return;let k=b.connection.request("session/request_permission",r);u.push({client:b}),f++,k.then(S=>{f--,h(()=>{let I=Q1({toolCallId:s,result:S,resolver:b});for(let x of u)x.client.clientId!==b.clientId&&x.client.connection.notify("session/update",{sessionId:m,update:I}).catch(()=>{});d(S)})}).catch(S=>{if(f--,g(S)||(p=S),f===0&&!l){let I=p??Qn(new Error("no client handled permission request"),G.PermissionDenied);h(()=>c(I))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,w);for(let b of t)w(b)})}async enqueuePrompt(e,t){return new Promise((r,s)=>{let o={kind:"internal",messageId:Hs(),label:e,enqueuedAt:Date.now(),cancelled:!1,task:t,resolve:r,reject:s};this.promptQueue.push(o),this.drainQueue()})}async enqueueUserPrompt(e,t,r,s,o){let i=(t??{}).prompt??[],a={clientId:e.clientId};e.clientInfo?.name&&(a.name=e.clientInfo.name),e.clientInfo?.version&&(a.version=e.clientInfo.version),s?.fromSession&&(a.fromSession=s.fromSession),s?.fromSessionTitle&&(a.fromSessionTitle=s.fromSessionTitle),s?.fromLabel&&(a.fromLabel=s.fromLabel),s?.depth!==void 0&&(a.depth=s.depth);let d=this.parseQueuePosition(t);return new Promise((c,l)=>{let u={kind:"user",messageId:r,originator:a,clientId:e.clientId,prompt:i,enqueuedAt:Date.now(),cancelled:!1,resolve:c,reject:l};o?.steerOriginated===!0&&(u.wasSteer=!0);let f=this.insertEntryAt(u,d);this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),this.drainQueue()})}promptCarriesSentBy(e){if(!e||typeof e!="object")return!1;let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t[ut];if(!r||typeof r!="object"||Array.isArray(r))return!1;let s=r.sentBy;return!!s&&typeof s=="object"}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let r=t["hydra-acp"];if(!r||typeof r!="object"||Array.isArray(r))return"tail";let s=r.queuePosition;if(s==="head"||s==="tail")return s;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let r=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),r;if(typeof t=="object"){let s=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===s);if(o>=0)return this.promptQueue.splice(o+1,0,e),r+o+1}return this.promptQueue.push(e),r+this.promptQueue.length-1}persistRewrite(){let e=[];for(let r of this.promptQueue)r.kind!=="user"||r.cancelled||e.push(this.persistedFromEntry(r));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ql(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[0];if(e?.kind==="user"&&(await this.holdForUnsolicitedTurn(e),this.closing))break;let t=this.promptQueue.shift();if(!t)break;if(!t.cancelled){this.currentEntry=t,t.kind==="user"&&this.persistRewrite(),t.kind==="user"&&this.broadcastQueueRemoved(t.messageId,"started");try{let r=await this.runQueueEntry(t);t.resolve(r),await new Promise(s=>setImmediate(s))}catch(r){t.reject(r)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.supersededAutonomousTurn=void 0,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return this.closeUnsolicitedTurn("superseded",`internal:${e.label}`),e.task();this.broadcastPromptReceived(e);let t=ua(e.prompt).replace(/\s+$/,""),r=!t.includes(`
|
|
100
|
+
`)}async seedFromImport(){await this.enqueuePrompt("seed:import",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("seed:fork",async()=>{let t=this.title??"(untitled)",r=[];if(this.historyStore)try{r=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let s=Pw({synopsis:e,title:t,tail:r,tailK:v1,tailFloor:S1,watermark:this._summarizedThroughEntry,recallArmed:(this._summarizedThroughEntry??0)>0});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:s}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${s.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.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 r=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,s={};e.capacityBytes!==void 0&&(s.capacityBytes=e.capacityBytes),r!==void 0&&(s.filePath=r),e.fileCapBytes!==void 0&&(s.fileCapBytes=e.fileCapBytes),s.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_stream_truncated",...r!==void 0?{filePath:r}:{},fileCapBytes:e.fileCapBytes}})};let o=new Cp(s);this.streamBuffer=o,this.streamFilePath=r;let i={capacityBytes:o.capacity};return r!==void 0&&(i.filePath=r),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let r=this.requireStreamBuffer();if(e.length>0){let s=Buffer.from(e,"base64");r.append(s)}return t===!0&&r.close(),{writeCursor:r.writeCursorPos}}async streamRead(e,t,r){let s=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??fc,fc)),i=s.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&r!==void 0&&r>0){let d=await s.waitForData(i.nextCursor,r);(d==="data"||d==="eof")&&(i=s.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let r=this.requireStreamBuffer().tail(e);return{bytes:r.bytes.toString("base64"),startCursor:r.startCursor,endCursor:r.endCursor,truncated:r.truncated}}streamHead(e){let r=this.requireStreamBuffer().head(e);return{bytes:r.bytes.toString("base64"),startCursor:r.startCursor,endCursor:r.endCursor,truncated:r.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=G.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closeUnsolicitedTurn("closed"),e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.cancelOrphanTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.originatorNeedsTurnComplete(this.currentEntry)),this.currentEntry=void 0;let r=this.promptQueue;this.promptQueue=[];for(let o of r){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");let i=this.pendingTurnNotifiers.get(o.messageId);i&&(this.pendingTurnNotifiers.delete(o.messageId),vw(i,{sessionId:this.sessionId,messageId:i.originalMessageId,stopReason:"cancelled",deliveredAt:Date.now(),...o.messageId!==i.originalMessageId?{amendedTo:o.messageId}:{}}));try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear(),this.openToolCalls.clear();let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>_C(s).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>WC.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,r){this._setAttentionFlag(e,t,r,!0)}_setAttentionFlag(e,t,r,s){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(r))return;this.attentionFlags.set(o,{...i,payload:r,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:r});s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,r){let s=`${e}::${t}`;this.attentionFlags.delete(s)&&r&&(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.hasWorkInFlight){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},r=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${r}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()}scheduleOrphanCheck(){this.closed||this.orphanTimeoutMs<=0||this.clients.size>0||this._interactive===!0||this.armOrphanTimer(this.orphanTimeoutMs)}armOrphanTimer(e){this.orphanTimer&&clearTimeout(this.orphanTimer),this.orphanTimer=setTimeout(()=>{this.orphanTimer=void 0,this.checkOrphan()},e),typeof this.orphanTimer.unref=="function"&&this.orphanTimer.unref()}checkOrphan(){if(!this.closed&&!(this.clients.size>0||this._interactive===!0)){if(this.hasWorkInFlight){this.armOrphanTimer(this.orphanTimeoutMs);return}this.logger?.info(`session ${this.sessionId} orphan timeout fired after ${Math.round(this.orphanTimeoutMs/1e3)}s with no attached client and no prompt ever received \u2014 closing`),this.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}cancelOrphanTimer(){this.orphanTimer&&(clearTimeout(this.orphanTimer),this.orphanTimer=void 0)}get currentPromptDepth(){if(this.currentEntry?.kind==="user")return this.currentEntry.originator.depth??0}get hasWorkInFlight(){return this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0||this.armedBackgroundTasks.length>0}onIdle(e,t){let r={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(r),()=>{let s=this.idleHandlers.indexOf(r);s>=0&&this.idleHandlers.splice(s,1),r.timer&&(clearTimeout(r.timer),r.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let r of this.idleHandlers)r.timer&&(clearTimeout(r.timer),r.timer=void 0);return}let t=[...this.idleHandlers];for(let r of t){if(r.debounceMs===0){if(r.once){let s=this.idleHandlers.indexOf(r);s>=0&&this.idleHandlers.splice(s,1)}try{r.fn(this)}catch{}continue}r.timer&&(clearTimeout(r.timer),r.timer=void 0),r.timer=setTimeout(()=>{if(r.timer=void 0,!this.closed&&this.isQuiescedSync()){if(r.once){let s=this.idleHandlers.indexOf(r);s>=0&&this.idleHandlers.splice(s,1)}try{r.fn(this)}catch{}}},r.debounceMs),typeof r.timer.unref=="function"&&r.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}noteRecordedToolCall(e,t){if(e!=="session/update")return;let r=t?.update;if(r===void 0)return;let s=typeof r.toolCallId=="string"?r.toolCallId:"";if(s.length===0)return;let o=typeof r.title=="string"&&r.title!==""?r.title:void 0;if(r.sessionUpdate==="tool_call"){this.turnRanTool=!0,r.status!=="completed"&&r.status!=="failed"&&this.openToolCalls.set(s,{startedAt:Date.now(),...o!==void 0?{title:o}:{}});return}if(r.sessionUpdate!=="tool_call_update")return;if(r.status==="completed"||r.status==="failed"){this.openToolCalls.delete(s),this.disarmOpenToolCall(s);return}let i=this.openToolCalls.get(s);i!==void 0&&o!==void 0&&(i.title=o)}armOpenToolCalls(){let e=!1;for(let[t,r]of this.openToolCalls){if(this.armedTasks.has(t))continue;let s=this.toolLabels.get(t),o=s?.fromDescription===!0?s.label:P1(r.title??s?.label??"").slice(0,Fw);this.armedTasks.set(t,{label:o===""?"running tool":o,repeating:!1,armedAt:r.startedAt,openToolCall:!0}),e=!0}e&&this.onArmedTasksChanged()}disarmOpenToolCall(e){this.armedTasks.get(e)?.openToolCall===!0&&(this.armedTasks.delete(e),this.onArmedTasksChanged())}closeOpenToolCalls(e){if(this.openToolCalls.size===0||this.closed)return;let t=[...this.openToolCalls.keys()];this.openToolCalls.clear();for(let r of t)this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"tool_call_update",toolCallId:r,status:"failed",_meta:{[ut]:{synthetic:!0,closedBy:e}}}});this.logger?.info(`session ${this.sessionId} closed ${t.length} open tool call(s) on ${e}`)}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let r=t,s=typeof r.sessionUpdate=="string"?r.sessionUpdate:"";if(s!=="tool_call"&&s!=="tool_call_update")return;let o=typeof r.toolCallId=="string"&&r.toolCallId.length>0?r.toolCallId:void 0;if(!o)return;let i=typeof r.kind=="string"?r.kind:void 0;this.toolCallKind.note(o,i);let a=this.toolCallKind.effective(o,i);if(a===iC&&Array.isArray(r.locations))for(let l of r.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:o};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p),this.reportIsolationBreach(u,o)}if(s!=="tool_call_update")return;let d=typeof r.status=="string"?r.status:void 0;if(d!=="completed"&&d!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,d);let c={toolCallId:o,status:d};a&&(c.kind=a),r.content!==void 0&&(c.content=r.content),Array.isArray(r.locations)&&(c.locations=r.locations),this.notifyChain("tool.completed",c)}notifyChain(e,t){let r=`lifecycle:${e}`;for(let s of this.transformChain)s.intercepts.has(r)&&s.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,r){let s=this.rewriteForClient(t),o=!Lw(e,s),i=o?J1(e,s):s,a=Date.now(),d=o?this.lastSeq=Math.max(this.lastSeq+1,a):void 0,c=o?Ls(Fs(i,a),d):i;if(o){this.noteRecordedToolCall(e,i);let l={method:e,params:i,recordedAt:a,seq:d};if(this.lastRecordedAt=l.recordedAt,this.appendCount+=1,this.historyStore){let u=this.historyStore;u.append(this.sessionId,l).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,u.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let u of this.broadcastHandlers)try{u(l)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let l of this.clients.values())r&&l.clientId===r||l.connection.notify(e,c).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw Qn(new Error("no clients attached to handle permission request"),G.PermissionDenied);let r=this.rewriteForClient(e),s=LC(r),o=Us(),{toolCall:i,options:a}=r??{};return new Promise((d,c)=>{let l=!1,u=[],f=0,p,m=this.sessionId,h=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),b())},g=b=>b?.code===G.MethodNotFound;function w(b){if(l)return;let k=b.connection.request("session/request_permission",r);u.push({client:b}),f++,k.then(S=>{f--,h(()=>{let I=Q1({toolCallId:s,result:S,resolver:b});for(let x of u)x.client.clientId!==b.clientId&&x.client.connection.notify("session/update",{sessionId:m,update:I}).catch(()=>{});d(S)})}).catch(S=>{if(f--,g(S)||(p=S),f===0&&!l){let I=p??Qn(new Error("no client handled permission request"),G.PermissionDenied);h(()=>c(I))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,w);for(let b of t)w(b)})}async enqueuePrompt(e,t){return new Promise((r,s)=>{let o={kind:"internal",messageId:Us(),label:e,enqueuedAt:Date.now(),cancelled:!1,task:t,resolve:r,reject:s};this.promptQueue.push(o),this.drainQueue()})}async enqueueUserPrompt(e,t,r,s,o){let i=(t??{}).prompt??[],a={clientId:e.clientId};e.clientInfo?.name&&(a.name=e.clientInfo.name),e.clientInfo?.version&&(a.version=e.clientInfo.version),s?.fromSession&&(a.fromSession=s.fromSession),s?.fromSessionTitle&&(a.fromSessionTitle=s.fromSessionTitle),s?.fromLabel&&(a.fromLabel=s.fromLabel),s?.depth!==void 0&&(a.depth=s.depth);let d=this.parseQueuePosition(t);return new Promise((c,l)=>{let u={kind:"user",messageId:r,originator:a,clientId:e.clientId,prompt:i,enqueuedAt:Date.now(),cancelled:!1,resolve:c,reject:l};o?.steerOriginated===!0&&(u.wasSteer=!0);let f=this.insertEntryAt(u,d);this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),this.drainQueue()})}promptCarriesSentBy(e){if(!e||typeof e!="object")return!1;let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t[ut];if(!r||typeof r!="object"||Array.isArray(r))return!1;let s=r.sentBy;return!!s&&typeof s=="object"}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let r=t["hydra-acp"];if(!r||typeof r!="object"||Array.isArray(r))return"tail";let s=r.queuePosition;if(s==="head"||s==="tail")return s;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let r=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),r;if(typeof t=="object"){let s=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===s);if(o>=0)return this.promptQueue.splice(o+1,0,e),r+o+1}return this.promptQueue.push(e),r+this.promptQueue.length-1}persistRewrite(){let e=[];for(let r of this.promptQueue)r.kind!=="user"||r.cancelled||e.push(this.persistedFromEntry(r));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ql(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[0];if(e?.kind==="user"&&(await this.holdForUnsolicitedTurn(e),this.closing))break;let t=this.promptQueue.shift();if(!t)break;if(!t.cancelled){this.currentEntry=t,t.kind==="user"&&this.persistRewrite(),t.kind==="user"&&this.broadcastQueueRemoved(t.messageId,"started");try{let r=await this.runQueueEntry(t);t.resolve(r),await new Promise(s=>setImmediate(s))}catch(r){t.reject(r)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.supersededAutonomousTurn=void 0,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return this.closeUnsolicitedTurn("superseded",`internal:${e.label}`),e.task();this.broadcastPromptReceived(e);let t=ua(e.prompt).replace(/\s+$/,""),r=!t.includes(`
|
|
101
101
|
`)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",s=r.startsWith("/")?r.slice(1):"",o=s.length>0&&this.aliasableBareVerbs().has(s);if(r==="/model"||r==="/mode"||r==="/sessions"||r==="/help"||r==="/hydra"||o){let d;if(r==="/sessions")d=await this.handleSessionsCommand();else if(r==="/help")d=await this.handleHelpCommand();else if(r==="/mode")d=await this.handleModeCommand(t);else if(r==="/model")d=await this.handleModelCommand(t);else if(o){let c=t.slice(r.length).trim(),l=c?`/hydra ${s} ${c}`:`/hydra ${s}`;d=await this.handleSlashCommand(l,e.messageId)}else d=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,d,e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),d}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let i=e.prompt;r&&this.agentAdvertisedCommands.length>0&&!this.agentKnowsSlashCommand(r)&&(i=Nw(e.prompt,eN));let a;this.agentTurnInFlight=!0;try{i=this.applyWorkspacePromptRewrite(i),a=await this.dispatchPrompt(e,i)}catch(d){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),d}finally{this.agentTurnInFlight=!1}return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,this.originatorNeedsTurnComplete(e)),this.clearAmendIfMatches(e.messageId),a}async dispatchPrompt(e,t){let r=()=>this.awaitPromptResponse(this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:t},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0));try{return await r()}catch(s){if(this.loadExistingAgentSession&&F1(s))return this.logger?.warn(`agent ${this.agentId} no longer knows upstream session ${this.upstreamSessionId} for ${this.sessionId}; reloading it onto a fresh process and retrying the prompt once`),await this.reloadUpstreamAfterAgentLoss(),await r();if(!N1(s)||this.turnRanTool||(this.logger?.warn(`agent ${this.agentId} hit a transient auth failure for ${this.sessionId}; retrying the prompt once in ${FC}ms`),await new Promise(o=>setTimeout(o,FC)),e.cancelled))throw s;return await r()}}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}},O1=["session not found","the claude agent session has ended"];L1=["failed to refresh oauth token"],FC=6e4;D1=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction"]);eN="\u200B"});import{z as wc}from"zod";var nN,qC,zC=q(()=>{"use strict";nN=wc.object({source:wc.string(),reason:wc.string(),raisedAt:wc.number(),payload:wc.unknown()}),qC=wc.array(nN)});import{z as wt}from"zod";function JC(n){let e=n.trim();if(e.length===0)return;let t=bc(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=bc(e.slice(o,i+1)))}if(t===void 0){let o=YC(e);o!==void 0&&(t=bc(o))}if(t===void 0||t===null||typeof t!="object")return;let r=t,s={};if(typeof r.title=="string"){let o=r.title.trim();o.length>0&&(s.title=o.slice(0,GC))}if(r.synopsis!==void 0&&r.synopsis!==null){let o=Zl.safeParse(r.synopsis);o.success&&rN(o.data)&&(s.synopsis=o.data)}if(!(s.title===void 0&&s.synopsis===void 0))return s}function VC(n){let e=n.trim();if(e.length===0)return;let t=bc(e);if(t===void 0){let c=e.indexOf("{"),l=e.lastIndexOf("}");c>=0&&l>c&&(t=bc(e.slice(c,l+1)))}if(t===void 0){let c=YC(e);c!==void 0&&(t=bc(c))}if(t===void 0||t===null||typeof t!="object")return;let r=t,s={};if(typeof r.title=="string"){let c=r.title.trim();c.length>0&&(s.title=c.slice(0,GC))}let o={},i=!1,a=["goal","outcome"];for(let c of a)if(typeof r[c]=="string"){let l=r[c].trim();l.length>0&&(o[c]=l,i=!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(r[c])){let l=r[c],u=wt.array(wt.string()).safeParse(l);u.success&&l.length>0&&(o[c]=u.data,i=!0)}if(i&&(s.synopsis=o),!(s.title===void 0&&s.synopsis===void 0))return s}function bc(n){try{return JSON.parse(n)}catch{return}}function YC(n){let e=n.indexOf("{");if(e<0)return;let t=0,r=!1,s=!1;for(let o=e;o<n.length;o++){let i=n[o];if(r){s?s=!1:i==="\\"?s=!0:i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return n.slice(e,o+1)}}function rN(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 KC,Zl,GC,Uw,Ww,$p=q(()=>{"use strict";KC=wt.object({status:wt.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:wt.number(),runId:wt.string().optional(),iter:wt.number().int().nonnegative().optional(),attempts:wt.number().int().nonnegative().optional(),lastError:wt.string().optional(),worker:wt.object({upstreamSessionId:wt.string(),pid:wt.number().int().nonnegative()}).optional()}),Zl=wt.object({goal:wt.string().optional(),outcome:wt.string().optional(),files_touched:wt.array(wt.string()).optional(),tools_used:wt.array(wt.string()).optional(),rejected_approaches:wt.array(wt.string()).optional(),open_threads:wt.array(wt.string()).optional(),decisions:wt.array(wt.string()).optional(),file_edit_intentions:wt.array(wt.string()).optional(),unresolved_errors:wt.array(wt.string()).optional(),tool_state:wt.array(wt.string()).optional()}),GC=200,Uw=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
102
102
|
{
|
|
103
103
|
"title": "short summary, max 80 chars",
|
|
@@ -124,7 +124,7 @@ Use empty arrays/strings where a field doesn't apply.`});import*as Cr from"fs/pr
|
|
|
124
124
|
`))if(t.length!==0)try{let r=JSON.parse(t);typeof r=="string"&&e.push(r)}catch{}return e}function cu(n,e,t=TR){let r=e.replace(/\n+$/,"");if(r.length===0||n.length>0&&n[n.length-1]===r)return n;let s=n.concat(r);return s.length>t?s.slice(s.length-t):s}function ER(n,e){return e===null?!1:n>=e}async function ha(n,e){await au.mkdir(cb.dirname(n),{recursive:!0});let t=e.map(r=>JSON.stringify(r));await au.writeFile(n,t.length>0?t.join(`
|
|
125
125
|
`)+`
|
|
126
126
|
`:"")}async function PR(n,e){let t=e.replace(/\n+$/,"");t.length!==0&&(await au.mkdir(cb.dirname(n),{recursive:!0}),await au.appendFile(n,JSON.stringify(t)+`
|
|
127
|
-
`,{encoding:"utf8"}))}function nh(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(s=>!t.has(s)),...e]}function lb(n,e,t=TR){if(e.length===0)return n;let r=new Set(n),s=n;for(let o of e){let i=o.replace(/\n+$/,"");i.length!==0&&(r.has(i)||(r.add(i),s=cu(s,i,t)))}return s}var TR,rh=q(()=>{"use strict";TR=500});import{z as ft}from"zod";function lu(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 as(n){return sD.parse(n)}var nD,rD,sD,ma=q(()=>{"use strict";Jw();$p();nD=ft.object({method:ft.string(),params:ft.unknown(),recordedAt:ft.number()}),rD=ft.object({sessionId:ft.string(),lineageId:ft.string(),upstreamSessionId:ft.string().optional(),agentId:ft.string(),cwd:ft.string(),title:ft.string().optional(),synopsis:Zl.optional(),summarizedThroughEntry:ft.number().int().nonnegative().optional(),currentModel:ft.string().optional(),currentMode:ft.string().optional(),currentUsage:zw.optional(),agentCommands:ft.array(jw).optional(),agentModes:ft.array(qw).optional(),interactive:ft.boolean().optional(),originatingClient:Kw.optional(),priority:ft.number().int().nonnegative().optional(),createdAt:ft.string(),updatedAt:ft.string()}),sD=ft.object({version:ft.literal(1),exportedAt:ft.string(),exportedFrom:ft.object({hydraVersion:ft.string(),machine:ft.string(),hydraHost:ft.string().optional()}),session:rD,history:ft.array(nD),promptHistory:ft.array(ft.string()).optional(),toolBlobs:ft.record(ft.string()).optional()})});function uu(n){if(n&&!(n.costAmount===void 0&&n.cumulativeCost===void 0))return(n.cumulativeCost??0)+(n.costAmount??0)}function ga(n){if(!n)return;let e={};n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size);let t=uu(n);return t&&(e.costAmount=t),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),e}var Sc=q(()=>{"use strict"});import*as ah from"fs/promises";import*as Ic from"path";async function BR(n){try{return await ah.stat(n),n}catch{}if(Ic.basename(n)!==gD)return n;let e=Ic.dirname(n),t;try{t=await ah.readdir(e)}catch{return n}let r;for(let s of t){let o=/\.(\d+)(?:\.[^.]+)?$/.exec(s);if(!o)continue;let i=Number(o[1]);Number.isFinite(i)&&(!r||i>r.n)&&(r={name:s,n:i})}return r?Ic.join(e,r.name):n}var dh,gD,ch=q(()=>{"use strict";dh=process.platform!=="win32",gD="current.log"});import{createHash as ID}from"crypto";function bu(n){if(Array.isArray(n))return n.map(bu);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=bu(n[t]);return e}return n}function ci(n){let e={};for(let[r,s]of Object.entries(n)){let o=ry(r);if(o.nested){let i={};for(let[a,d]of Object.entries(s??{}))sy(a).reload==="restart"&&(i[a]=d);Object.keys(i).length>0&&(e[r]=i);continue}o.reload==="restart"&&(e[r]=s)}let t=JSON.stringify(bu(e));return ID("sha256").update(t).digest("hex").slice(0,16)}function jR(n,e){let t=[],r=(s,o)=>JSON.stringify(bu(s))!==JSON.stringify(bu(o));for(let s of Object.keys(e)){let o=ry(s),i=e[s],a=n[s];if(o.nested){for(let d of Object.keys(i??{})){if(sy(d).reload!=="warn")continue;let c=i[d],l=(a??{})[d];r(l,c)&&t.push(`${s}.${d}`)}continue}o.reload==="warn"&&r(a,i)&&t.push(s)}return t}var Rc=q(()=>{"use strict";rt();iy()});function vb(n){return Math.floor(n/4)}function nA(n){let e=0,t=new Map;for(let r of n){let s=r.params;if(!s||typeof s!="object")continue;let o=s.update;if(!o||typeof o!="object")continue;let i=o;switch(i.sessionUpdate){case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":e+=va(i.content);break;case"tool_call":case"tool_call_update":{let a=typeof i.toolCallId=="string"?i.toolCallId:"",d=DD(i),c=t.get(a)??0;d>c&&t.set(a,d);break}default:break}}for(let r of t.values())e+=r;return e}function DD(n){let e=0;return typeof n.title=="string"&&(e+=n.title.length),e+=Sh(n.rawInput),e+=va(n.content),e+=Sh(n.rawOutput),e}function Sh(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(typeof n=="number"||typeof n=="boolean")return String(n).length;if(Array.isArray(n)){let e=0;for(let t of n)e+=Sh(t);return e}if(typeof n=="object"){let e=n.bytes;if(typeof n.__hydraBlob=="string"&&typeof e=="number")return e;let t=0;for(let r of Object.values(n))t+=Sh(r);return t}return 0}function va(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(Array.isArray(n)){let t=0;for(let r of n)t+=va(r);return t}if(typeof n!="object")return 0;let e=n;return typeof e.__hydraBlob=="string"&&typeof e.bytes=="number"?e.bytes:e.text!==void 0?va(e.text):e.type==="diff"?va(e.oldText)+va(e.newText):e.content!==void 0?va(e.content):0}function rA(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e,t;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize,t=!0;else{let s=vb(n.unsummarizedChars),o=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/o,t=!1}if(t&&e>=n.config.hardCeilingFraction)return!0;let r=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&r>=n.config.idleBeforePromptMs}function sA(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var Sb=q(()=>{"use strict"});function ku(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}function xb(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let r=t.parentToolUseId;return typeof r=="string"?r:void 0}var oA=q(()=>{"use strict"});import{posix as BD}from"path";import HD from"strip-ansi";function zt(n){return HD(n).replace(UD,"")}function ot(n){return zt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Ws(n,e={}){if(!n||typeof n!="object")return null;let t=n,r=t.sessionUpdate??t.kind;if(typeof r!="string")return null;switch(r){case"agent_message_chunk":return GD(t);case"agent_thought_chunk":case"agent_thought":return JD(t);case"user_message_chunk":return VD(t);case"prompt_received":return YD(t);case"tool_call":return QD(t,e);case"tool_call_update":return nB(t,e);case"plan":return oB(t);case"current_mode_update":return iB(t);case"_hydra_current_model_update":return aB(t);case"turn_complete":return dB(t);case"_hydra_turn_started":return dA(t,"turn-started");case"_hydra_turn_ended":return dA(t,"turn-ended");case"usage_update":return KD(t);case"available_commands_update":return qD(t);case"_hydra_available_modes_update":return zD(t);case"session_info_update":return jD(t);case"config_option_update":return WD(t);default:return{kind:"unknown",sessionUpdate:r,raw:n}}}function WD(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||typeof s.currentValue!="string"||!Array.isArray(s.options))continue;let o=[];for(let i of s.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:s.id,name:typeof s.name=="string"?s.name:s.id,type:"select",currentValue:s.currentValue,options:o,...typeof s.category=="string"?{category:s.category}:{}})}return{kind:"config-options",options:t}}function jD(n){let e=qt(n,"title"),t=e!==void 0?ot(e):void 0,r=n._meta,s,o;if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(s=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&s===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),s!==void 0&&(i.agentId=s),o!==void 0&&(i.pendingAgentSwap=o),i}function xh(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.name!="string"||r.name.length===0)continue;let s=r.name.startsWith("/")?r.name:`/${r.name}`,o={name:ot(s)};typeof r.description=="string"&&(o.description=ot(r.description)),e.push(o)}return e}function qD(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:xh(e)}:null}function zD(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||s.id.length===0)continue;let o={id:ot(s.id)};typeof s.name=="string"&&(o.name=ot(s.name)),typeof s.description=="string"&&(o.description=ot(s.description)),t.push(o)}return{kind:"available-modes",modes:t}}function KD(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 GD(n){let e=vu(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ku(n)}}function JD(n){let e=typeof n.text=="string"?zt(n.text):vu(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ku(n)}}function VD(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e["hydra-acp"];if(r&&typeof r=="object"&&!Array.isArray(r)&&r.compatFor==="prompt_received")return null}let t=vu(n.content);return t===null?null:{kind:"user-text",text:t}}function YD(n){let e=cB(n.prompt);return e===null?null:{kind:"user-text",text:e}}function cA(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function iA(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 Ih(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(s.type!=="diff")continue;let o=iA(s.oldText),i=iA(s.newText);if(o===void 0&&i===void 0)continue;let a=typeof s.path=="string"?s.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t,s=typeof r.file_path=="string"?r.file_path:typeof r.path=="string"?r.path:void 0;if(typeof r.old_string=="string"&&typeof r.new_string=="string")return{...s!==void 0?{path:s}:{},oldText:r.old_string,newText:r.new_string};if(typeof r.content=="string")return{...s!==void 0?{path:s}:{},oldText:"",newText:r.content}}return null}function lA(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:zt(t)}function QD(n,e={}){let t=qt(n,"toolCallId")??qt(n,"id");if(!t)return null;let r=qt(n,"title")??qt(n,"name")??qt(n,"label")??"tool call",s=qt(n,"name")??qt(n,"title");if(cA(s)){let h=lA(n);if(h!==null){let g=qt(n,"status"),w={kind:"exit-plan-mode",toolCallId:t,plan:h};return g!==void 0&&(w.status=g),w}}let o=pA(ot(r),n,e),i=qt(n,"status"),a=qt(n,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=Ih(n);c!==null&&(d.editDiff=c);let l=fA(n);l!==void 0&&(d.detail=l);let u=Ib(n);u!==void 0&&(d.detailFull=u);let f=uA(n);f!==void 0&&(d.locations=f);let p=ku(n);p!==void 0&&(d.workerTaskId=p);let m=xb(n);return m!==void 0&&(d.parentToolUseId=m),d}function uA(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.path!="string"||s.path.length===0)continue;let o={path:s.path};typeof s.line=="number"&&Number.isFinite(s.line)&&s.line>=1&&(o.line=Math.floor(s.line)),t.push(o)}return t.length>0?t:void 0}function fA(n){let e=Ib(n);if(e===void 0)return;let t=ot(e),r=n.rawInput;return r&&typeof r.command=="string"?eB(t,aA):tB(t,aA)}function Ib(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 zt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let r=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(r!==void 0&&r.length>0)return V(ot(r))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let r=t.path;if(typeof r=="string"&&r.length>0)return V(ot(r))}}}function ZD(n){for(let e of XD)if(n.startsWith(e))return!0;return!1}function pA(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return V(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let r=e.rawInput;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=[s.file_path,s.filePath,s.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return V(i)}return ZD(n)?V(`/${n}`):t.cwd&&t.cwd.length>0?V(BD.resolve(t.cwd,n)):n}function eB(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function tB(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),r=t.indexOf("/");return r>=0&&r<e/2?`\u2026${t.slice(r)}`:`\u2026${t}`}function nB(n,e={}){let t=qt(n,"toolCallId")??qt(n,"id");if(!t)return null;let r=qt(n,"title"),s=r!==void 0?pA(ot(r),n,e):void 0,o=qt(n,"status"),i=Ih(n),a=fA(n),d=Cb(n);if(!(s!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let l=qt(n,"name")??r;if(cA(l)){let g={kind:"exit-plan-mode",toolCallId:t},w=lA(n);return w!==null&&(g.plan=w),o!==void 0&&(g.status=o),g}let u={kind:"tool-call-update",toolCallId:t};s!==void 0&&(u.title=s),a!==void 0&&(u.detail=a);let f=Ib(n);f!==void 0&&(u.detailFull=f);let p=uA(n);if(p!==void 0&&(u.locations=p),d!==void 0&&(u.resultSummary=d),o!==void 0&&(u.status=o),i!==null&&(u.editDiff=i),o==="failed"){let g=rB(n);g!==null&&(u.errorText=g),sB(n,g)&&(u.upstreamInterrupted=!0)}let m=ku(n);m!==void 0&&(u.workerTaskId=m);let h=xb(n);return h!==void 0&&(u.parentToolUseId=h),u}function Cb(n){if(!n||typeof n!="object")return;let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r=l=>{let u=t[l];return typeof u=="number"&&Number.isFinite(u)?u:void 0},s=(l,u,f=`${u}s`)=>`${l} ${l===1?u:f}`,o=[],i=r("totalMatches");i!==void 0&&o.push(s(i,"match","matches"));let a=r("totalFiles");a!==void 0&&o.push(s(a,"file"));let d=r("referenceCount");d!==void 0&&o.push(s(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let c=r("exitCode");return c!==void 0&&c!==0&&o.push(`exit ${c}`),o.length>0?o.join(", "):void 0}function hA(n){if(!n||typeof n!="object")return[];let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e,r=[];for(let s of["content","stdout","stderr"]){let o=t[s];typeof o=="string"?o.length>0&&r.push(o):o&&typeof o=="object"&&!Array.isArray(o)&&r.push(o)}return r}function rB(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=vu(r.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"&&r.length>0)return zt(r)}return null}function sB(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.metadata;if(r&&typeof r=="object"&&r.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function oB(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r,o=typeof s.content=="string"?ot(s.content):void 0;if(!o)continue;let i={content:o};typeof s.status=="string"&&(i.status=s.status),typeof s.priority=="string"&&(i.priority=s.priority),t.push(i)}return{kind:"plan",entries:t}}function iB(n){let e=qt(n,"currentModeId")??qt(n,"currentMode")??qt(n,"mode");return e?{kind:"mode-changed",mode:ot(e)}:null}function aB(n){let e=qt(n,"currentModel")??qt(n,"model");if(!e)return null;let t=n.availableModels,r=Array.isArray(t)?t.map(s=>typeof s=="object"&&s!==null?s.modelId:typeof s=="string"?s:void 0).filter(s=>typeof s=="string"&&s.length>0):void 0;return{kind:"model-changed",model:ot(e),...r&&r.length>0?{availableModels:r}:{}}}function dB(n){let e=qt(n,"stopReason"),t=n._meta,r=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,s={kind:"turn-complete"};return e!==void 0&&(s.stopReason=e),r&&(s.amended=!0),s}function dA(n,e){let r=n._meta?.["hydra-acp"],s=r?.unsolicited===!0;if(e==="turn-started"){let i=r?.cause?.label,a={kind:e,unsolicited:s};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:s};return typeof r?.reason=="string"&&(o.reason=r.reason),o}function vu(n){if(typeof n=="string")return zt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?zt(e.text):null}function cB(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let r=vu(t);r!==null&&e.push(r)}return e.length===0?null:e.join("")}function qt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var UD,aA,XD,Io=q(()=>{"use strict";ke();oA();UD=/[\x00-\x08\x0b-\x1f\x7f]/g;aA=64;XD=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Ac(n){let e=new Map,t=new Map;for(let s of n){let i=s.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=uB(i);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(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)lB(t,u)}let r=[];for(let[s,o]of t)r.push({path:s,hunks:o.hunks,created:o.created});return r}function Tc(n){let e=[];for(let t of n){let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){r=o;break}if(r===-1){e.push(t);continue}let s=e[r];e.splice(r,1,{oldText:s.oldText,newText:t.newText})}return e}function lB(n,e){let t={oldText:e.oldText,newText:e.newText},r=n.get(e.path);if(r===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}r.hunks.push(t)}function uB(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==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:i,oldText:l,newText:u})}if(e.length>0)return e}}let r=n.content;if(Array.isArray(r)){for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let d=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let s=Ih(n);return s&&s.path&&e.push({path:s.path,oldText:s.oldText,newText:s.newText}),e}var Ch=q(()=>{"use strict";Io()});function SB(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,r=[],s;for(;(s=t.exec(e))!==null;)r.push(s[0]);let o="OR",i=!1,a=!1,d=[];for(let l of r){let u=l.toUpperCase();u==="AND"?i=!0:u==="OR"?a=!0:d.push(l)}i?o="AND":a&&(o="OR");let c=d.map(l=>xB(l)).filter(l=>l.term.length>0);return{operator:o,terms:c}}function xB(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:yA(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let r=/^(prompt|response|tool|edit|edited):([\s\S]*)$/i.exec(n);return r?{scope:yA(r[1]),term:r[2].trim()}:{scope:"all",term:n.trim()}}function yA(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";case"edit":case"edited":return"edit";default:return"all"}}function IB(n,e){return e==="edit"?n==="edit":n==="edit"?!1:n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}function SA(n){return Number.isFinite(n)?Math.max(AB,Math.min(TB,Math.floor(n))):Th}async function xA(n,e,t={}){let r=SB(e);if(r.terms.length===0)return{query:e,truncated:!1,results:[]};let s=t.maxSnippetsPerSession??CB,o=t.maxSessions??RB,i=SA(t.snippetWidth??Th),a=t.sessionIds?new Set(t.sessionIds):null,d=await n.list(),c=a?d.filter(f=>a.has(f.sessionId)):d,l=[],u=!1;for(let f of c){if(l.length>=o){u=!0;break}let p=await n.loadHistory(f.sessionId,{tools:"references"}).catch(()=>[]),m=EB(p,r,s,i,Ec(f));if(m.snippets.length===0)continue;let h={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:m.totalMatches,snippets:m.snippets};f.title!==void 0&&(h.title=f.title),l.push(h)}return{query:e,truncated:u,results:l}}function Ec(n){let e=n.workspace?.sourceCwd;if(e===void 0||e.length===0||n.cwd.length===0)return;let t=n.cwd.endsWith("/")?n.cwd:n.cwd+"/";return r=>r.startsWith(t)?e.replace(/\/+$/,"")+"/"+r.slice(t.length):r}function EB(n,e,t,r=Th,s){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let o=0,i=[],a=Math.max(1,Math.floor(t/e.terms.length)),d=[];for(let{scope:c,term:l}of e.terms){let u=PB(n,l,c,t,r,s);if(e.operator==="AND"&&u.totalMatches===0)return{totalMatches:0,snippets:[]};o+=u.totalMatches,i.push(...u.snippets.slice(0,a)),d.push(...u.snippets.slice(a))}for(let c of d){if(i.length>=t)break;i.push(c)}return{totalMatches:o,snippets:i.slice(0,t)}}function PB(n,e,t,r,s,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let l of n){let u=MB(l).filter(f=>IB(t,f.kind));for(let f of u){let p=f.text.toLowerCase();if(f.kind==="edit"){let g=o?.(f.text);if(!(wA(f.text,e)||(g!==void 0&&g!==f.text?wA(g,e):!1))||c.has(f.text))continue;if(c.add(f.text),a+=1,d.length<r){let b={kind:"edit",text:f.text,recordedAt:l.recordedAt};f.toolName!==void 0&&(b.toolName=f.toolName),d.push(b)}continue}let m=p.indexOf(i);if(m===-1)continue;let h=0;for(;m!==-1;)h++,m=p.indexOf(i,m+i.length);if(a+=h,d.length<r){let g=p.indexOf(i),w={kind:f.kind,text:DB(f.text,g,i.length,s),recordedAt:l.recordedAt};f.toolName!==void 0&&(w.toolName=f.toolName),d.push(w)}}}return{totalMatches:a,snippets:d}}function MB(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 r=t,s=typeof r.sessionUpdate=="string"?r.sessionUpdate:r.kind;if(typeof s!="string")return[];switch(s){case"agent_message_chunk":{let o=Ah(r.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof r.text=="string"?zt(r.text):Ah(r.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(LB(r))return[];let o=Ah(r.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=NB(r.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return _B(r);default:return[]}}function _B(n){let e=kA(n,"name"),t=kA(n,"title"),r=[];if(t!==void 0){let a=ot(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),r.push(d)}}if(e!==void 0&&e!==t){let a=ot(e);a.length>0&&r.push({kind:"tool",toolName:e,text:a})}let s=n.rawInput;if(s&&typeof s=="object"){let a=vA(s);if(a.length>0){let d={kind:"tool-input",text:ot(a)};e!==void 0&&(d.toolName=e),r.push(d)}}for(let a of $B(n)){let d={kind:"edit",text:a};e!==void 0&&(d.toolName=e),r.push(d)}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=vA(o);if(a.length>0){let d={kind:"tool-input",text:ot(a)};e!==void 0&&(d.toolName=e),r.push(d)}}let i=OB(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),r.push(a)}return r}function $B(n){let e=[],t=new Set,r=i=>{typeof i!="string"||i.length===0||t.has(i)||(t.add(i),e.push(i))},s=n.content;if(Array.isArray(s))for(let i of s){if(!i||typeof i!="object")continue;let a=i;a.type==="diff"&&r(a.path)}let o=n.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o;(i.old_string!==void 0||i.new_string!==void 0||i.content!==void 0||Array.isArray(i.edits))&&r(typeof i.file_path=="string"?i.file_path:i.path)}return e}function wA(n,e){let t=bA(n.toLowerCase()),r=bA(e.toLowerCase());if(r.length===0)return!1;if(r.startsWith("/"))return t===r||t.startsWith(r+"/");let s="/"+r,o=t.indexOf(s);for(;o!==-1;){let i=o+s.length;if(i===t.length||t[i]==="/")return!0;o=t.indexOf(s,o+1)}return t===r||t.startsWith(r+"/")}function bA(n){return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function OB(n){if(!FB(n.status))return null;let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=r.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=ot(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"){let s=ot(r);if(s.length>0)return s}}return null}function FB(n){return n==="failed"||n==="rejected"||n==="cancelled"}function LB(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 Ah(n){if(typeof n=="string")return zt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?zt(e.text):""}function NB(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let r=Ah(t);r.length>0&&e.push(r)}return e.join("")}function kA(n,e){let t=n[e];return typeof t=="string"?t:void 0}function vA(n){try{return JSON.stringify(n)}catch{return""}}function DB(n,e,t,r=Th){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let o=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),a=i.length>0?o.indexOf(i):0;a===-1&&(a=0);let d=SA(r),c=Math.max(0,d-i.length),l=Math.floor(c/2),u=Math.min(l,a),f=Math.min(c-u,s.length-(a+i.length)),p=Math.max(0,a-(c-f)),m=Math.min(s.length,a+i.length+f),h=p>0?"\u2026":"",g=m<s.length?"\u2026":"";return`${h}${s.slice(p,m)}${g}`}var CB,RB,Th,AB,TB,Eh=q(()=>{"use strict";Io();CB=5,RB=200,Th=72,AB=24,TB=512});function Rr(n){let e=[],t=[],r=!1,s=o=>{if(!r){r=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.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:G.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>s()),n.on("error",o=>s(o)),{async send(o){if(r)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{n.send(i,c=>{if(c){d(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){r||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(d),o())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),s())}}}var Sa=q(()=>{"use strict";fn()});import*as Ia from"fs/promises";import*as sU from"path";async function ST(n,e=20){let t=D.daemonBootLog();try{if((await Ia.stat(t)).mtimeMs<n-1e3)return;let i=(await Ia.readFile(t,"utf8")).trimEnd().split(`
|
|
127
|
+
`,{encoding:"utf8"}))}function nh(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(s=>!t.has(s)),...e]}function lb(n,e,t=TR){if(e.length===0)return n;let r=new Set(n),s=n;for(let o of e){let i=o.replace(/\n+$/,"");i.length!==0&&(r.has(i)||(r.add(i),s=cu(s,i,t)))}return s}var TR,rh=q(()=>{"use strict";TR=500});import{z as ft}from"zod";function lu(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 as(n){return sD.parse(n)}var nD,rD,sD,ma=q(()=>{"use strict";Jw();$p();nD=ft.object({method:ft.string(),params:ft.unknown(),recordedAt:ft.number()}),rD=ft.object({sessionId:ft.string(),lineageId:ft.string(),upstreamSessionId:ft.string().optional(),agentId:ft.string(),cwd:ft.string(),title:ft.string().optional(),synopsis:Zl.optional(),summarizedThroughEntry:ft.number().int().nonnegative().optional(),currentModel:ft.string().optional(),currentMode:ft.string().optional(),currentUsage:zw.optional(),agentCommands:ft.array(jw).optional(),agentModes:ft.array(qw).optional(),interactive:ft.boolean().optional(),originatingClient:Kw.optional(),priority:ft.number().int().nonnegative().optional(),createdAt:ft.string(),updatedAt:ft.string()}),sD=ft.object({version:ft.literal(1),exportedAt:ft.string(),exportedFrom:ft.object({hydraVersion:ft.string(),machine:ft.string(),hydraHost:ft.string().optional()}),session:rD,history:ft.array(nD),promptHistory:ft.array(ft.string()).optional(),toolBlobs:ft.record(ft.string()).optional()})});function uu(n){if(n&&!(n.costAmount===void 0&&n.cumulativeCost===void 0))return(n.cumulativeCost??0)+(n.costAmount??0)}function ga(n){if(!n)return;let e={};n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size);let t=uu(n);return t&&(e.costAmount=t),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),e}var Sc=q(()=>{"use strict"});import*as ah from"fs/promises";import*as Ic from"path";async function BR(n){try{return await ah.stat(n),n}catch{}if(Ic.basename(n)!==gD)return n;let e=Ic.dirname(n),t;try{t=await ah.readdir(e)}catch{return n}let r;for(let s of t){let o=/\.(\d+)(?:\.[^.]+)?$/.exec(s);if(!o)continue;let i=Number(o[1]);Number.isFinite(i)&&(!r||i>r.n)&&(r={name:s,n:i})}return r?Ic.join(e,r.name):n}var dh,gD,ch=q(()=>{"use strict";dh=process.platform!=="win32",gD="current.log"});import{createHash as ID}from"crypto";function bu(n){if(Array.isArray(n))return n.map(bu);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=bu(n[t]);return e}return n}function ci(n){let e={};for(let[r,s]of Object.entries(n)){let o=ry(r);if(o.nested){let i={};for(let[a,d]of Object.entries(s??{}))sy(a).reload==="restart"&&(i[a]=d);Object.keys(i).length>0&&(e[r]=i);continue}o.reload==="restart"&&(e[r]=s)}let t=JSON.stringify(bu(e));return ID("sha256").update(t).digest("hex").slice(0,16)}function jR(n,e){let t=[],r=(s,o)=>JSON.stringify(bu(s))!==JSON.stringify(bu(o));for(let s of Object.keys(e)){let o=ry(s),i=e[s],a=n[s];if(o.nested){for(let d of Object.keys(i??{})){if(sy(d).reload!=="warn")continue;let c=i[d],l=(a??{})[d];r(l,c)&&t.push(`${s}.${d}`)}continue}o.reload==="warn"&&r(a,i)&&t.push(s)}return t}var Rc=q(()=>{"use strict";rt();iy()});function vb(n){return Math.floor(n/4)}function nA(n){let e=0,t=new Map;for(let r of n){let s=r.params;if(!s||typeof s!="object")continue;let o=s.update;if(!o||typeof o!="object")continue;let i=o;switch(i.sessionUpdate){case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":e+=va(i.content);break;case"tool_call":case"tool_call_update":{let a=typeof i.toolCallId=="string"?i.toolCallId:"",d=DD(i),c=t.get(a)??0;d>c&&t.set(a,d);break}default:break}}for(let r of t.values())e+=r;return e}function DD(n){let e=0;return typeof n.title=="string"&&(e+=n.title.length),e+=Sh(n.rawInput),e+=va(n.content),e+=Sh(n.rawOutput),e}function Sh(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(typeof n=="number"||typeof n=="boolean")return String(n).length;if(Array.isArray(n)){let e=0;for(let t of n)e+=Sh(t);return e}if(typeof n=="object"){let e=n.bytes;if(typeof n.__hydraBlob=="string"&&typeof e=="number")return e;let t=0;for(let r of Object.values(n))t+=Sh(r);return t}return 0}function va(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(Array.isArray(n)){let t=0;for(let r of n)t+=va(r);return t}if(typeof n!="object")return 0;let e=n;return typeof e.__hydraBlob=="string"&&typeof e.bytes=="number"?e.bytes:e.text!==void 0?va(e.text):e.type==="diff"?va(e.oldText)+va(e.newText):e.content!==void 0?va(e.content):0}function rA(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e,t;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize,t=!0;else{let s=vb(n.unsummarizedChars),o=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/o,t=!1}if(t&&e>=n.config.hardCeilingFraction)return!0;let r=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&r>=n.config.idleBeforePromptMs}function sA(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var Sb=q(()=>{"use strict"});function ku(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}function xb(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let r=t.parentToolUseId;return typeof r=="string"?r:void 0}var oA=q(()=>{"use strict"});import{posix as BD}from"path";import HD from"strip-ansi";function zt(n){return HD(n).replace(UD,"")}function ot(n){return zt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function js(n,e={}){if(!n||typeof n!="object")return null;let t=n,r=t.sessionUpdate??t.kind;if(typeof r!="string")return null;switch(r){case"agent_message_chunk":return GD(t);case"agent_thought_chunk":case"agent_thought":return JD(t);case"user_message_chunk":return VD(t);case"prompt_received":return YD(t);case"tool_call":return QD(t,e);case"tool_call_update":return nB(t,e);case"plan":return oB(t);case"current_mode_update":return iB(t);case"_hydra_current_model_update":return aB(t);case"turn_complete":return dB(t);case"_hydra_turn_started":return dA(t,"turn-started");case"_hydra_turn_ended":return dA(t,"turn-ended");case"usage_update":return KD(t);case"available_commands_update":return qD(t);case"_hydra_available_modes_update":return zD(t);case"session_info_update":return jD(t);case"config_option_update":return WD(t);default:return{kind:"unknown",sessionUpdate:r,raw:n}}}function WD(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||typeof s.currentValue!="string"||!Array.isArray(s.options))continue;let o=[];for(let i of s.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:s.id,name:typeof s.name=="string"?s.name:s.id,type:"select",currentValue:s.currentValue,options:o,...typeof s.category=="string"?{category:s.category}:{}})}return{kind:"config-options",options:t}}function jD(n){let e=qt(n,"title"),t=e!==void 0?ot(e):void 0,r=n._meta,s,o;if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(s=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&s===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),s!==void 0&&(i.agentId=s),o!==void 0&&(i.pendingAgentSwap=o),i}function xh(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.name!="string"||r.name.length===0)continue;let s=r.name.startsWith("/")?r.name:`/${r.name}`,o={name:ot(s)};typeof r.description=="string"&&(o.description=ot(r.description)),e.push(o)}return e}function qD(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:xh(e)}:null}function zD(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||s.id.length===0)continue;let o={id:ot(s.id)};typeof s.name=="string"&&(o.name=ot(s.name)),typeof s.description=="string"&&(o.description=ot(s.description)),t.push(o)}return{kind:"available-modes",modes:t}}function KD(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 GD(n){let e=vu(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ku(n)}}function JD(n){let e=typeof n.text=="string"?zt(n.text):vu(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ku(n)}}function VD(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e["hydra-acp"];if(r&&typeof r=="object"&&!Array.isArray(r)&&r.compatFor==="prompt_received")return null}let t=vu(n.content);return t===null?null:{kind:"user-text",text:t}}function YD(n){let e=cB(n.prompt);return e===null?null:{kind:"user-text",text:e}}function cA(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function iA(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 Ih(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(s.type!=="diff")continue;let o=iA(s.oldText),i=iA(s.newText);if(o===void 0&&i===void 0)continue;let a=typeof s.path=="string"?s.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t,s=typeof r.file_path=="string"?r.file_path:typeof r.path=="string"?r.path:void 0;if(typeof r.old_string=="string"&&typeof r.new_string=="string")return{...s!==void 0?{path:s}:{},oldText:r.old_string,newText:r.new_string};if(typeof r.content=="string")return{...s!==void 0?{path:s}:{},oldText:"",newText:r.content}}return null}function lA(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:zt(t)}function QD(n,e={}){let t=qt(n,"toolCallId")??qt(n,"id");if(!t)return null;let r=qt(n,"title")??qt(n,"name")??qt(n,"label")??"tool call",s=qt(n,"name")??qt(n,"title");if(cA(s)){let h=lA(n);if(h!==null){let g=qt(n,"status"),w={kind:"exit-plan-mode",toolCallId:t,plan:h};return g!==void 0&&(w.status=g),w}}let o=pA(ot(r),n,e),i=qt(n,"status"),a=qt(n,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=Ih(n);c!==null&&(d.editDiff=c);let l=fA(n);l!==void 0&&(d.detail=l);let u=Ib(n);u!==void 0&&(d.detailFull=u);let f=uA(n);f!==void 0&&(d.locations=f);let p=ku(n);p!==void 0&&(d.workerTaskId=p);let m=xb(n);return m!==void 0&&(d.parentToolUseId=m),d}function uA(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.path!="string"||s.path.length===0)continue;let o={path:s.path};typeof s.line=="number"&&Number.isFinite(s.line)&&s.line>=1&&(o.line=Math.floor(s.line)),t.push(o)}return t.length>0?t:void 0}function fA(n){let e=Ib(n);if(e===void 0)return;let t=ot(e),r=n.rawInput;return r&&typeof r.command=="string"?eB(t,aA):tB(t,aA)}function Ib(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 zt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let r=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(r!==void 0&&r.length>0)return V(ot(r))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let r=t.path;if(typeof r=="string"&&r.length>0)return V(ot(r))}}}function ZD(n){for(let e of XD)if(n.startsWith(e))return!0;return!1}function pA(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return V(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let r=e.rawInput;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=[s.file_path,s.filePath,s.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return V(i)}return ZD(n)?V(`/${n}`):t.cwd&&t.cwd.length>0?V(BD.resolve(t.cwd,n)):n}function eB(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function tB(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),r=t.indexOf("/");return r>=0&&r<e/2?`\u2026${t.slice(r)}`:`\u2026${t}`}function nB(n,e={}){let t=qt(n,"toolCallId")??qt(n,"id");if(!t)return null;let r=qt(n,"title"),s=r!==void 0?pA(ot(r),n,e):void 0,o=qt(n,"status"),i=Ih(n),a=fA(n),d=Cb(n);if(!(s!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let l=qt(n,"name")??r;if(cA(l)){let g={kind:"exit-plan-mode",toolCallId:t},w=lA(n);return w!==null&&(g.plan=w),o!==void 0&&(g.status=o),g}let u={kind:"tool-call-update",toolCallId:t};s!==void 0&&(u.title=s),a!==void 0&&(u.detail=a);let f=Ib(n);f!==void 0&&(u.detailFull=f);let p=uA(n);if(p!==void 0&&(u.locations=p),d!==void 0&&(u.resultSummary=d),o!==void 0&&(u.status=o),i!==null&&(u.editDiff=i),o==="failed"){let g=rB(n);g!==null&&(u.errorText=g),sB(n,g)&&(u.upstreamInterrupted=!0)}let m=ku(n);m!==void 0&&(u.workerTaskId=m);let h=xb(n);return h!==void 0&&(u.parentToolUseId=h),u}function Cb(n){if(!n||typeof n!="object")return;let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r=l=>{let u=t[l];return typeof u=="number"&&Number.isFinite(u)?u:void 0},s=(l,u,f=`${u}s`)=>`${l} ${l===1?u:f}`,o=[],i=r("totalMatches");i!==void 0&&o.push(s(i,"match","matches"));let a=r("totalFiles");a!==void 0&&o.push(s(a,"file"));let d=r("referenceCount");d!==void 0&&o.push(s(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let c=r("exitCode");return c!==void 0&&c!==0&&o.push(`exit ${c}`),o.length>0?o.join(", "):void 0}function hA(n){if(!n||typeof n!="object")return[];let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e,r=[];for(let s of["content","stdout","stderr"]){let o=t[s];typeof o=="string"?o.length>0&&r.push(o):o&&typeof o=="object"&&!Array.isArray(o)&&r.push(o)}return r}function rB(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=vu(r.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"&&r.length>0)return zt(r)}return null}function sB(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.metadata;if(r&&typeof r=="object"&&r.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function oB(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r,o=typeof s.content=="string"?ot(s.content):void 0;if(!o)continue;let i={content:o};typeof s.status=="string"&&(i.status=s.status),typeof s.priority=="string"&&(i.priority=s.priority),t.push(i)}return{kind:"plan",entries:t}}function iB(n){let e=qt(n,"currentModeId")??qt(n,"currentMode")??qt(n,"mode");return e?{kind:"mode-changed",mode:ot(e)}:null}function aB(n){let e=qt(n,"currentModel")??qt(n,"model");if(!e)return null;let t=n.availableModels,r=Array.isArray(t)?t.map(s=>typeof s=="object"&&s!==null?s.modelId:typeof s=="string"?s:void 0).filter(s=>typeof s=="string"&&s.length>0):void 0;return{kind:"model-changed",model:ot(e),...r&&r.length>0?{availableModels:r}:{}}}function dB(n){let e=qt(n,"stopReason"),t=n._meta,r=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,s={kind:"turn-complete"};return e!==void 0&&(s.stopReason=e),r&&(s.amended=!0),s}function dA(n,e){let r=n._meta?.["hydra-acp"],s=r?.unsolicited===!0;if(e==="turn-started"){let i=r?.cause?.label,a={kind:e,unsolicited:s};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:s};return typeof r?.reason=="string"&&(o.reason=r.reason),o}function vu(n){if(typeof n=="string")return zt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?zt(e.text):null}function cB(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let r=vu(t);r!==null&&e.push(r)}return e.length===0?null:e.join("")}function qt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var UD,aA,XD,Io=q(()=>{"use strict";ke();oA();UD=/[\x00-\x08\x0b-\x1f\x7f]/g;aA=64;XD=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Ac(n){let e=new Map,t=new Map;for(let s of n){let i=s.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=uB(i);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(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)lB(t,u)}let r=[];for(let[s,o]of t)r.push({path:s,hunks:o.hunks,created:o.created});return r}function Tc(n){let e=[];for(let t of n){let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){r=o;break}if(r===-1){e.push(t);continue}let s=e[r];e.splice(r,1,{oldText:s.oldText,newText:t.newText})}return e}function lB(n,e){let t={oldText:e.oldText,newText:e.newText},r=n.get(e.path);if(r===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}r.hunks.push(t)}function uB(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==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:i,oldText:l,newText:u})}if(e.length>0)return e}}let r=n.content;if(Array.isArray(r)){for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let d=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let s=Ih(n);return s&&s.path&&e.push({path:s.path,oldText:s.oldText,newText:s.newText}),e}var Ch=q(()=>{"use strict";Io()});function SB(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,r=[],s;for(;(s=t.exec(e))!==null;)r.push(s[0]);let o="OR",i=!1,a=!1,d=[];for(let l of r){let u=l.toUpperCase();u==="AND"?i=!0:u==="OR"?a=!0:d.push(l)}i?o="AND":a&&(o="OR");let c=d.map(l=>xB(l)).filter(l=>l.term.length>0);return{operator:o,terms:c}}function xB(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:yA(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let r=/^(prompt|response|tool|edit|edited):([\s\S]*)$/i.exec(n);return r?{scope:yA(r[1]),term:r[2].trim()}:{scope:"all",term:n.trim()}}function yA(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";case"edit":case"edited":return"edit";default:return"all"}}function IB(n,e){return e==="edit"?n==="edit":n==="edit"?!1:n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}function SA(n){return Number.isFinite(n)?Math.max(AB,Math.min(TB,Math.floor(n))):Th}async function xA(n,e,t={}){let r=SB(e);if(r.terms.length===0)return{query:e,truncated:!1,results:[]};let s=t.maxSnippetsPerSession??CB,o=t.maxSessions??RB,i=SA(t.snippetWidth??Th),a=t.sessionIds?new Set(t.sessionIds):null,d=await n.list(),c=a?d.filter(f=>a.has(f.sessionId)):d,l=[],u=!1;for(let f of c){if(l.length>=o){u=!0;break}let p=await n.loadHistory(f.sessionId,{tools:"references"}).catch(()=>[]),m=EB(p,r,s,i,Ec(f));if(m.snippets.length===0)continue;let h={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:m.totalMatches,snippets:m.snippets};f.title!==void 0&&(h.title=f.title),l.push(h)}return{query:e,truncated:u,results:l}}function Ec(n){let e=n.workspace?.sourceCwd;if(e===void 0||e.length===0||n.cwd.length===0)return;let t=n.cwd.endsWith("/")?n.cwd:n.cwd+"/";return r=>r.startsWith(t)?e.replace(/\/+$/,"")+"/"+r.slice(t.length):r}function EB(n,e,t,r=Th,s){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let o=0,i=[],a=Math.max(1,Math.floor(t/e.terms.length)),d=[];for(let{scope:c,term:l}of e.terms){let u=PB(n,l,c,t,r,s);if(e.operator==="AND"&&u.totalMatches===0)return{totalMatches:0,snippets:[]};o+=u.totalMatches,i.push(...u.snippets.slice(0,a)),d.push(...u.snippets.slice(a))}for(let c of d){if(i.length>=t)break;i.push(c)}return{totalMatches:o,snippets:i.slice(0,t)}}function PB(n,e,t,r,s,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let l of n){let u=MB(l).filter(f=>IB(t,f.kind));for(let f of u){let p=f.text.toLowerCase();if(f.kind==="edit"){let g=o?.(f.text);if(!(wA(f.text,e)||(g!==void 0&&g!==f.text?wA(g,e):!1))||c.has(f.text))continue;if(c.add(f.text),a+=1,d.length<r){let b={kind:"edit",text:f.text,recordedAt:l.recordedAt};f.toolName!==void 0&&(b.toolName=f.toolName),d.push(b)}continue}let m=p.indexOf(i);if(m===-1)continue;let h=0;for(;m!==-1;)h++,m=p.indexOf(i,m+i.length);if(a+=h,d.length<r){let g=p.indexOf(i),w={kind:f.kind,text:DB(f.text,g,i.length,s),recordedAt:l.recordedAt};f.toolName!==void 0&&(w.toolName=f.toolName),d.push(w)}}}return{totalMatches:a,snippets:d}}function MB(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 r=t,s=typeof r.sessionUpdate=="string"?r.sessionUpdate:r.kind;if(typeof s!="string")return[];switch(s){case"agent_message_chunk":{let o=Ah(r.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof r.text=="string"?zt(r.text):Ah(r.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(LB(r))return[];let o=Ah(r.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=NB(r.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return _B(r);default:return[]}}function _B(n){let e=kA(n,"name"),t=kA(n,"title"),r=[];if(t!==void 0){let a=ot(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),r.push(d)}}if(e!==void 0&&e!==t){let a=ot(e);a.length>0&&r.push({kind:"tool",toolName:e,text:a})}let s=n.rawInput;if(s&&typeof s=="object"){let a=vA(s);if(a.length>0){let d={kind:"tool-input",text:ot(a)};e!==void 0&&(d.toolName=e),r.push(d)}}for(let a of $B(n)){let d={kind:"edit",text:a};e!==void 0&&(d.toolName=e),r.push(d)}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=vA(o);if(a.length>0){let d={kind:"tool-input",text:ot(a)};e!==void 0&&(d.toolName=e),r.push(d)}}let i=OB(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),r.push(a)}return r}function $B(n){let e=[],t=new Set,r=i=>{typeof i!="string"||i.length===0||t.has(i)||(t.add(i),e.push(i))},s=n.content;if(Array.isArray(s))for(let i of s){if(!i||typeof i!="object")continue;let a=i;a.type==="diff"&&r(a.path)}let o=n.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o;(i.old_string!==void 0||i.new_string!==void 0||i.content!==void 0||Array.isArray(i.edits))&&r(typeof i.file_path=="string"?i.file_path:i.path)}return e}function wA(n,e){let t=bA(n.toLowerCase()),r=bA(e.toLowerCase());if(r.length===0)return!1;if(r.startsWith("/"))return t===r||t.startsWith(r+"/");let s="/"+r,o=t.indexOf(s);for(;o!==-1;){let i=o+s.length;if(i===t.length||t[i]==="/")return!0;o=t.indexOf(s,o+1)}return t===r||t.startsWith(r+"/")}function bA(n){return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function OB(n){if(!FB(n.status))return null;let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=r.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=ot(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"){let s=ot(r);if(s.length>0)return s}}return null}function FB(n){return n==="failed"||n==="rejected"||n==="cancelled"}function LB(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 Ah(n){if(typeof n=="string")return zt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?zt(e.text):""}function NB(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let r=Ah(t);r.length>0&&e.push(r)}return e.join("")}function kA(n,e){let t=n[e];return typeof t=="string"?t:void 0}function vA(n){try{return JSON.stringify(n)}catch{return""}}function DB(n,e,t,r=Th){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let o=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),a=i.length>0?o.indexOf(i):0;a===-1&&(a=0);let d=SA(r),c=Math.max(0,d-i.length),l=Math.floor(c/2),u=Math.min(l,a),f=Math.min(c-u,s.length-(a+i.length)),p=Math.max(0,a-(c-f)),m=Math.min(s.length,a+i.length+f),h=p>0?"\u2026":"",g=m<s.length?"\u2026":"";return`${h}${s.slice(p,m)}${g}`}var CB,RB,Th,AB,TB,Eh=q(()=>{"use strict";Io();CB=5,RB=200,Th=72,AB=24,TB=512});function Rr(n){let e=[],t=[],r=!1,s=o=>{if(!r){r=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.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:G.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>s()),n.on("error",o=>s(o)),{async send(o){if(r)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{n.send(i,c=>{if(c){d(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){r||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(d),o())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),s())}}}var Sa=q(()=>{"use strict";fn()});import*as Ia from"fs/promises";import*as sU from"path";async function ST(n,e=20){let t=D.daemonBootLog();try{if((await Ia.stat(t)).mtimeMs<n-1e3)return;let i=(await Ia.readFile(t,"utf8")).trimEnd().split(`
|
|
128
128
|
`).slice(-e).join(`
|
|
129
129
|
`);return i.length>0?i:void 0}catch{return}}var fX,xT=q(()=>{"use strict";ke();fX=64*1024});import{spawn as oU}from"child_process";import{dirname as iU,resolve as aU}from"path";import{fileURLToPath as dU}from"url";import{setTimeout as IT}from"timers/promises";async function CT(){let n=await Es();if(n&&kr(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function cU(n){let e=await Ca(n,500);return e?e.home!==void 0&&!ny(e.home,D.home())||e.configDigest===void 0?"mismatch":e.configDigest===ci(n)?"match":"mismatch":"missing"}async function hi(n,e){let t=await cU(n);if(t==="mismatch"){let r=Nn();throw new Error(`config changed since daemon started \u2014 run \`${r} daemon restart\` to apply.`)}if(t==="missing"&&(process.stderr.write(`hydra-acp: daemon not running; starting it...
|
|
130
130
|
`),Kh(n),await Gh(n)),e!==void 0){let r=await Es();if(r&&kr(r.pid)){let s=`http://127.0.0.1:${r.loopbackPort}`;e.baseUrl=s,e.wsUrl=`ws://127.0.0.1:${r.loopbackPort}/acp`}await uU(`${e.baseUrl}/v1/health`)}}async function zh(n){let e=await CT();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Ca(n,e=1e3){let t=await CT();if(t)try{let r=await fetch(t,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!r.ok)return;let s=await r.json();return{version:typeof s.version=="string"?s.version:void 0,configDigest:typeof s.configDigest=="string"?s.configDigest:void 0,home:typeof s.home=="string"?s.home:void 0,driftedKeys:Array.isArray(s.driftedKeys)?s.driftedKeys.filter(o=>typeof o=="string"):void 0}}catch{return}}function Kh(n){let e=iU(dU(import.meta.url)),t=aU(e,"./daemon.js");n&&Ul(n.daemon.scrubEnv),oU(process.execPath,[t],{detached:!0,stdio:"ignore",windowsHide:!0,env:tc()}).unref()}async function lU(n,e=500){try{return(await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}})).ok}catch{return!1}}async function uU(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await lU(n))return;await IT(150)}throw new Error(`hydra-acp daemon did not answer ${n} within ${e}ms`)}async function Gh(n,e=15e3){let t=Date.now(),r=t+e;for(;Date.now()<r;){if(await zh(n))return;await IT(150)}let s=await ST(t),o=await fU(n);throw new Error(`hydra-acp daemon did not become ready within ${e}ms`+(s?`
|
|
@@ -143,7 +143,7 @@ That is why the daemon started here could not bind. Point both at the same absol
|
|
|
143
143
|
`)||process.stdout.write(`
|
|
144
144
|
`)}finally{await s.close()}return e}function Jh(n){let e=new Set(["--tail","-n"]),t,r=[],s=0;for(;s<n.length;){let o=n[s];if(o===void 0)break;if(o.startsWith("-")){if(r.push(o),e.has(o)&&s+1<n.length){let i=n[s+1];i!==void 0&&r.push(i),s+=2;continue}s+=1;continue}if(t===void 0){t=o,s+=1;continue}r.push(o),s+=1}return{name:t,rest:r}}function hU(n){let e=50,t=!1,r=0;for(;r<n.length;){let s=n[r];if(s==="--tail"||s==="-n"){let o=n[r+1],i=Number.parseInt(o??"",10);(!Number.isInteger(i)||i<0)&&(process.stderr.write(`Invalid --tail value: ${o}
|
|
145
145
|
`),process.exit(2)),e=i,r+=2;continue}if(s==="--follow"||s==="-f"){t=!0,r+=1;continue}return process.stderr.write(`Unknown flag: ${s}
|
|
146
|
-
`),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var Ru=q(()=>{"use strict";ch()});async function lr(n,e={},t=8e3,r=fetch){let s=new AbortController,o=e.signal??void 0;o&&(o.aborted?s.abort(o.reason):o.addEventListener("abort",()=>s.abort(o.reason),{once:!0}));let i=!1,a=setTimeout(()=>{i=!0,s.abort()},t);try{return await r(n,{...e,signal:s.signal})}catch(d){throw i?new Nb(n,t):d}finally{clearTimeout(a)}}async function Db(n,e={},t=fetch){let r=new URL(`${n.baseUrl}/v1/sessions`);e.cwd&&r.searchParams.set("cwd",e.cwd),e.all&&r.searchParams.set("all","true"),e.includeNonInteractive&&r.searchParams.set("includeNonInteractive","true"),e.status&&r.searchParams.set("status",e.status),e.since!==void 0&&r.searchParams.set("since",String(e.since));let s=await lr(r.toString(),{headers:{Authorization:`Bearer ${n.token}`},signal:e.signal},8e3,t);if(!s.ok)throw new Error(`daemon returned HTTP ${s.status}`);let o=await s.json();return{sessions:Array.isArray(o.sessions)?o.sessions.map(a=>({sessionId:a.sessionId,cwd:a.cwd,workspace:a.workspace,workspaceError:a.workspaceError,updatedAt:a.updatedAt,attachedClients:a.attachedClients??0,status:a.status??"warm",upstreamSessionId:a.upstreamSessionId,agentId:a.agentId,currentModel:a.currentModel,currentUsage:a.currentUsage,title:a.title,importedFromMachine:a.importedFromMachine,importedFromUpstreamSessionId:a.importedFromUpstreamSessionId,remote:a.remote,forkedFromSessionId:a.forkedFromSessionId,forkedFromMessageId:a.forkedFromMessageId,busy:a.busy,awaitingInput:a.awaitingInput,armedTasks:a.armedTasks,originatingClient:a.originatingClient,interactive:a.interactive,priority:a.priority,compactionState:a.compactionState,forkSynthesisState:a.forkSynthesisState})):[],removed:Array.isArray(o.removed)?o.removed:[],cursor:typeof o.cursor=="number"?o.cursor:0}}async function Ks(n,e={},t=fetch){return(await Db(n,e,t)).sessions}function _T(n,e,t){if(!t)return e.sessions;let r=new Map(n.map(s=>[s.sessionId,s]));for(let s of r.values())s.status!=="cold"&&r.delete(s.sessionId);for(let s of e.removed)r.delete(s);for(let s of e.sessions)r.set(s.sessionId,s);return[...r.values()]}async function $T(n,e=fetch){let t=await lr(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let r=await t.json(),s=Array.isArray(r.agents)?r.agents.filter(d=>d.installed==="yes"):[],o=0,i=0,a=0;for(let d of s)try{let c=await lr(`${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();o+=Array.isArray(l.synced)?l.synced.length:0,i+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:o,skipped:i,agents:a}}async function Aa(n,e=fetch){let t=await lr(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let r=await t.json();return Array.isArray(r.agents)?r.agents.map(s=>({id:s.id,name:s.name,description:s.description,...s.extendsChain?{extendsChain:s.extendsChain}:{},...s.onboarding?{onboarding:s.onboarding}:{}})):[]}async function Vh(n,e,t={},r=fetch){let s=await lr(`${n.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)},18e4,r);if(!s.ok){let o="";try{let i=await s.json();typeof i.error=="string"&&(o=`: ${i.error}`)}catch{}throw new Error(`fork failed (HTTP ${s.status})${o}`)}return await s.json()}async function Gs(n,e,t=fetch){let r=await lr(`${n.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Au(n,e,t,r=fetch){let s=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:t})},8e3,r);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function OT(n,e,t,r=fetch){let s=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:t})},8e3,r);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function FT(n,e,t=fetch){let r=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,t);if(!r.ok&&r.status!==202&&r.status!==204&&r.status!==404&&r.status!==409)throw new Error(`daemon returned HTTP ${r.status}`)}async function LT(n,e,t={},r=fetch){let s={q:e};t.sessionIds&&t.sessionIds.length>0&&(s.sessionIds=t.sessionIds),t.snippetWidth!==void 0&&(s.snippetWidth=t.snippetWidth);let o=await lr(`${n.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)},2e4,r);if(!o.ok)throw new Error(`daemon returned HTTP ${o.status}`);return await o.json()}async function NT(n,e,t=fetch){let r=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}function Yh(n,e){let t=n.filter(o=>o.cwd===e);if(t.length===0)return null;let r=o=>o.status==="warm"?1:0;return[...t].sort((o,i)=>{let a=r(i)-r(o);return a!==0?a:i.updatedAt.localeCompare(o.updatedAt)})[0]??null}var Nb,Tu=q(()=>{"use strict";Nb=class extends Error{constructor(t,r){super(`daemon did not respond within ${r}ms (${t})`);this.url=t;this.timeoutMs=r;this.name="DaemonTimeoutError"}url;timeoutMs}});function Bb(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function DT(n,e){let t=n??"?",r=Bb(e);return r?`${t}${yU}${r}`:t}function BT(n){return n??"?"}function HT(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:Qh(e,t)}function Qh(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var yU,Hb=q(()=>{"use strict";yU="\u2022"});function Wb(n){let e=n.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(e.length===0)throw new Error("--columns: no column names given");let t=new Set,r=[];for(let s of e){if(!Zh.includes(s))throw new Error(`--columns: unknown column "${s}" (valid: ${Zh.join(", ")})`);if(t.has(s))throw new Error(`--columns: duplicate column "${s}"`);t.add(s),r.push(s)}return r}function bU(n){return n.workspace!==void 0?V(n.workspace.sourceCwd):n.workspaceError!==void 0?`${V(n.cwd)} !not-isolated`:V(n.cwd)}function ds(n,e=Date.now()){return{session:st(n.sessionId),upstream:vU(n.upstreamSessionId,n.remote??n.importedFromMachine),host:n.remote??n.importedFromMachine??"-",state:SU(n.status,n.busy,n.awaitingInput,kU(n.compactionState),n.forkSynthesisState,n.armedTasks),agent:BT(n.agentId),model:Bb(n.currentModel)??"-",age:xU(n.updatedAt,e),title:n.title??"-",cwd:bU(n),cost:HT(n.currentUsage)}}function kU(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 vU(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function SU(n,e,t,r,s,o){if(n==="cold")return"COLD";let i=e||(o??0)>0?"BUSY":"WARM",a=s==="failed"?"\u26A0":"";return t?`${i}\u25E6${a}`:s==="running"?`${i}\u2728`:a?`${i}${a}`:r?`${i}\u27F3`:i}function Js(n,e={}){let t=e.columns??mi,r={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let s of t)r[s]=IU(Co[s],n.map(o=>o[s]));return r}function xU(n,e){if(!n)return"?";let t=Date.parse(n);if(Number.isNaN(t))return"?";let r=Math.max(0,e-t),s=Math.floor(r/1e3);if(s<60)return"<1m";let o=Math.floor(s/60);if(o<60)return`${o}m`;let i=Math.floor(o/60);if(i<24)return`${i}h`;let a=Math.floor(i/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 IU(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}function ur(n,e,t,r={}){let s=r.columns??mi,o=r.cwdMaxWidth??wU,i=b=>b==="age"?n[b].padStart(e[b]):n[b].padEnd(e[b]);if(t===void 0)return s.map((k,S)=>S===s.length-1?n[k]:i(k)).join(Xh);let a=s.map((b,k)=>({col:b,i:k})).filter(({col:b})=>Ub.has(b)),d=a.length>0?a[a.length-1].i:-1;if(d===-1){let b=s.map(i).join(Xh);return b.length>t?b.slice(0,t):b}let c=s.filter(b=>!Ub.has(b)).reduce((b,k)=>b+e[k],0),l=Math.max(0,s.length-1),u=t-c-l*Xh.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:k}of a){if(k===d)continue;let S=b==="cwd"?Math.min(e[b],o):e[b],I=Math.min(S,Math.max(0,p-1));f.set(k,I),p=Math.max(0,p-I)}f.set(d,Math.max(0,p));let m=s.length-1,h=(b,k,S)=>{if(b==="cwd")return Eu(n[b],k).padEnd(k);let I=CU(n[b],k);return S?I:I.padEnd(k)},w=s.map((b,k)=>Ub.has(b)?h(b,f.get(k)??0,k===m):i(b)).join(Xh);return w.length>t?w.slice(0,t):w}function CU(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function Eu(n,e){if(e<=0)return"";if(n.length<=e)return n;if(e===1)return"\u2026";let t=Math.ceil((e-1)/2),r=e-1-t;return n.slice(0,t)+"\u2026"+n.slice(n.length-r)}var Zh,mi,Ub,Co,Xh,wU,Nc=q(()=>{"use strict";Hb();ke();ir();Zh=["session","upstream","host","state","agent","model","age","cwd","title","cost"],mi=["session","state","age","cwd","title","agent","cost"],Ub=new Set(["cwd","title"]),Co={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Xh=" ",wU=32});import{spawn as GU}from"child_process";import{Writable as JU}from"stream";function rm(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,r=VU(t,n.platform??process.platform);if(r===null)return{stream:process.stdout,flush:async()=>{}};let s=n.spawn??GU,o={...t};o.LESS===void 0&&(o.LESS="FRX");let i=s(r,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:o,windowsHide:!0}),a=i.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
|
|
146
|
+
`),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var Ru=q(()=>{"use strict";ch()});async function lr(n,e={},t=8e3,r=fetch){let s=new AbortController,o=e.signal??void 0;o&&(o.aborted?s.abort(o.reason):o.addEventListener("abort",()=>s.abort(o.reason),{once:!0}));let i=!1,a=setTimeout(()=>{i=!0,s.abort()},t);try{return await r(n,{...e,signal:s.signal})}catch(d){throw i?new Nb(n,t):d}finally{clearTimeout(a)}}async function Db(n,e={},t=fetch){let r=new URL(`${n.baseUrl}/v1/sessions`);e.cwd&&r.searchParams.set("cwd",e.cwd),e.all&&r.searchParams.set("all","true"),e.includeNonInteractive&&r.searchParams.set("includeNonInteractive","true"),e.status&&r.searchParams.set("status",e.status),e.since!==void 0&&r.searchParams.set("since",String(e.since));let s=await lr(r.toString(),{headers:{Authorization:`Bearer ${n.token}`},signal:e.signal},8e3,t);if(!s.ok)throw new Error(`daemon returned HTTP ${s.status}`);let o=await s.json();return{sessions:Array.isArray(o.sessions)?o.sessions.map(a=>({sessionId:a.sessionId,cwd:a.cwd,workspace:a.workspace,workspaceError:a.workspaceError,updatedAt:a.updatedAt,attachedClients:a.attachedClients??0,status:a.status??"warm",upstreamSessionId:a.upstreamSessionId,agentId:a.agentId,currentModel:a.currentModel,currentUsage:a.currentUsage,title:a.title,importedFromMachine:a.importedFromMachine,importedFromUpstreamSessionId:a.importedFromUpstreamSessionId,remote:a.remote,forkedFromSessionId:a.forkedFromSessionId,forkedFromMessageId:a.forkedFromMessageId,busy:a.busy,awaitingInput:a.awaitingInput,armedTasks:a.armedTasks,originatingClient:a.originatingClient,interactive:a.interactive,priority:a.priority,compactionState:a.compactionState,forkSynthesisState:a.forkSynthesisState})):[],removed:Array.isArray(o.removed)?o.removed:[],cursor:typeof o.cursor=="number"?o.cursor:0}}async function Gs(n,e={},t=fetch){return(await Db(n,e,t)).sessions}function _T(n,e,t){if(!t)return e.sessions;let r=new Map(n.map(s=>[s.sessionId,s]));for(let s of r.values())s.status!=="cold"&&r.delete(s.sessionId);for(let s of e.removed)r.delete(s);for(let s of e.sessions)r.set(s.sessionId,s);return[...r.values()]}async function $T(n,e=fetch){let t=await lr(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let r=await t.json(),s=Array.isArray(r.agents)?r.agents.filter(d=>d.installed==="yes"):[],o=0,i=0,a=0;for(let d of s)try{let c=await lr(`${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();o+=Array.isArray(l.synced)?l.synced.length:0,i+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:o,skipped:i,agents:a}}async function Aa(n,e=fetch){let t=await lr(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let r=await t.json();return Array.isArray(r.agents)?r.agents.map(s=>({id:s.id,name:s.name,description:s.description,...s.extendsChain?{extendsChain:s.extendsChain}:{},...s.onboarding?{onboarding:s.onboarding}:{}})):[]}async function Vh(n,e,t={},r=fetch){let s=await lr(`${n.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)},18e4,r);if(!s.ok){let o="";try{let i=await s.json();typeof i.error=="string"&&(o=`: ${i.error}`)}catch{}throw new Error(`fork failed (HTTP ${s.status})${o}`)}return await s.json()}async function Js(n,e,t=fetch){let r=await lr(`${n.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Au(n,e,t,r=fetch){let s=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:t})},8e3,r);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function OT(n,e,t,r=fetch){let s=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:t})},8e3,r);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function FT(n,e,t=fetch){let r=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,t);if(!r.ok&&r.status!==202&&r.status!==204&&r.status!==404&&r.status!==409)throw new Error(`daemon returned HTTP ${r.status}`)}async function LT(n,e,t={},r=fetch){let s={q:e};t.sessionIds&&t.sessionIds.length>0&&(s.sessionIds=t.sessionIds),t.snippetWidth!==void 0&&(s.snippetWidth=t.snippetWidth);let o=await lr(`${n.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)},2e4,r);if(!o.ok)throw new Error(`daemon returned HTTP ${o.status}`);return await o.json()}async function NT(n,e,t=fetch){let r=await lr(`${n.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}function Yh(n,e){let t=n.filter(o=>o.cwd===e);if(t.length===0)return null;let r=o=>o.status==="warm"?1:0;return[...t].sort((o,i)=>{let a=r(i)-r(o);return a!==0?a:i.updatedAt.localeCompare(o.updatedAt)})[0]??null}var Nb,Tu=q(()=>{"use strict";Nb=class extends Error{constructor(t,r){super(`daemon did not respond within ${r}ms (${t})`);this.url=t;this.timeoutMs=r;this.name="DaemonTimeoutError"}url;timeoutMs}});function Bb(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function DT(n,e){let t=n??"?",r=Bb(e);return r?`${t}${yU}${r}`:t}function BT(n){return n??"?"}function HT(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:Qh(e,t)}function Qh(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var yU,Hb=q(()=>{"use strict";yU="\u2022"});function Wb(n){let e=n.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(e.length===0)throw new Error("--columns: no column names given");let t=new Set,r=[];for(let s of e){if(!Zh.includes(s))throw new Error(`--columns: unknown column "${s}" (valid: ${Zh.join(", ")})`);if(t.has(s))throw new Error(`--columns: duplicate column "${s}"`);t.add(s),r.push(s)}return r}function bU(n){return n.workspace!==void 0?V(n.workspace.sourceCwd):n.workspaceError!==void 0?`${V(n.cwd)} !not-isolated`:V(n.cwd)}function ds(n,e=Date.now()){return{session:st(n.sessionId),upstream:vU(n.upstreamSessionId,n.remote??n.importedFromMachine),host:n.remote??n.importedFromMachine??"-",state:SU(n.status,n.busy,n.awaitingInput,kU(n.compactionState),n.forkSynthesisState,n.armedTasks),agent:BT(n.agentId),model:Bb(n.currentModel)??"-",age:xU(n.updatedAt,e),title:n.title??"-",cwd:bU(n),cost:HT(n.currentUsage)}}function kU(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 vU(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function SU(n,e,t,r,s,o){if(n==="cold")return"COLD";let i=e||(o??0)>0?"BUSY":"WARM",a=s==="failed"?"\u26A0":"";return t?`${i}\u25E6${a}`:s==="running"?`${i}\u2728`:a?`${i}${a}`:r?`${i}\u27F3`:i}function Vs(n,e={}){let t=e.columns??mi,r={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let s of t)r[s]=IU(Co[s],n.map(o=>o[s]));return r}function xU(n,e){if(!n)return"?";let t=Date.parse(n);if(Number.isNaN(t))return"?";let r=Math.max(0,e-t),s=Math.floor(r/1e3);if(s<60)return"<1m";let o=Math.floor(s/60);if(o<60)return`${o}m`;let i=Math.floor(o/60);if(i<24)return`${i}h`;let a=Math.floor(i/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 IU(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}function ur(n,e,t,r={}){let s=r.columns??mi,o=r.cwdMaxWidth??wU,i=b=>b==="age"?n[b].padStart(e[b]):n[b].padEnd(e[b]);if(t===void 0)return s.map((k,S)=>S===s.length-1?n[k]:i(k)).join(Xh);let a=s.map((b,k)=>({col:b,i:k})).filter(({col:b})=>Ub.has(b)),d=a.length>0?a[a.length-1].i:-1;if(d===-1){let b=s.map(i).join(Xh);return b.length>t?b.slice(0,t):b}let c=s.filter(b=>!Ub.has(b)).reduce((b,k)=>b+e[k],0),l=Math.max(0,s.length-1),u=t-c-l*Xh.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:k}of a){if(k===d)continue;let S=b==="cwd"?Math.min(e[b],o):e[b],I=Math.min(S,Math.max(0,p-1));f.set(k,I),p=Math.max(0,p-I)}f.set(d,Math.max(0,p));let m=s.length-1,h=(b,k,S)=>{if(b==="cwd")return Eu(n[b],k).padEnd(k);let I=CU(n[b],k);return S?I:I.padEnd(k)},w=s.map((b,k)=>Ub.has(b)?h(b,f.get(k)??0,k===m):i(b)).join(Xh);return w.length>t?w.slice(0,t):w}function CU(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function Eu(n,e){if(e<=0)return"";if(n.length<=e)return n;if(e===1)return"\u2026";let t=Math.ceil((e-1)/2),r=e-1-t;return n.slice(0,t)+"\u2026"+n.slice(n.length-r)}var Zh,mi,Ub,Co,Xh,wU,Nc=q(()=>{"use strict";Hb();ke();ir();Zh=["session","upstream","host","state","agent","model","age","cwd","title","cost"],mi=["session","state","age","cwd","title","agent","cost"],Ub=new Set(["cwd","title"]),Co={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Xh=" ",wU=32});import{spawn as GU}from"child_process";import{Writable as JU}from"stream";function rm(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,r=VU(t,n.platform??process.platform);if(r===null)return{stream:process.stdout,flush:async()=>{}};let s=n.spawn??GU,o={...t};o.LESS===void 0&&(o.LESS="FRX");let i=s(r,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:o,windowsHide:!0}),a=i.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
|
|
147
147
|
`)});let d=new JU({write(l,u,f){if(!a.writable){f();return}a.write(l,m=>{if(m&&m.code!=="EPIPE"){f(m);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}
|
|
148
148
|
`)});let c=new Promise(l=>{i.once("exit",()=>l()),i.once("error",()=>l())});return{stream:d,flush:async()=>{a.writable&&await new Promise(l=>{d.end(()=>l())}),await c}}}function VU(n,e){let t=n.HYDRA_ACP_PAGER;if(t!==void 0)return t.length===0?null:t;let r=n.PAGER;return r!==void 0?r.length===0?null:r:e==="win32"?null:"less"}var Kb=q(()=>{"use strict"});import*as gi from"path";function Mu(n,e="list"){let t=o=>e==="diff"?o:V(o);if(n===void 0)return o=>o;let r=Ec({cwd:n.workspace?.path??n.cwd,...n.workspace!==void 0?{workspace:{sourceCwd:n.workspace.sourceCwd}}:{}})??(o=>o),s=QU(n.workspace?.sourceCwd??n.cwd);return o=>{let i=r(o);if(s.length===0)return t(i);let a=gi.relative(s,i);return a.length===0||a.startsWith("..")||gi.isAbsolute(a)?t(i):YU(a)}}function YU(n){return gi.sep==="\\"?n.split(gi.sep).join("/"):n}function QU(n){return n.length<=1?n:n.endsWith("/")||n.endsWith(gi.sep)?n.slice(0,-1):n}var Gb=q(()=>{"use strict";ke();Eh()});import{highlight as XU,supportsLanguage as sm}from"cli-highlight";import im from"string-width";function h0(n){let e=process.platform==="win32"?n.replace(/\\/g,"/"):n,t=/^([A-Za-z]):(\/.*)?$/.exec(e),r=t?`/${t[1]}:`:"",s=t?t[2]??"/":e;return r+s.split("/").map(o=>encodeURIComponent(o)).join("/")}function Vb(n){let e=n.indexOf("#"),t=e===-1?n:n.slice(0,e),r=e===-1?"":n.slice(e);return`file://${ZU}${h0(t)}${r}`}function m0(n){return`file://${h0(n)}`}function Ro(n,e={}){switch(n.kind){case"user-text":{let t=Jb(n.text,"\u258E ","user",void 0,n.sentBy,!0);if(n.attachments&&n.attachments.length>0)for(let r of n.attachments)t.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${r.name??"image"}`,bodyStyle:"user",fillRow:!0});return t}case"agent-text":return Jb(n.text," ","agent");case"agent-thought":return Jb(n.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return kW(n,e.maxPlanItems??wW);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"notice",body:`mode: ${n.mode}`,bodyStyle:"notice"}];case"model-changed":return[];case"turn-complete":return[];case"turn-started":return n.unsolicited?[{prefix:" ",body:n.cause?`agent resumed \xB7 ${n.cause}`:"agent resumed",bodyStyle:"muted"}]:[];case"turn-ended":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function Yb(n,e){return yi(n,e).styled}function yi(n,e,t){let r=e??Jx(),{codeOpen:s,linkOpen:o}=r,i=t??r.base,a=p=>ns+p,d="",c=0,l=!1,u=[],f=0;for(;f<n.length;){let p=n[f];if(p==="\\"&&f+1<n.length){let m=n[f+1];if(m==="*"||m==="_"||m==="`"||m==="["||m==="]"||m==="\\"){d+=m,c+=1,f+=2;continue}}if(p==="^"){d+="^",c+=1,f+=1;continue}if(p==="*"&&n[f+1]==="*"){let m=n.indexOf("**",f+2);if(m!==-1&&m>f+2){let h=n.slice(f+2,m),g=yi(h,r,i+Vy),w=c;d+=`${Vy}${g.styled}${a(i)}`;for(let b of g.links)u.push({start:w+b.start,end:w+b.end,url:b.url});c+=g.cleanLength,g.ansi&&(l=!0),f=m+2;continue}}if(p==="*"&&n[f+1]!=="*"){let m=f>0?n[f-1]:"",h=n[f+1]??"";if(h!==""&&h!==" "&&h!==" "&&h!==`
|
|
149
149
|
`&&!/[A-Za-z0-9]/.test(m)){let w=-1;for(let b=f+1;b<n.length;b++){let k=n[b];if(k===`
|
|
@@ -221,21 +221,21 @@ Synced ${r.synced.length} session(s); skipped ${r.skipped} already tracked.
|
|
|
221
221
|
`),process.exit(1);return}let r=Q0.join(D.agentsDir(),t,e),s=!1;try{await um.stat(r),s=!0}catch{}if(!s){process.stdout.write(`Nothing to remove: ${e} is not installed on ${t}.
|
|
222
222
|
`);return}await um.rm(r,{recursive:!0,force:!0}),process.stdout.write(`Uninstalled ${e} (${t}). Next session using it will re-install.
|
|
223
223
|
`)}async function mm(n){await gy(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.
|
|
224
|
-
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Eo(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}var gm=q(()=>{"use strict";rt();ke();oc();Ru();vr()});function we(n){DW(n)}var ym,Po,Wc,Fu,eE,tE,Lu,yk,wm,Ma,nE,_a,rE,$a,sE,Oa,jc,qc,oE,zc,iE,aE,dE,wk,cE,bm,km,Nu,lE,uE,NW,DW,Fa=q(()=>{"use strict";ym="\x1B[?2004h",Po="\x1B[?2004l",Wc="\x1B[200~",Fu="\x1B[201~",eE="\x1B[?1049l",tE="\x1B[H\x1B[J",Lu="\x1B[?7h",yk="\x1B[?7l",wm="\x1B[?25h",Ma="\x1B[?1l",nE="\x1B[>1u",_a="\x1B[<u",rE="\x1B[>4;2m",$a="\x1B[>4;0m",sE="\x1B[>5;1m",Oa="\x1B[>5;0m",jc="\x1B[?1000l",qc="\x1B[?1002l",oE="\x1B[?1003l",zc="\x1B[?1006l",iE="\x1B[?1015l",aE="\x1B[?w",dE="\x1B[=24;1w",wk="\x1B[=0;0w",cE="\x1B]22;pointer\x07",bm="\x1B]22;default\x07",km="\x1B[?1004h",Nu="\x1B[?1004l",lE="\x1B[?2026h",uE="\x1B[?2026l",NW=n=>{process.stdout.write(n)},DW=NW});function bk(n,e){let t=new Map;for(let[r,s,o]of n){let i=t.get(r);i||(i=new Map,t.set(r,i)),i.set(s,o)}return{chords:t,timeoutMs:e}}var wi,kk,vm,Du=q(()=>{"use strict";wi=class{constructor(e,t=Date.now){this.table=e;this.now=t}table;now;pending=null;get isArmed(){return this.pending!==null}clear(){this.pending=null}feed(e){if(this.pending){let{prefix:t,armedAt:r}=this.pending;this.pending=null;let o=this.now()-r<=this.table.timeoutMs?this.table.chords.get(t)?.get(e):void 0;return o!==void 0?{kind:"pass",token:o}:{kind:"aborted"}}return this.table.chords.has(e)?(this.pending={prefix:e,armedAt:this.now()},{kind:"armed"}):{kind:"pass",token:e}}};kk=1500,vm=bk([["CTRL_X","CTRL_E","CTRL_X_CTRL_E"]],kk)});function ls(){we(ns),we(_a),we(Po),we($a),we(Oa),we(jc),we(qc),we(zc),we(Ma),we("\x1B>")}function xn(n){return n.width??80}function
|
|
224
|
+
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Eo(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}var gm=q(()=>{"use strict";rt();ke();oc();Ru();vr()});function we(n){DW(n)}var ym,Po,Wc,Fu,eE,tE,Lu,yk,wm,Ma,nE,_a,rE,$a,sE,Oa,jc,qc,oE,zc,iE,aE,dE,wk,cE,bm,km,Nu,lE,uE,NW,DW,Fa=q(()=>{"use strict";ym="\x1B[?2004h",Po="\x1B[?2004l",Wc="\x1B[200~",Fu="\x1B[201~",eE="\x1B[?1049l",tE="\x1B[H\x1B[J",Lu="\x1B[?7h",yk="\x1B[?7l",wm="\x1B[?25h",Ma="\x1B[?1l",nE="\x1B[>1u",_a="\x1B[<u",rE="\x1B[>4;2m",$a="\x1B[>4;0m",sE="\x1B[>5;1m",Oa="\x1B[>5;0m",jc="\x1B[?1000l",qc="\x1B[?1002l",oE="\x1B[?1003l",zc="\x1B[?1006l",iE="\x1B[?1015l",aE="\x1B[?w",dE="\x1B[=24;1w",wk="\x1B[=0;0w",cE="\x1B]22;pointer\x07",bm="\x1B]22;default\x07",km="\x1B[?1004h",Nu="\x1B[?1004l",lE="\x1B[?2026h",uE="\x1B[?2026l",NW=n=>{process.stdout.write(n)},DW=NW});function bk(n,e){let t=new Map;for(let[r,s,o]of n){let i=t.get(r);i||(i=new Map,t.set(r,i)),i.set(s,o)}return{chords:t,timeoutMs:e}}var wi,kk,vm,Du=q(()=>{"use strict";wi=class{constructor(e,t=Date.now){this.table=e;this.now=t}table;now;pending=null;get isArmed(){return this.pending!==null}clear(){this.pending=null}feed(e){if(this.pending){let{prefix:t,armedAt:r}=this.pending;this.pending=null;let o=this.now()-r<=this.table.timeoutMs?this.table.chords.get(t)?.get(e):void 0;return o!==void 0?{kind:"pass",token:o}:{kind:"aborted"}}return this.table.chords.has(e)?(this.pending={prefix:e,armedAt:this.now()},{kind:"armed"}):{kind:"pass",token:e}}};kk=1500,vm=bk([["CTRL_X","CTRL_E","CTRL_X_CTRL_E"]],kk)});function ls(){we(ns),we(_a),we(Po),we($a),we(Oa),we(jc),we(qc),we(zc),we(Ma),we("\x1B>")}function xn(n){return n.width??80}function Ys(n){return n.height??24}function pr(n,e){let t=xn(n),r=Ys(n),s=e.contentWidth??BW,o=Math.max(10,t-4),i=Math.min(s,o),a=i+2,d=Math.max(1,Math.min(e.contentHeight,r-4)),c=d+2,l=Math.max(1,Math.floor((t-a)/2)+1),u=Math.max(1,Math.floor((r-c)/2)+1);e.overlay||n.moveTo(1,1).eraseDisplayBelow();let f=fE.repeat(a-2),p=qW(f,e.title);n.moveTo(l,u),B(n,"box-border",HW),zW(n,p),B(n,"box-border",UW);for(let m=1;m<=d;m++)n.moveTo(l,u+m),B(n,"box-border",pE),e.overlay&&n.noFormat(" ".repeat(i)),n.moveTo(l+a-1,u+m),B(n,"box-border",pE);return n.moveTo(l,u+c-1),B(n,"box-border",WW+fE.repeat(a-2)+jW),{x:l,y:u,w:a,h:c,contentX:l+1,contentY:u+1,contentW:i,contentH:d}}function qW(n,e){if(!e)return{dashes:n};let t=` ${e} `;if(t.length+4>n.length)return{dashes:n};let r=2;return{dashes:n.slice(0,r)+" ".repeat(t.length)+n.slice(r+t.length),title:{offset:r,text:t}}}function zW(n,e){if(!e.title){B(n,"box-border",e.dashes);return}B(n,"box-border",e.dashes.slice(0,e.title.offset)),B(n,"box-title",e.title.text),B(n,"box-border",e.dashes.slice(e.title.offset+e.title.text.length))}function _t(n,e){return e<=1?"":n.length<=e?n:n.slice(0,Math.max(0,e-1))+"\u2026"}function La(n,e){return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}async function Qs(n){let{term:e,render:t,onKey:r,onResize:s,onMouse:o}=n,i=n.hideCursor!==!1;return t(),i&&e.hideCursor(),await new Promise(a=>{let d=!1,c=new wi(vm),l=()=>{d||(s??t)()},u=(h,g,w)=>{if(d)return;if(w?.isCharacter){c.clear(),r(h,g,w,m);return}let b=c.feed(h);switch(b.kind){case"pass":r(b.token,g,w,m);return;case"armed":case"aborted":return}},f=(h,g)=>{d||!o||o(h,g,m)},p=()=>{d||(d=!0,e.off("key",u),e.off("resize",l),o&&e.off("mouse",f),e.grabInput(!1),ge({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),n.overlay||e.moveTo(1,1).eraseDisplayBelow())},m=h=>{p(),a(h)};o?(e.grabInput({mouse:"motion"}),e.on("mouse",f)):e.grabInput({}),ge({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",u),e.on("resize",l)})}var BW,fE,pE,HW,UW,WW,jW,Na=q(()=>{"use strict";na();Fa();Tn();Du();BW=64,fE="\u2500",pE="\u2502",HW="\u250C",UW="\u2510",WW="\u2514",jW="\u2518"});function hE(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 JW(n,e,t){let r={title:`Agent "${n}" needs to be set up`,description:e?.description??KW,footer:GW};if(e?.command&&(r.command=e.command),e?.url&&(r.url=e.url),t&&t.length>0){r.authMethods=t;let s=t.map((d,c)=>({index:c,label:`[${c+1}] ${hE(d)}`,method:d}));r.methodLines=s;let o=Math.min(t.length,9),i=o===1?"[1]":`[1\u2026${o}]`,a=t.length===1?" \xB7 [Enter] choose":"";r.footer=`${i} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return r}function VW(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 r=Number(n)-1;return r<t?{kind:"selectMethod",index:r}:{kind:"ignore"}}return e?.isCharacter&&n.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function YW(n){return typeof n!="object"||n===null?!1:n.code===G.AuthRequired}function mE(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 r=t[ut];if(!(typeof r!="object"||r===null))return r}function QW(n){let e=mE(n);if(!e)return;let t=e.agentId;return typeof t=="string"?t:void 0}function XW(n){let e=mE(n);if(!e)return;let t=e.authMethods;if(!Array.isArray(t))return;let r=[];for(let s of t){if(typeof s!="object"||s===null)continue;let o=s.id;if(typeof o!="string"||o.length===0)continue;let i=s.description,a=s.type,d=s.name,c=s._meta,l={id:o,description:typeof i=="string"?i:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof d=="string"&&(l.name=d),c!==null&&typeof c=="object"&&!Array.isArray(c)&&(l._meta=c),r.push(l)}return r.length>0?r:void 0}async function gE(n){for(;;)try{return{kind:"ok",result:await n.request()}}catch(e){if(!YW(e))throw e;let t=QW(e)??n.fallbackAgentId??"",r=XW(e),s=await n.resolveOnboarding(t),o=await n.showBanner(t,s,r);if(o==="back")return{kind:"back"};if(o==="cancel")return{kind:"cancel"}}}async function ZW(n,e,t){n.grabInput(!1),ge({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),ls(),n.moveTo(1,1).eraseDisplayBelow();let r=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(r+`
|
|
225
225
|
`);let s=t?.spawn??(await import("child_process")).spawn;return await new Promise(o=>{let i=()=>{try{n.grabInput({}),ge({src:"grab",site:"runTerminalAuthSpawn.reGrab",on:!0})}catch{}};try{let a=s(e.command,e.args,{stdio:"inherit",env:e.env,cwd:e.cwd});a.on("exit",d=>{i(),o({exitCode:d})}),a.on("error",d=>{i(),process.stdout.write(`
|
|
226
226
|
failed to spawn ${e.command}: ${d.message}
|
|
227
227
|
`),o({exitCode:-1})})}catch(a){i(),process.stdout.write(`
|
|
228
228
|
failed to spawn ${e.command}: ${a.message}
|
|
229
|
-
`),o({exitCode:-1})}})}function ej(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 vk(n,e){let t;try{t=await e.authenticate(n.id)}catch(r){return{kind:"error",message:r instanceof Error&&r.message.length>0?r.message:String(r)}}if(ej(t)){let r={command:t.command,args:t.args,env:t.env,cwd:t.cwd},s=await e.runTerminalAuth(r);return s.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:s.exitCode}}return{kind:"retry"}}async function yE(n,e,t,r,s){ls();let o=JW(e,t,r),i=!1,a,d,c=null,l=null,u=null,f=null,p=(k,S,I,x)=>{let A=_t(I,k.contentW-3);if(n.moveTo(k.contentX,S),x){B(n,"list-selected",La(` ${A}`,k.contentW));return}B(n,"modal-label"," "),B(n,"content",A),3+A.length<k.contentW&&n.noFormat(" ".repeat(k.contentW-3-A.length))},m=()=>{let k=4;o.command&&k++,o.url&&k++,o.methodLines&&(k+=1+o.methodLines.length),a&&k++,d&&k++;let S=pr(n,{contentHeight:k,contentWidth:80,title:"Authentication required"}),I=S.contentW,x=0;if(a&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-note",_t(` ${a}`,I)),x++),d&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-error",_t(` ${d}`,I)),x++),n.moveTo(S.contentX,S.contentY+x),B(n,"modal-title",_t(` ${o.title}`,I)),x+=2,n.moveTo(S.contentX,S.contentY+x),B(n,"content",_t(` ${o.description}`,I)),x++,o.command&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-label"," Run: "),B(n,"modal-value",_t(o.command,I-7)),x++),o.url&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-label"," Docs: "),B(n,"modal-value",_t(o.url,I-7)),x++),o.methodLines){n.moveTo(S.contentX,S.contentY+x),B(n,"modal-label"," Methods reported by the agent:"),x++,l=S.contentY+x;for(let A of o.methodLines)p(S,S.contentY+x,A.label,A.index===u),x++}else l=null;return x++,n.moveTo(S.contentX,S.contentY+x),B(n,"modal-hint",` ${o.footer}`),c=S,S},h=()=>{let k=c,S=l;if(!(k===null||S===null||!o.methodLines))for(let I of o.methodLines)p(k,S+I.index,I.label,I.index===u)},g=k=>{let S=l,I=o.methodLines?.length??0;if(S===null||I===0)return null;let x=k-S;return x>=0&&x<I?x:null},w=o.methodLines?.length??0;return
|
|
229
|
+
`),o({exitCode:-1})}})}function ej(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 vk(n,e){let t;try{t=await e.authenticate(n.id)}catch(r){return{kind:"error",message:r instanceof Error&&r.message.length>0?r.message:String(r)}}if(ej(t)){let r={command:t.command,args:t.args,env:t.env,cwd:t.cwd},s=await e.runTerminalAuth(r);return s.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:s.exitCode}}return{kind:"retry"}}async function yE(n,e,t,r,s){ls();let o=JW(e,t,r),i=!1,a,d,c=null,l=null,u=null,f=null,p=(k,S,I,x)=>{let A=_t(I,k.contentW-3);if(n.moveTo(k.contentX,S),x){B(n,"list-selected",La(` ${A}`,k.contentW));return}B(n,"modal-label"," "),B(n,"content",A),3+A.length<k.contentW&&n.noFormat(" ".repeat(k.contentW-3-A.length))},m=()=>{let k=4;o.command&&k++,o.url&&k++,o.methodLines&&(k+=1+o.methodLines.length),a&&k++,d&&k++;let S=pr(n,{contentHeight:k,contentWidth:80,title:"Authentication required"}),I=S.contentW,x=0;if(a&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-note",_t(` ${a}`,I)),x++),d&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-error",_t(` ${d}`,I)),x++),n.moveTo(S.contentX,S.contentY+x),B(n,"modal-title",_t(` ${o.title}`,I)),x+=2,n.moveTo(S.contentX,S.contentY+x),B(n,"content",_t(` ${o.description}`,I)),x++,o.command&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-label"," Run: "),B(n,"modal-value",_t(o.command,I-7)),x++),o.url&&(n.moveTo(S.contentX,S.contentY+x),B(n,"modal-label"," Docs: "),B(n,"modal-value",_t(o.url,I-7)),x++),o.methodLines){n.moveTo(S.contentX,S.contentY+x),B(n,"modal-label"," Methods reported by the agent:"),x++,l=S.contentY+x;for(let A of o.methodLines)p(S,S.contentY+x,A.label,A.index===u),x++}else l=null;return x++,n.moveTo(S.contentX,S.contentY+x),B(n,"modal-hint",` ${o.footer}`),c=S,S},h=()=>{let k=c,S=l;if(!(k===null||S===null||!o.methodLines))for(let I of o.methodLines)p(k,S+I.index,I.label,I.index===u)},g=k=>{let S=l,I=o.methodLines?.length??0;if(S===null||I===0)return null;let x=k-S;return x>=0&&x<I?x:null},w=o.methodLines?.length??0;return Qs({term:n,render:()=>{m()},onKey:(k,S,I,x)=>{if(i)return;let A=VW(k,I,w);if(A.kind!=="ignore"){if(A.kind==="retry"||A.kind==="back"||A.kind==="cancel"){x(A.kind);return}A.kind==="selectMethod"&&b(A.index,x)}},onMouse:(k,S,I)=>{if(i)return;if(k==="MOUSE_LEFT_BUTTON_PRESSED"){f={x:S?.x??-1,y:S?.y??-1};return}let x=S?.y;if(typeof x!="number")return;if(k==="MOUSE_MOTION"){let $=g(x);$!==u&&(u=$,h());return}if(k!=="MOUSE_LEFT_BUTTON_RELEASED")return;let A=S?.x,_=f!==null&&A===f.x&&x===f.y;if(f=null,!_)return;if(c!==null&&typeof A=="number"&&(A<c.x||A>=c.x+c.w||x<c.y||x>=c.y+c.h)){I("back");return}let P=g(x);P!==null&&b(P,I)}});function b(k,S){let I=o.methodLines?.[k]?.method;if(!I||!s?.authenticate)return;i=!0,u=null,d=void 0,a=`Authenticating with ${hE(I)}\u2026`,m();let x=s.runTerminalAuth??(A=>ZW(n,A));(async()=>{let A=await vk(I,{authenticate:s.authenticate,runTerminalAuth:x});if(A.kind==="terminal-completed"){S("terminal-completed");return}if(A.kind==="retry"){S("retry");return}if(A.kind==="error"){d=A.message,a=void 0,i=!1,m();return}a=void 0,d=`auth process exited with code ${A.exitCode??"(signal)"}`,i=!1,m()})()}}var KW,GW,Sk=q(()=>{"use strict";na();jl();cc();Na();Tn();KW="This agent requires authentication before use.",GW="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as CE}from"timers/promises";function lj(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var ij,aj,dj,cj,Gc,xk=q(()=>{"use strict";qd();Sa();ij=200,aj=5e3,dj=2,cj=60,Gc=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,r=new Promise((s,o)=>{this.pendingRequests.set(t,{resolve:s,reject:o})});try{await this.current.send(e)}catch(s){throw this.pendingRequests.delete(t),s}return r}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),CE(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=ij;for(;!this.destroyed;)try{let r=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,s=typeof this.opts.subprotocols=="function"?await this.opts.subprotocols():this.opts.subprotocols,o=await bo(r,s);this.bindStream(Rr(o));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(a=>{this.releaseConnectGate=a});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(a){this.log(`hydra-acp: post-connect handler failed: ${a.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(r){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(r),e>=cj)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${r.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${r.message}); retrying in ${t}ms`),await CE(t),this.destroyed)return;t=Math.min(t*dj,aj)}}bindStream(e){this.current=e,e.onMessage(t=>{if(lj(t)&&t.id!==null){let r=this.pendingRequests.get(t.id);r&&(this.pendingRequests.delete(t.id),r.resolve(t))}for(let r of this.messageHandlers)r(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let r=t??new Error("ws closed before response");for(let{reject:s}of this.pendingRequests.values())s(r);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 r of this.closeHandlers)r(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
|
|
230
230
|
`)}}});function RE(n,e){let t=n&&typeof n=="object"?n.options:void 0;if(Array.isArray(t)){for(let o of e){let i=t.find(a=>typeof a=="object"&&a!==null&&a.kind===o&&typeof a.optionId=="string");if(i?.optionId!==void 0)return i.optionId}let s=t.find(o=>typeof o=="object"&&o!==null&&typeof o.optionId=="string");if(s?.optionId!==void 0)return s.optionId}let r=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(r)} (agent will likely reject)`),r}function Da(n){return{outcome:{outcome:"selected",optionId:RE(n,["allow_once","allow_always"])}}}function AE(n){return{outcome:{outcome:"selected",optionId:RE(n,["reject_once","reject_always"])}}}function Im(n){return n&&typeof n=="object"?n:void 0}function Hu(n){return typeof n=="string"&&n.length>0?n:void 0}function TE(n){let e=Im(n),t=Im(e?.toolCall),r={paths:[]};if(!t)return r;let s=Hu(t.kind);s&&(r.kind=s);let o=new Set,i=c=>{let l=Hu(c);l&&!o.has(l)&&(o.add(l),r.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let c of a)i(Im(c)?.path);let d=Im(t.rawInput);if(d){i(d.file_path),i(d.filePath),i(d.path);let c=Hu(d.command);c&&(r.command=c);let l=Hu(d.url);l&&(r.url=l);let u=Hu(d.description);u&&(r.description=u)}return r}function EE(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 Cm=q(()=>{"use strict"});function f2(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function GE(n){let t=(n.split("-",1)[0]??n).split("."),r=Number(t[0]),s=Number(t[1]),o=Number(t[2]);return!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o)?null:[r,s,o]}function p2(n,e){let t=GE(n),r=GE(e);if(!t||!r)return n!==e;for(let s=0;s<3;s++){let o=t[s],i=r[s];if(o>i)return!0;if(o<i)return!1}return!1}async function Uu(){if(ki!==void 0)return ki;if(f2())return ki=null,ki;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:JE,version:Ue}}),r=t.update;if(r&&typeof r.latest=="string"&&typeof r.current=="string"&&p2(r.latest,r.current)){try{t.config?.set?.("update",r)}catch{}ki={current:r.current,latest:r.latest,type:typeof r.type=="string"?r.type:"unknown"}}else{if(r&&typeof r.latest=="string"&&typeof r.current=="string")try{t.config?.set?.("update",void 0)}catch{}ki=null}}catch{ki=null}return ki}function Wu(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${JE}`}var JE,ki,Ak=q(()=>{"use strict";dr();JE="@hydra-acp/cli"});import*as Pk from"net";import*as YE from"path";function y2(n){return n.HERDR_ENV==="1"&&!!n.HERDR_SOCKET_PATH&&!!n.HERDR_PANE_ID}function w2(n,e,t){return new Promise(r=>{let s;try{s=`${JSON.stringify({id:t,method:e.method,params:e.params})}
|
|
231
231
|
`}catch{r(!1);return}let o;try{o=Pk.connect(n)}catch{r(!1);return}let i=!1,a=d=>{i||(i=!0,o.destroy(),r(d))};o.on("connect",()=>o.write(s)),o.on("data",()=>a(!0)),o.on("error",()=>a(!1)),o.on("close",()=>a(!1)),o.setTimeout(h2,()=>a(!1))})}function Ha(n,e,t){return new Promise((r,s)=>{let o;try{o=Pk.connect(n)}catch(c){s(c);return}let i="",a=!1,d=(c,l)=>{a||(a=!0,o.destroy(),c?s(c):r(l))};o.on("connect",()=>{o.write(`${JSON.stringify({id:"hydra-req",method:e,params:t})}
|
|
232
232
|
`)}),o.on("data",c=>{i+=c.toString("utf8");let l=i.indexOf(`
|
|
233
233
|
`),u=l===-1?i:i.slice(0,l);if(!(l===-1&&u.length===0))try{d(null,JSON.parse(u.trim()))}catch{}}),o.on("error",c=>d(c)),o.on("close",()=>d(new Error("herdr closed the connection"))),o.setTimeout(m2,()=>d(new Error("herdr did not respond")))})}function Mm(){return Tk+=1,Tk}function b2(n){return n!==null&&n>0?String(n):null}function k2(n){let e=n?.trim();return e?YE.basename(e)||e:null}function v2(n,e,t){if(n.length===0)return null;let r=s=>s.pane_id===e?0:t&&s.workspace_id===t?1:2;return[...n].sort((s,o)=>r(s)-r(o)||s.pane_id.localeCompare(o.pane_id))[0]}var Pm,VE,h2,m2,g2,Tk,Ek,QE,XE=q(()=>{"use strict";Pm="hydra",VE="hydra",h2=2e3,m2=5e3,g2=["HERDR_PANE_ID","HERDR_TAB_ID","HERDR_WORKSPACE_ID","HERDR_STARTUP_CWD"];Tk=Date.now()*1e3;Ek=class{id="herdr";caps={openTab:!0,split:!1,label:!!process.env.HERDR_TAB_ID,report:!0,reveal:!0};socketPath;paneId;tabId;chain=Promise.resolve();sentState=null;sentMeta=null;claimed=!1;constructor(e){this.socketPath=e.HERDR_SOCKET_PATH,this.paneId=e.HERDR_PANE_ID,this.tabId=e.HERDR_TAB_ID}tokens(e){return{kind:e.agent??null,cwd:k2(e.cwd),model:e.model??null,cost:e.cost??null,queue:b2(e.queued),turn:e.turnOrigin,turn_label:e.turnLabel,session:e.sessionId??null}}send(e,t){if(e.length===0)return Promise.resolve();let r=e.map((s,o)=>({frame:s,id:`hydra-${Tk}-${o}`}));return this.chain=this.chain.then(async()=>{for(let{frame:s,id:o}of r)if(!await w2(this.socketPath,s,o)){t?.();return}}).catch(()=>{t?.()}),this.chain}async report(e){let t=this.tokens(e),r=JSON.stringify({title:e.title,tokens:t}),s=[],o=this.sentState===null&&e.state==="unknown",i=`${e.state} ${e.turnOrigin??""}`;if(this.sentState!==i&&!o&&s.push({method:"pane.report_agent",params:{pane_id:this.paneId,source:Pm,agent:VE,state:e.state,...e.turnOrigin?{turn_origin:e.turnOrigin}:{},...e.turnLabel?{turn_label:e.turnLabel}:{},seq:Mm()}}),this.sentMeta!==r&&s.push({method:"pane.report_metadata",params:{pane_id:this.paneId,source:Pm,seq:Mm(),...e.title?{title:e.title}:{clear_title:!0},clear_display_agent:!0,tokens:t}}),s.length===0)return;let a=this.sentState,d=this.sentMeta;this.sentState=i,this.sentMeta=r,this.claimed=!0,await this.send(s,()=>{this.sentState=a,this.sentMeta=d})}async release(){if(!this.claimed)return;let e={kind:null,cwd:null,model:null,cost:null,queue:null,turn:null,turn_label:null,session:null},t=this.send([{method:"pane.report_metadata",params:{pane_id:this.paneId,source:Pm,seq:Mm(),clear_title:!0,clear_display_agent:!0,clear_state_labels:!0,tokens:e}},{method:"pane.release_agent",params:{pane_id:this.paneId,source:Pm,agent:VE,seq:Mm()}}]);this.sentState=null,this.sentMeta=null,this.claimed=!1,await t}async openTab(e){let t={type:"pane",label:e.label,command:e.argv};e.cwd&&e.cwd.startsWith("/")&&(t.cwd=e.cwd),e.env&&Object.keys(e.env).length>0&&(t.env=e.env);let r={tab_label:e.label,focus:!0,root:t};process.env.HERDR_WORKSPACE_ID&&(r.workspace_id=process.env.HERDR_WORKSPACE_ID);let s;try{s=await Ha(this.socketPath,"layout.apply",r)}catch(a){return{ok:!1,error:a.message}}let o=s;if(o?.error)return{ok:!1,error:o.error.message||o.error.code||"herdr rejected the request"};let i=o?.result?.layout?.tab_id;return i&&await Ha(this.socketPath,"tab.focus",{tab_id:i}).catch(()=>{}),{ok:!0}}async revealSession(e){if(!e)return!1;let t;try{t=await Ha(this.socketPath,"pane.list",{})}catch{return!1}let r=t?.result?.panes;if(!Array.isArray(r))return!1;let s=r.filter(i=>!!i&&typeof i=="object"&&typeof i.pane_id=="string"&&(i.tokens?.session??null)===e),o=v2(s,this.paneId,process.env.HERDR_WORKSPACE_ID);return o?(o.tab_id&&await Ha(this.socketPath,"tab.focus",{tab_id:o.tab_id}).catch(()=>{}),await Ha(this.socketPath,"pane.focus",{pane_id:o.pane_id}).catch(()=>{}),!0):!1}async readLabel(){if(!this.tabId)return null;let e=await Ha(this.socketPath,"tab.get",{tab_id:this.tabId});if(!e||e.error)return null;let t=e.result?.tab;return!t||typeof t.label!="string"||typeof t.pane_count!="number"?null:{label:t.label,paneCount:t.pane_count}}async writeLabel(e){return this.tabId?!(await Ha(this.socketPath,"tab.rename",{tab_id:this.tabId,label:e}))?.error:!1}isAutoLabel(e){let t=e.trim();return t.length===0||/^[0-9]+$/.test(t)}},QE={id:"herdr",paneScopedEnv:g2,detect:y2,create:()=>new Ek(process.env)}});import{execFile as S2}from"child_process";import{promisify as x2}from"util";function A2(n){return!!n.PASEO_TERMINAL_ID&&!!n.PASEO_ACTIVITY_TOKEN&&!!n.PASEO_TERMINAL_ACTIVITY_URL}function T2(n){switch(n){case"working":return"running";case"blocked":return"needs-input";case"idle":case"unknown":return"idle"}}function tP(n){return`'${n.replace(/'/g,"'\\''")}'`}var ZE,eP,I2,C2,R2,Mk,nP,rP=q(()=>{"use strict";ZE=x2(S2),eP=5e3,I2=1e3,C2=1e3,R2=["PASEO_TERMINAL_ID","PASEO_ACTIVITY_TOKEN"];Mk=class{id="paseo";caps={openTab:!0,split:!1,label:!1,report:!0,reveal:!1};cli;terminalId;token;activityUrl;fetchImpl;lastState=null;claimed=!1;pendingNeedsInput=null;cancelPendingNeedsInput(){this.pendingNeedsInput!==null&&(clearTimeout(this.pendingNeedsInput),this.pendingNeedsInput=null)}constructor(e,t=fetch){this.cli=e.PASEO_HOOK_CLI||"paseo",this.terminalId=e.PASEO_TERMINAL_ID,this.token=e.PASEO_ACTIVITY_TOKEN,this.activityUrl=e.PASEO_TERMINAL_ACTIVITY_URL,this.fetchImpl=t}async post(e){let t=new AbortController,r=setTimeout(()=>t.abort(),I2);try{await this.fetchImpl(this.activityUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({terminalId:this.terminalId,token:this.token,state:e}),signal:t.signal})}catch{}finally{clearTimeout(r)}}async report(e){let t=T2(e.state);if(t!==this.lastState){if(this.lastState=t,this.claimed=!0,this.cancelPendingNeedsInput(),t==="needs-input"){this.pendingNeedsInput=setTimeout(()=>{this.pendingNeedsInput=null,this.lastState==="needs-input"&&this.post("needs-input")},C2),this.pendingNeedsInput.unref?.();return}await this.post(t)}}async release(){this.cancelPendingNeedsInput(),this.claimed&&(this.claimed=!1,this.lastState=null,await this.post("idle"))}async openTab(e){let t;try{let i=["terminal","create","--json","--name",e.label];e.cwd&&i.push("--cwd",e.cwd);let{stdout:a}=await ZE(this.cli,i,{timeout:eP});t=JSON.parse(a)}catch(i){return{ok:!1,error:i.message}}if(typeof t.id!="string"||t.id.length===0)return{ok:!1,error:"paseo terminal create returned no id"};let r=Object.entries(e.env??{}).map(([i,a])=>`${i}=${tP(a)}`).join(" "),s=e.argv.map(tP).join(" "),o=r?`${r} ${s}`:s;try{await ZE(this.cli,["terminal","send-keys",t.id,o,"Enter"],{timeout:eP})}catch(i){return{ok:!1,error:i.message}}return{ok:!0}}},nP={id:"paseo",paneScopedEnv:R2,detect:A2,create:()=>new Mk(process.env)}});import{execFile as E2}from"child_process";import{promisify as P2}from"util";function O2(n){return!!n.TMUX&&!!n.TMUX_PANE}function F2(n){let e=n.TMUX?.split(",")[0];return e&&e.length>0?e:null}function oP(n){let e=n,t=e.stderr?.trim();return t&&t.length>0?t:e.message??"tmux failed"}var M2,_2,$2,sP,_k,iP,aP=q(()=>{"use strict";M2=P2(E2),_2=2e3,$2=["TMUX_PANE"],sP=["@hydra_state","@hydra_title","@hydra_cwd","@hydra_agent","@hydra_model","@hydra_cost","@hydra_queue","@hydra_turn_origin","@hydra_turn_label","@hydra_session"];_k=class{id="tmux";caps={openTab:!0,split:!0,label:!0,report:!0,reveal:!0};socket;pane;session=null;sentTokens=null;constructor(e,t){this.socket=e,this.pane=t}async tmux(...e){let{stdout:t}=await M2("tmux",["-S",this.socket,...e],{timeout:_2,maxBuffer:1048576});return t}async sessionId(){return this.session===null&&(this.session=(await this.tmux("display-message","-p","-t",this.pane,"-F","#{session_id}")).trim()),this.session}tokenValues(e){return{"@hydra_state":e.state,"@hydra_title":e.title,"@hydra_cwd":e.cwd,"@hydra_agent":e.agent,"@hydra_model":e.model,"@hydra_cost":e.cost,"@hydra_queue":e.queued!==null&&e.queued>0?String(e.queued):null,"@hydra_turn_origin":e.turnOrigin,"@hydra_turn_label":e.turnLabel,"@hydra_session":e.sessionId}}async report(e){let t=this.tokenValues(e),r=JSON.stringify(t);if(this.sentTokens===r)return;let s=[];for(let o of sP){s.length>0&&s.push(";");let i=t[o]??null;s.push("set-option","-p","-t",this.pane),i===null||i===""?s.push("-u",o):s.push(o,i)}this.sentTokens=r;try{await this.tmux(...s)}catch(o){throw this.sentTokens=null,o}}async release(){if(this.sentTokens===null)return;this.sentTokens=null;let e=[];for(let t of sP)e.length>0&&e.push(";"),e.push("set-option","-p","-t",this.pane,"-u",t);await this.tmux(...e)}async revealSession(e){if(!e)return!1;let t;try{t=await this.tmux("list-panes","-a","-F","#{pane_id} #{session_id} #{window_id} #{@hydra_session}")}catch{return!1}let r=t.split(`
|
|
234
234
|
`).map(u=>u.split(" ")).filter(u=>u.length>=4&&u[3]===e);if(r.length===0)return!1;let s=null;try{s=await this.sessionId()}catch{s=null}let o=u=>u[0]===this.pane?0:s&&u[1]===s?1:2,i=[...r].sort((u,f)=>o(u)-o(f)||u[0].localeCompare(f[0]))[0],[a,d,c]=i,l=[];s&&d!==s&&l.push("switch-client","-t",d,";"),l.push("select-window","-t",c,";","select-pane","-t",a);try{await this.tmux(...l)}catch{return!1}return!0}async openTab(e){let t;try{t=await this.sessionId()}catch(s){return{ok:!1,error:oP(s)}}let r=["new-window","-t",t,"-n",e.label];return this.spawnWindow(r,e)}async splitTab(e){return this.spawnWindow(["split-window","-h","-t",this.pane],e)}async spawnWindow(e,t){let r=[...e];t.cwd&&t.cwd.startsWith("/")&&r.push("-c",t.cwd);for(let[s,o]of Object.entries(t.env??{}))r.push("-e",`${s}=${o}`);r.push(...t.argv);try{return await this.tmux(...r),{ok:!0}}catch(s){return{ok:!1,error:oP(s)}}}async readLabel(){let e;try{e=await this.tmux("display-message","-p","-t",this.pane,"-F","#{window_name} #{window_panes} #{?automatic-rename,1,0}")}catch{return null}let[t,r,s]=(e.split(`
|
|
235
235
|
`)[0]??"").split(" "),o=Number.parseInt(r??"",10);return t===void 0||!Number.isFinite(o)?null:{label:t,paneCount:o,auto:s==="1"}}async writeLabel(e){try{return await this.tmux("rename-window","-t",this.pane,e),!0}catch{return!1}}isAutoLabel(){return!1}};iP={id:"tmux",paneScopedEnv:$2,detect:O2,create:()=>{let n=F2(process.env),e=process.env.TMUX_PANE;if(!n||!e)throw new Error("tmux environment incomplete");return new _k(n,e)}}});var dP={};Ji(dP,{CANDIDATES:()=>Ua,__resetTerminalHostForTests:()=>B2,initTerminalHost:()=>$k,parseTerminalHostOverride:()=>N2,setTerminalHost:()=>D2,terminalHost:()=>on,terminalHostOverrideKeywords:()=>L2});function L2(){return["true","false","1","0","auto",...Ua.map(n=>n.id)]}function N2(n){if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;if(n==="auto")return"auto";let e=Ua.find(t=>t.id===n);return e?e.id:void 0}function $k(n=process.env,e="auto"){if(e===!1)return us=null,null;if(e!==!0&&e!=="auto"){let t=Ua.find(r=>r.id===e);if(t){try{us=t.create()}catch{us=null}return us}}for(let t of Ua){let r=!1;try{r=t.detect(n)}catch{continue}if(r){try{us=t.create()}catch{us=null}return us}}return us=null,null}function on(){return us}function D2(n){us=n}function B2(){us=null}var Ua,us,Wa=q(()=>{"use strict";XE();rP();aP();Ua=[nP,QE,iP];us=null});function Fm(n){let e=n.split(`
|
|
236
|
-
`)[0]?.trim()??"";return e.length<=cP?e:`${e.slice(0,cP-1).trimEnd()}\u2026`}function H2(n){if(lP)return;lP=!0;let e=process.env[uP];if(e&&e===n){Qs=n,_m=n,Fk=!0;return}n===Om&&(Qs=n,Fk=!0)}function Lk(){let n=on();return!n||!n.caps.label||!n.readLabel||!n.writeLabel||!n.isAutoLabel?null:{readLabel:n.readLabel.bind(n),writeLabel:n.writeLabel.bind(n),isAutoLabel:n.isAutoLabel.bind(n)}}function U2(n,e,t,r){return e!==1?!1:n===Qs?!0:r??t(n)}async function W2(){for(;ja!==null;){let n=Lk();if(!n){ja=null;return}let e=ja;if(ja=null,e.label===Qs)continue;let t;try{t=await n.readLabel()}catch{return}if(t&&(H2(t.label),!!U2(t.label,t.paneCount,n.isAutoLabel,t.auto))){try{if(!await n.writeLabel(e.label))return}catch{return}$m===null&&($m=t.label),Qs=e.label,e.transient||(_m=e.label)}}}function ju(n,e={}){if(!Lk())return;let t=n?Fm(n):"";t&&(ja={label:t,transient:e.transient===!0},!Ok&&(Ok=!0,W2().finally(()=>{Ok=!1;let r=ja;r!==null&&r.label!==Qs&&ju(r.label,{transient:r.transient})})))}async function fP(){let n=Lk();ja=null;let e=Fk?_m:$m;if(!n||e===null||Qs===null||e===Qs)return;let t=Qs;$m=null,Qs=null,_m=null;try{let r=await n.readLabel();if(!r||r.label!==t)return;await n.writeLabel(e)}catch{}}function pP(n){return{[uP]:n}}var uP,Om,cP,Qs,lP,Fk,_m,$m,ja,Ok,Nk=q(()=>{"use strict";Wa();uP="HYDRA_TAB_LABEL",Om="hydra\u2026",cP=40;Qs=null,lP=!1;Fk=!1,_m=null,$m=null,ja=null,Ok=!1});var Hk={};Ji(Hk,{__resetLauncherModeForTests:()=>J2,canOpenTab:()=>qu,canReveal:()=>Lm,labelForPrompt:()=>hP,launcherModeActive:()=>G2,launcherModeUnavailable:()=>j2,openInNewTab:()=>Yc,revealOrOpen:()=>zu,setLauncherMode:()=>Bk});function qu(){let n=on();return!!n&&n.caps.openTab&&!!n.openTab}function j2(n){for(let e of Ua)try{if(e.detect(n))return null}catch{}return"needs a supported terminal host (herdr or tmux); this pane is in neither"}function Lm(){let n=on();return!!n&&n.caps.reveal&&!!n.revealSession}async function zu(n){let e=on();if(e&&e.caps.reveal&&e.revealSession)try{if(await e.revealSession(n.sessionId))return{outcome:"revealed"}}catch{}let t=await Yc(n);return t.ok?{outcome:"opened"}:{outcome:"failed",...t.error?{error:t.error}:{}}}function z2(){let n=process.argv[1];if(!n)return null;let e=n.replace(/\\/g,"/").split("/").pop()??"";return q2.has(e)?n:null}function K2(n){let e=z2();return[...e?[process.execPath,e]:["hydra"],"tui",...n]}function Bk(n,e=!1){Nm=n,Dk=e}function G2(){return Nm}function J2(){Nm=!1,Dk=!1}function hP(n){return(n?Fm(n):"")||"new session"}function V2(n){if(n.kind==="attach"){let r=["--session",n.sessionId];return n.jumpToRecordedAt!==void 0&&r.push("--jump-to-recorded-at",String(n.jumpToRecordedAt)),{label:(n.title?Fm(n.title):"")||n.sessionId,args:r}}let e=["--new"];n.cwd&&e.push("--cwd",n.cwd),n.agentId&&e.push("--agent",n.agentId),n.model&&e.push("--model",n.model);let t=n.prompt?.trim();return t&&e.push("--prompt",t),{label:hP(t),args:e}}async function Yc(n){let e=on();if(!e||!e.caps.openTab||!e.openTab)return{ok:!1,error:"no terminal host available"};let{label:t,args:r}=V2(n);Nm?r.push("--terminal-host-launcher"):Dk&&r.push("--no-terminal-host-launcher");try{return await e.openTab({label:t,argv:K2(r),cwd:n.cwd,env:pP(t)})}catch(s){return{ok:!1,error:s.message}}}var q2,Nm,Dk,Ku=q(()=>{"use strict";Wa();Nk();q2=new Set(["cli.js","hydra","hydra-acp"]);Nm=!1,Dk=!1});import*as Gu from"fs/promises";import*as Uk from"path";function mP(n){if(process.platform!=="win32")return 0;let e=0;for(let t=1;t+1<n.length;t++){if(n[t]!==":")continue;let r=n[t-1]??"",s=n[t+1];/^[A-Za-z]$/.test(r)&&(s==="\\"||s==="/")&&(e=t-1)}return e}function Wk(n){let e=-1;for(let t=0;t<n.length-1;t++){if(n[t]!=="/")continue;let r=n[t+1];if(r==="/")e=t;else if(r==="~"){let s=n[t+2];(s==="/"||s===void 0)&&(e=t)}}return Math.max(e===-1?0:e+1,mP(n))}function gP(n){let e=0;for(let t=0;t<n.length-1;t++){if(n[t]!=="/")continue;let r=n[t+1];if(r==="/"){let s=t;for(;n[s]==="/";)s++;s-t>=3&&s-1>e&&(e=s-1)}else r==="~"&&n[t+2]==="/"&&t+1>e&&(e=t+1)}return Math.max(e,mP(n))}function yP(n){return n.slice(Wk(n))}async function Ju(n){let e=yP(n.trim());if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Uk.resolve(mt(e)),r;try{r=await Gu.stat(t)}catch{return{ok:!1,reason:`${t} does not exist`}}return r.isDirectory()?{ok:!0,path:t}:{ok:!1,reason:`${t} is not a directory`}}async function wP(n){let e=[],t=new Set,r=s=>{t.has(s)||(t.add(s),e.push(s))};r(n),n.startsWith("/Users/")?r("/home/"+n.slice(7)):n.startsWith("/home/")&&r("/Users/"+n.slice(6));for(let s of e)try{if((await Gu.stat(s)).isDirectory())return s}catch{}return null}async function bP(n){let e=yP(n),t=e.lastIndexOf("/"),r,s,o;t===-1?(r="",s=e,o="."):(r=e.slice(0,t+1),s=e.slice(t+1),o=t===0?"/":r);let i=Uk.resolve(mt(o)),a;try{a=(await Gu.readdir(i,{withFileTypes:!0})).map(u=>({name:u.name,isDir:u.isDirectory()}))}catch{return{prefix:r,basePrefix:s,matches:[]}}let d=s.startsWith("."),c=a.filter(l=>l.name.startsWith(s)).filter(l=>d||!l.name.startsWith(".")).map(l=>l.isDir?`${l.name}/`:l.name).sort();return{prefix:r,basePrefix:s,matches:c}}var jk=q(()=>{"use strict";rt()});var kP,vP,SP,xP=q(()=>{"use strict";kP="hydra-acp/question/list",vP="hydra-acp/question/answer",SP="hydra-acp/question/dismiss"});function Y2(n,e){let t=n.options.find(r=>r.value===e);return t?t.name||t.value:e}function IP(n){return{title:`${n.name} (${n.options.length})`,rows:n.options.map(e=>({id:e.value,kind:"choice",label:e.name||e.value,...e.name&&e.name!==e.value?{note:e.value}:{},...e.value===n.currentValue?{current:!0}:{}})),cursor:Math.max(0,n.options.findIndex(e=>e.value===n.currentValue)),hints:[{label:"\u2191/\u2193 choose"},{label:"\u23CE switch",action:"commit"},{label:"s save & apply",action:"save"},{label:"Esc close",action:"close"}],maxRows:16}}function qk(n,e=new Map){return{title:`Session config (${n.length})`,rows:n.map(t=>({id:t.id,kind:"select",label:t.name||t.id,value:Y2(t,e.get(t.id)??t.currentValue)})),cursor:0,hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 choose"},{label:"s save & apply",action:"save"},{label:"\u23CE apply",action:"commit"},{label:"Esc cancel",action:"cancel"}],maxRows:16}}function CP(n,e,t){if(n.options.length===0)return e;let r=n.options.findIndex(o=>o.value===e),s=r===-1?0:(r+t+n.options.length)%n.options.length;return n.options[s].value}var RP=q(()=>{"use strict"});var vi,Dm=q(()=>{"use strict";vi=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}setCursor(e){this.cur=Math.max(0,Math.min(e,this.buffer.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}}});function X2(n,e){if(e.type==="char")return n.insertText(e.ch),!0;if(e.type==="paste")return n.insertText(e.text.replace(/[\r\n\t]+/g," ")),!0;if(e.type!=="key")return!1;let t=Q2[e.name];return t!==void 0&&n.handleKey(t,!1)}function zk(n){return Math.max(0,Math.min(n.cursor,n.rows.length-1))}function Vu(n,e){let t=n.rows;if(t.length===0)return{type:"noop"};let r=zk(n),s=t[r],o=i=>(i+t.length)%t.length;if(e.type==="key")switch(e.name){case"enter":return s.kind==="select"?{type:"advance",row:r}:{type:"commit",row:r};case"escape":return{type:"close"};case"ctrl-c":return{type:"cancel"};case"up":return{type:"row",row:o(r-1)};case"down":return{type:"row",row:o(r+1)};default:break}if(s.kind==="text")return X2(s.editor,e)?{type:"edited",row:r}:{type:"noop"};if(e.type==="char"){if(/^[1-9]$/.test(e.ch)){let i=Number.parseInt(e.ch,10)-1;return i<t.length?{type:"row",row:i,viaDigit:!0}:{type:"noop"}}return e.ch==="s"||e.ch==="S"?{type:"save",row:r}:e.ch==="d"||e.ch==="D"?{type:"dismiss",row:r}:{type:"noop"}}if(e.type!=="key")return{type:"noop"};switch(e.name){case"left":return s.kind==="select"?{type:"cycle",row:r,delta:-1}:{type:"noop"};case"right":return s.kind==="select"?{type:"cycle",row:r,delta:1}:{type:"noop"};case"home":return{type:"row",row:0};case"end":return{type:"row",row:t.length-1};default:return{type:"noop"}}}function AP(n){let e=n.rows.map(t=>t.kind==="text"?{kind:"text",label:t.label,text:t.editor.text,cursor:t.editor.cursor}:t.kind==="choice"?{kind:"choice",label:t.label,...t.note!==void 0?{note:t.note}:{},...t.current===!0?{current:!0}:{}}:{kind:"select",label:t.label,value:t.value});return{title:n.title,rows:e,selectedIndex:zk(n),hints:n.hints,...n.maxRows!==void 0?{maxRows:n.maxRows}:{}}}function TP(n,e){if(e.kind==="hint")return[Z2(n,e.action)];let t=n.rows[e.row];if(t===void 0)return[];let r={type:"row",row:e.row};return e.select===!0?[r]:t.kind==="text"?e.caretOffset===void 0?[r]:(t.editor.setCursor(e.caretOffset),[r,{type:"edited",row:e.row}]):t.kind==="choice"?[{type:"commit",row:e.row}]:[r,{type:"cycle",row:e.row,delta:1}]}function Z2(n,e){let t=zk(n);switch(e){case"commit":return n.rows[t]?.kind==="select"?{type:"advance",row:t}:{type:"commit",row:t};case"close":return{type:"close"};case"cancel":return{type:"cancel"};case"save":return{type:"save",row:t};case"dismiss":return{type:"dismiss",row:t}}}function EP(n){return{title:n.title,rows:[{id:n.id,kind:"text",label:n.label,editor:new vi(n.initial)}],cursor:0,hints:n.hints}}var Q2,PP=q(()=>{"use strict";Dm();Q2={left:"LEFT",right:"RIGHT",home:"HOME",end:"END",backspace:"BACKSPACE",delete:"DELETE","alt-backspace":"ALT_BACKSPACE","alt-b":"ALT_B","alt-f":"ALT_F","ctrl-a":"CTRL_A","ctrl-b":"CTRL_B","ctrl-e":"CTRL_E","ctrl-f":"CTRL_F","ctrl-k":"CTRL_K","ctrl-u":"CTRL_U","ctrl-w":"CTRL_W","ctrl-y":"CTRL_Y","ctrl-underscore":"","alt-underscore":"\x1B_"}});import{EventEmitter as eq}from"events";import{WebSocket as tq}from"ws";function nq(n,e){let t={};try{let r=new URL(n);if(r.protocol==="wss:"){let s=$l(r.hostname);s.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=s.rejectUnauthorized),s.autoSelectFamily!==void 0&&(t.autoSelectFamily=s.autoSelectFamily),s.checkServerIdentity!==void 0&&(t.checkServerIdentity=s.checkServerIdentity)}}catch{}return new Promise((r,s)=>{let o=new tq(n,e,t),i=()=>{o.off("error",a),r(Rr(o))},a=d=>{o.off("open",i),s(d)};o.once("open",i),o.once("error",a)})}function MP(n,e,t,r={}){return new Promise((s,o)=>{(async()=>{let i=r.fetchImpl??fetch,a=r._streamFactory??nq,d=["acp.v1",`hydra-acp-token.${n.token}`],c=await a(n.wsUrl,d),l=new pn(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(r.reuseSessionId!==void 0)u=r.reuseSessionId;else{let h=t.replace(/\s+/g," ").trim().slice(0,60);u=(await Vh(n,e,{forkAt:r.forkAt,cwd:r.cwd,agentId:r.agentId,title:`btw: ${h}`,mode:"verbatim"},i)).sessionId}}catch(h){throw c.close().catch(()=>{}),h}let f=new Kk(l,c,u,n,i),p=!1,m=h=>{p||(p=!0,f.emit("event",h),c.close().catch(()=>{}))};l.onNotification("session/update",h=>{let g=h?.update;g!==void 0&&f.emit("event",{kind:"update",update:g})}),l.onClose(()=>{p||m({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw c.close().catch(()=>{}),Gs(n,u,i).catch(()=>{}),h}s(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[ut]:{ancillary:!0}}}).then(h=>{let g=h&&typeof h=="object"?h.stopReason:void 0;m(g==="cancelled"?{kind:"cancelled"}:g==="error"||g==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{m({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(o)})}var Kk,_P=q(()=>{"use strict";Xo();Tu();bo();Sa();fn();Kk=class extends eq{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,t,r,s,o){super(),this._conn=e,this._stream=t,this._sessionId=r,this._target=s,this._fetchImpl=o}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),Gs(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 Gk,Bm,$P=q(()=>{"use strict";To();Io();Gk=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t)}off(e,t){this._listeners.get(e)?.delete(t)}emit(e){this._listeners.get(e)?.forEach(r=>r())}},Bm=class extends Gk{_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=Ws(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 r=t.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=r;let i=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,i),i.length}this._pendingAgentText=r;let s=this._parseAgent(r),o=this._lines.length;return this._pushLines(s),this._pendingAgentRange={start:o,length:s.length},s.length}case"agent-thought":{let r=t.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=r;let i=Hc(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,i),i.length}this._pendingThoughtText=r;let s=Hc(r),o=this._lines.length;return this._pushLines(s),this._pendingThoughtRange={start:o,length:s.length},s.length}case"tool-call":{let r={initialTitle:t.title,latestTitle:t.title,status:t.status??"pending"};t.detail!==void 0&&(r.detail=t.detail),this._toolStates.set(t.toolCallId,r);let s=$u(r),o=this._lines.length;return this._pushLines(s),this._toolRanges.set(t.toolCallId,{start:o,length:s.length}),s.length}case"tool-call-update":{let r=this._toolStates.get(t.toolCallId);if(!r)return 0;t.title!==void 0&&(r.latestTitle=t.title),t.status!==void 0&&(r.status=t.status),t.detail!==void 0&&(r.detail=t.detail),t.errorText!==void 0&&(r.errorText=t.errorText);let s=$u(r),o=this._toolRanges.get(t.toolCallId);if(!o){let i=this._lines.length;return this._pushLines(s),this._toolRanges.set(t.toolCallId,{start:i,length:s.length}),s.length}return this._replaceRange(t.toolCallId,o,s),s.length}default:{let r=Ro(t);return this._pushLines(r),r.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return Ao(e,t!==void 0&&t>0?{maxWidth:t}:void 0)}_replaceAgentRange(e,t){let r=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.length,r!==0){for(let s of this._toolRanges.values())s.start>e.start&&(s.start+=r);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,t){let r=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.length,r!==0){for(let s of this._toolRanges.values())s.start>e.start&&(s.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=r)}this._emitChanged&&this.emit("changed")}_replaceRange(e,t,r){let s=r.length-t.length;if(this._lines.splice(t.start,t.length,...r),t.length=r.length,s!==0){for(let[o,i]of this._toolRanges)o!==e&&i.start>t.start&&(i.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>t.start&&(this._pendingAgentRange.start+=s),this._pendingThoughtRange&&this._pendingThoughtRange.start>t.start&&(this._pendingThoughtRange.start+=s)}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 r of e)this._lines.push(r);this._emitChanged&&this._lines.length>t&&this.emit("changed")}}});function qa(n){if(n!==void 0){if(n.remote!==void 0)return n.remote;if(n.importedFromMachine!==void 0&&!n.upstreamSessionId)return n.importedFromMachine}}function Qc(n){return n.remote!==void 0}var Jk,Hm=q(()=>{"use strict";Jk=[{id:"mode",label:"\u21E7\u21E5 mode",action:"toggle-mode"},{id:"options",label:"\u2303O options",action:"toggle-options"},{id:"pick",label:"\u2303P pick",action:"switch-session"},{id:"guide",label:"\u2303G guide",action:"show-help"},{id:"detach",label:"\u2303D detach",action:"detach"}]});function iq(n,e){let t=n.findIndex(r=>r.id===e);return t===-1?0:t}async function Yu(n,e,t,r){ls();let s=iq(e,t??rq),o=0,i=null,a=null,d=()=>{let x=Vs(n)-8;return Math.max(1,Math.min(sq,e.length,x))},c=()=>{let x=d(),A=Math.max(0,e.length-x);o>A&&(o=A),o<0&&(o=0)},l=()=>{let x=d();s<o?o=s:s>=o+x&&(o=s-x+1),c()},u=null,f=0,p=(x,A)=>{if(x<o||x>=o+f)return;let _=e[x];if(!_)return;let P=A.contentW,$=A.contentY+2+(x-o);n.moveTo(A.contentX,$);let F=x===s?"\u276F":" ",J=_.description??_.name,Y=` ${F} ${_.id}`;if(x===s){let W=`${Y} ${J}`;B(n,"list-selected",La(_t(W,P),P))}else{let W=P-Y.length-2,Z=W>1?` ${_t(J,W)}`:"";B(n,"content",Y),Z.length>0&&B(n,"list-description",Z);let ne=Y.length+Z.length;ne<P&&n.noFormat(" ".repeat(P-ne))}},m=(x,A)=>{let _=x.contentY+2+f+1;n.moveTo(x.contentX,_);let $=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>A?` (${s+1}/${e.length})`:""}`,F=La(_t($,x.contentW),x.contentW);B(n,"modal-hint",F)},h=()=>{c();let x=d(),A=x+4,_=Math.min(oq,Math.max(40,xn(n)-8)),P=pr(n,{contentHeight:A,contentWidth:_,title:r?.title??"Select agent",overlay:r?.overlay===!0});a=P,u=P,f=Math.min(x,e.length-o),i=P.contentY+2,n.moveTo(P.contentX,P.contentY),B(n,"content",` ${r?.intro??"Which agent should this session use?"}`);let $=Math.min(e.length,o+x);for(let F=o;F<$;F++)p(F,P);return m(P,x),P},g=()=>h(),w=x=>{let A=u;if(A===null){h();return}let _=d(),P=o;if(l(),o!==P){h();return}f=Math.min(_,e.length-o),x!==s&&(p(x,A),p(s,A)),m(A,_)},b=()=>{if(s<e.length-1){let x=s;s++,w(x)}},k=()=>{if(s>0){let x=s;s--,w(x)}},S=()=>{let x=u;if(x===null){h();return}let A=d();c(),f=Math.min(A,e.length-o);let _=Math.min(e.length,o+A);for(let P=o;P<_;P++)p(P,x);for(let P=f;P<A;P++){let $=x.contentY+2+P;n.moveTo(x.contentX,$),n.noFormat(" ".repeat(x.contentW))}m(x,A)},I=x=>{let A=d(),_=Math.max(0,e.length-A);if(_===0)return;let P=Math.max(0,Math.min(_,o+x));P!==o&&(o=P,S())};return Ys({term:n,render:g,overlay:r?.overlay===!0,onKey:(x,A,_,P)=>{if(x==="CTRL_C"||x==="CTRL_D"){P({kind:"cancel"});return}if(x==="ESCAPE"){P({kind:"back"});return}if(x==="ENTER"||x==="KP_ENTER"){let $=e[s];$&&P({kind:"select",agentId:$.id,persist:!1});return}if(x==="UP"||x==="SHIFT_TAB"){k();return}if(x==="DOWN"||x==="TAB"){b();return}if(_?.isCharacter){let $=x.toLowerCase();if($==="s"){let F=e[s];F&&P({kind:"select",agentId:F.id,persist:!0});return}if($==="j"){b();return}if($==="k"){k();return}}},onMouse:(x,A,_)=>{if(x==="MOUSE_WHEEL_UP"){I(-1);return}if(x==="MOUSE_WHEEL_DOWN"){I(1);return}if(x==="MOUSE_MOTION"){let W=A?.y;if(typeof W!="number"||i===null)return;let Z=W-i;if(Z<0||Z>=f)return;let ne=o+Z;if(ne<0||ne>=e.length)return;if(ne!==s){let ve=s;s=ne,w(ve)}return}if(x!=="MOUSE_LEFT_BUTTON_PRESSED")return;let P=A?.x,$=A?.y;if(a!==null&&typeof P=="number"&&typeof $=="number"&&(P<a.x||P>=a.x+a.w||$<a.y||$>=a.y+a.h)){_({kind:"back"});return}if(typeof $!="number"||i===null)return;let F=$-i;if(F<0||F>=f)return;let J=o+F;if(J<0||J>=e.length)return;let Y=e[J];Y&&_({kind:"select",agentId:Y.id,persist:!1})}})}var rq,sq,oq,Vk=q(()=>{"use strict";Na();Tn();rq="opencode",sq=20,oq=88});import aq from"path";function Qu(n){return OP[aq.extname(n).toLowerCase()]??null}function dq(n){return Qu(n)!==null}function Yk(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(!cq.has(t))return null;let r=e[2],s=r.endsWith("==")?2:r.endsWith("=")?1:0,o=Math.floor(r.length*3/4)-s;return{mimeType:t,data:r,sizeBytes:o}}function lq(n){return Yk(n)!==null}function Mr(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function FP(n){let e=n.trim();if(e.length===0)return null;let t=[],r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]??"");)r++;if(r>=e.length)break;let s=e[r],o="";if(s==="'"||s==='"'){let a=s;for(r++;r<e.length&&e[r]!==a;)o+=e[r],r++;if(r>=e.length)return null;r++}else for(;r<e.length&&!/\s/.test(e[r]??"");)e[r]==="\\"&&r+1<e.length?(o+=e[r+1],r+=2):(o+=e[r],r++);if(o.startsWith("data:")){if(!lq(o))return null;t.push(o);continue}let i=o;if(i.startsWith("file://")&&(i=decodeURI(i.slice(7))),!i.startsWith("/")||!dq(i))return null;t.push(i)}return t.length>0?t:null}var Xs,OP,cq,Um=q(()=>{"use strict";Xs=10*1024*1024,OP={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};cq=new Set(Object.values(OP))});import{spawn as uq}from"child_process";import Qk from"fs/promises";import fq from"os";import pq from"path";async function jm(n={}){let e={...Xk,...n};return e.platform==="darwin"?yq(e):e.platform==="linux"?wq(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function DP(n={}){let e={...Xk,...n},t,r;if(e.platform==="darwin")t="pbpaste",r=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Xc(e,"wl-paste"))t="wl-paste",r=["--primary","-n"];else if(e.env.DISPLAY&&await Xc(e,"xclip"))t="xclip",r=["-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 s=await Xu(e.spawn,t,r);return s.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Zk(s.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Zc(n,e={}){let{target:t="both",...r}=e,s={...Xk,...r},o=await hq(s,n,t);if(o.ok)return o;let i=mq(s,n,t);return i.ok||i.reason!==BP?i:o}async function hq(n,e,t){let r=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await Wm(n.spawn,"pbcopy",[],r),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(n.platform==="linux"){let s=t==="clipboard"||t==="both",o=t==="primary"||t==="both";return n.env.WAYLAND_DISPLAY&&await Xc(n,"wl-copy")?NP(n,r,"wl-copy",[],["--primary"],s,o):n.env.DISPLAY&&await Xc(n,"xclip")?NP(n,r,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],s,o):{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 NP(n,e,t,r,s,o,i){let a=t;if(o){try{await Wm(n.spawn,t,r,e)}catch{return{ok:!1,reason:`${t} failed`}}if(i)try{await Wm(n.spawn,t,s,e)}catch{}return{ok:!0,method:a}}try{return await Wm(n.spawn,t,s,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function mq(n,e,t){let r=Buffer.from(e,"utf-8").toString("base64");if(r.length>LP)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${r.length} > ${LP} bytes)`};let o=`\x1B]52;${t==="both"?"cp":t==="primary"?"p":"c"};${r}\x07`;return n.env.TMUX&&(o=`\x1BPtmux;${o.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(n.ttyWrite??gq)(o)?{ok:!0,method:"osc52"}:{ok:!1,reason:BP}}function gq(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 yq(n){let e=pq.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"],r=[];for(let s of t)r.push("-e",s);try{await HP(n.spawn,"osascript",r);let s=await xq(e,!0);if(s.ok||s.reason.startsWith("clipboard image is"))return s}catch{await Qk.unlink(e).catch(()=>{})}try{let s=await Xu(n.spawn,"pbpaste",[]);return s.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Zk(s.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function wq(n){let e=await bq(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await Sq(n,e),r=vq(t);if(r)try{let s=await Xu(n.spawn,e.cmd,e.imageArgs(r));if(s.length>0)return s.length>Xs?{ok:!1,reason:`clipboard image is ${Mr(s.length)}, max ${Mr(Xs)}`}:{ok:!0,kind:"image",attachment:{mimeType:r,data:s.toString("base64"),sizeBytes:s.length}}}catch{}try{let s=await Xu(n.spawn,e.cmd,e.textArgs);return s.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Zk(s.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function bq(n){return n.env.WAYLAND_DISPLAY&&await Xc(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Xc(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function vq(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of kq)if(e.has(t))return t;return null}async function Sq(n,e){try{return(await Xu(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
|
|
236
|
+
`)[0]?.trim()??"";return e.length<=cP?e:`${e.slice(0,cP-1).trimEnd()}\u2026`}function H2(n){if(lP)return;lP=!0;let e=process.env[uP];if(e&&e===n){Xs=n,_m=n,Fk=!0;return}n===Om&&(Xs=n,Fk=!0)}function Lk(){let n=on();return!n||!n.caps.label||!n.readLabel||!n.writeLabel||!n.isAutoLabel?null:{readLabel:n.readLabel.bind(n),writeLabel:n.writeLabel.bind(n),isAutoLabel:n.isAutoLabel.bind(n)}}function U2(n,e,t,r){return e!==1?!1:n===Xs?!0:r??t(n)}async function W2(){for(;ja!==null;){let n=Lk();if(!n){ja=null;return}let e=ja;if(ja=null,e.label===Xs)continue;let t;try{t=await n.readLabel()}catch{return}if(t&&(H2(t.label),!!U2(t.label,t.paneCount,n.isAutoLabel,t.auto))){try{if(!await n.writeLabel(e.label))return}catch{return}$m===null&&($m=t.label),Xs=e.label,e.transient||(_m=e.label)}}}function ju(n,e={}){if(!Lk())return;let t=n?Fm(n):"";t&&(ja={label:t,transient:e.transient===!0},!Ok&&(Ok=!0,W2().finally(()=>{Ok=!1;let r=ja;r!==null&&r.label!==Xs&&ju(r.label,{transient:r.transient})})))}async function fP(){let n=Lk();ja=null;let e=Fk?_m:$m;if(!n||e===null||Xs===null||e===Xs)return;let t=Xs;$m=null,Xs=null,_m=null;try{let r=await n.readLabel();if(!r||r.label!==t)return;await n.writeLabel(e)}catch{}}function pP(n){return{[uP]:n}}var uP,Om,cP,Xs,lP,Fk,_m,$m,ja,Ok,Nk=q(()=>{"use strict";Wa();uP="HYDRA_TAB_LABEL",Om="hydra\u2026",cP=40;Xs=null,lP=!1;Fk=!1,_m=null,$m=null,ja=null,Ok=!1});var Hk={};Ji(Hk,{__resetLauncherModeForTests:()=>J2,canOpenTab:()=>qu,canReveal:()=>Lm,labelForPrompt:()=>hP,launcherModeActive:()=>G2,launcherModeUnavailable:()=>j2,openInNewTab:()=>Yc,revealOrOpen:()=>zu,setLauncherMode:()=>Bk});function qu(){let n=on();return!!n&&n.caps.openTab&&!!n.openTab}function j2(n){for(let e of Ua)try{if(e.detect(n))return null}catch{}return"needs a supported terminal host (herdr or tmux); this pane is in neither"}function Lm(){let n=on();return!!n&&n.caps.reveal&&!!n.revealSession}async function zu(n){let e=on();if(e&&e.caps.reveal&&e.revealSession)try{if(await e.revealSession(n.sessionId))return{outcome:"revealed"}}catch{}let t=await Yc(n);return t.ok?{outcome:"opened"}:{outcome:"failed",...t.error?{error:t.error}:{}}}function z2(){let n=process.argv[1];if(!n)return null;let e=n.replace(/\\/g,"/").split("/").pop()??"";return q2.has(e)?n:null}function K2(n){let e=z2();return[...e?[process.execPath,e]:["hydra"],"tui",...n]}function Bk(n,e=!1){Nm=n,Dk=e}function G2(){return Nm}function J2(){Nm=!1,Dk=!1}function hP(n){return(n?Fm(n):"")||"new session"}function V2(n){if(n.kind==="attach"){let r=["--session",n.sessionId];return n.jumpToRecordedAt!==void 0&&r.push("--jump-to-recorded-at",String(n.jumpToRecordedAt)),{label:(n.title?Fm(n.title):"")||n.sessionId,args:r}}let e=["--new"];n.cwd&&e.push("--cwd",n.cwd),n.agentId&&e.push("--agent",n.agentId),n.model&&e.push("--model",n.model);let t=n.prompt?.trim();return t&&e.push("--prompt",t),{label:hP(t),args:e}}async function Yc(n){let e=on();if(!e||!e.caps.openTab||!e.openTab)return{ok:!1,error:"no terminal host available"};let{label:t,args:r}=V2(n);Nm?r.push("--terminal-host-launcher"):Dk&&r.push("--no-terminal-host-launcher");try{return await e.openTab({label:t,argv:K2(r),cwd:n.cwd,env:pP(t)})}catch(s){return{ok:!1,error:s.message}}}var q2,Nm,Dk,Ku=q(()=>{"use strict";Wa();Nk();q2=new Set(["cli.js","hydra","hydra-acp"]);Nm=!1,Dk=!1});import*as Gu from"fs/promises";import*as Uk from"path";function mP(n){if(process.platform!=="win32")return 0;let e=0;for(let t=1;t+1<n.length;t++){if(n[t]!==":")continue;let r=n[t-1]??"",s=n[t+1];/^[A-Za-z]$/.test(r)&&(s==="\\"||s==="/")&&(e=t-1)}return e}function Wk(n){let e=-1;for(let t=0;t<n.length-1;t++){if(n[t]!=="/")continue;let r=n[t+1];if(r==="/")e=t;else if(r==="~"){let s=n[t+2];(s==="/"||s===void 0)&&(e=t)}}return Math.max(e===-1?0:e+1,mP(n))}function gP(n){let e=0;for(let t=0;t<n.length-1;t++){if(n[t]!=="/")continue;let r=n[t+1];if(r==="/"){let s=t;for(;n[s]==="/";)s++;s-t>=3&&s-1>e&&(e=s-1)}else r==="~"&&n[t+2]==="/"&&t+1>e&&(e=t+1)}return Math.max(e,mP(n))}function yP(n){return n.slice(Wk(n))}async function Ju(n){let e=yP(n.trim());if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Uk.resolve(mt(e)),r;try{r=await Gu.stat(t)}catch{return{ok:!1,reason:`${t} does not exist`}}return r.isDirectory()?{ok:!0,path:t}:{ok:!1,reason:`${t} is not a directory`}}async function wP(n){let e=[],t=new Set,r=s=>{t.has(s)||(t.add(s),e.push(s))};r(n),n.startsWith("/Users/")?r("/home/"+n.slice(7)):n.startsWith("/home/")&&r("/Users/"+n.slice(6));for(let s of e)try{if((await Gu.stat(s)).isDirectory())return s}catch{}return null}async function bP(n){let e=yP(n),t=e.lastIndexOf("/"),r,s,o;t===-1?(r="",s=e,o="."):(r=e.slice(0,t+1),s=e.slice(t+1),o=t===0?"/":r);let i=Uk.resolve(mt(o)),a;try{a=(await Gu.readdir(i,{withFileTypes:!0})).map(u=>({name:u.name,isDir:u.isDirectory()}))}catch{return{prefix:r,basePrefix:s,matches:[]}}let d=s.startsWith("."),c=a.filter(l=>l.name.startsWith(s)).filter(l=>d||!l.name.startsWith(".")).map(l=>l.isDir?`${l.name}/`:l.name).sort();return{prefix:r,basePrefix:s,matches:c}}var jk=q(()=>{"use strict";rt()});var kP,vP,SP,xP=q(()=>{"use strict";kP="hydra-acp/question/list",vP="hydra-acp/question/answer",SP="hydra-acp/question/dismiss"});function Y2(n,e){let t=n.options.find(r=>r.value===e);return t?t.name||t.value:e}function IP(n){return{title:`${n.name} (${n.options.length})`,rows:n.options.map(e=>({id:e.value,kind:"choice",label:e.name||e.value,...e.name&&e.name!==e.value?{note:e.value}:{},...e.value===n.currentValue?{current:!0}:{}})),cursor:Math.max(0,n.options.findIndex(e=>e.value===n.currentValue)),hints:[{label:"\u2191/\u2193 choose"},{label:"\u23CE switch",action:"commit"},{label:"s save & apply",action:"save"},{label:"Esc close",action:"close"}],maxRows:16}}function qk(n,e=new Map){return{title:`Session config (${n.length})`,rows:n.map(t=>({id:t.id,kind:"select",label:t.name||t.id,value:Y2(t,e.get(t.id)??t.currentValue)})),cursor:0,hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 choose"},{label:"s save & apply",action:"save"},{label:"\u23CE apply",action:"commit"},{label:"Esc cancel",action:"cancel"}],maxRows:16}}function CP(n,e,t){if(n.options.length===0)return e;let r=n.options.findIndex(o=>o.value===e),s=r===-1?0:(r+t+n.options.length)%n.options.length;return n.options[s].value}var RP=q(()=>{"use strict"});var vi,Dm=q(()=>{"use strict";vi=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}setCursor(e){this.cur=Math.max(0,Math.min(e,this.buffer.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}}});function X2(n,e){if(e.type==="char")return n.insertText(e.ch),!0;if(e.type==="paste")return n.insertText(e.text.replace(/[\r\n\t]+/g," ")),!0;if(e.type!=="key")return!1;let t=Q2[e.name];return t!==void 0&&n.handleKey(t,!1)}function zk(n){return Math.max(0,Math.min(n.cursor,n.rows.length-1))}function Vu(n,e){let t=n.rows;if(t.length===0)return{type:"noop"};let r=zk(n),s=t[r],o=i=>(i+t.length)%t.length;if(e.type==="key")switch(e.name){case"enter":return s.kind==="select"?{type:"advance",row:r}:{type:"commit",row:r};case"escape":return{type:"close"};case"ctrl-c":return{type:"cancel"};case"up":return{type:"row",row:o(r-1)};case"down":return{type:"row",row:o(r+1)};default:break}if(s.kind==="text")return X2(s.editor,e)?{type:"edited",row:r}:{type:"noop"};if(e.type==="char"){if(/^[1-9]$/.test(e.ch)){let i=Number.parseInt(e.ch,10)-1;return i<t.length?{type:"row",row:i,viaDigit:!0}:{type:"noop"}}return e.ch==="s"||e.ch==="S"?{type:"save",row:r}:e.ch==="d"||e.ch==="D"?{type:"dismiss",row:r}:{type:"noop"}}if(e.type!=="key")return{type:"noop"};switch(e.name){case"left":return s.kind==="select"?{type:"cycle",row:r,delta:-1}:{type:"noop"};case"right":return s.kind==="select"?{type:"cycle",row:r,delta:1}:{type:"noop"};case"home":return{type:"row",row:0};case"end":return{type:"row",row:t.length-1};default:return{type:"noop"}}}function AP(n){let e=n.rows.map(t=>t.kind==="text"?{kind:"text",label:t.label,text:t.editor.text,cursor:t.editor.cursor}:t.kind==="choice"?{kind:"choice",label:t.label,...t.note!==void 0?{note:t.note}:{},...t.current===!0?{current:!0}:{}}:{kind:"select",label:t.label,value:t.value});return{title:n.title,rows:e,selectedIndex:zk(n),hints:n.hints,...n.maxRows!==void 0?{maxRows:n.maxRows}:{}}}function TP(n,e){if(e.kind==="hint")return[Z2(n,e.action)];let t=n.rows[e.row];if(t===void 0)return[];let r={type:"row",row:e.row};return e.select===!0?[r]:t.kind==="text"?e.caretOffset===void 0?[r]:(t.editor.setCursor(e.caretOffset),[r,{type:"edited",row:e.row}]):t.kind==="choice"?[{type:"commit",row:e.row}]:[r,{type:"cycle",row:e.row,delta:1}]}function Z2(n,e){let t=zk(n);switch(e){case"commit":return n.rows[t]?.kind==="select"?{type:"advance",row:t}:{type:"commit",row:t};case"close":return{type:"close"};case"cancel":return{type:"cancel"};case"save":return{type:"save",row:t};case"dismiss":return{type:"dismiss",row:t}}}function EP(n){return{title:n.title,rows:[{id:n.id,kind:"text",label:n.label,editor:new vi(n.initial)}],cursor:0,hints:n.hints}}var Q2,PP=q(()=>{"use strict";Dm();Q2={left:"LEFT",right:"RIGHT",home:"HOME",end:"END",backspace:"BACKSPACE",delete:"DELETE","alt-backspace":"ALT_BACKSPACE","alt-b":"ALT_B","alt-f":"ALT_F","ctrl-a":"CTRL_A","ctrl-b":"CTRL_B","ctrl-e":"CTRL_E","ctrl-f":"CTRL_F","ctrl-k":"CTRL_K","ctrl-u":"CTRL_U","ctrl-w":"CTRL_W","ctrl-y":"CTRL_Y","ctrl-underscore":"","alt-underscore":"\x1B_"}});import{EventEmitter as eq}from"events";import{WebSocket as tq}from"ws";function nq(n,e){let t={};try{let r=new URL(n);if(r.protocol==="wss:"){let s=$l(r.hostname);s.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=s.rejectUnauthorized),s.autoSelectFamily!==void 0&&(t.autoSelectFamily=s.autoSelectFamily),s.checkServerIdentity!==void 0&&(t.checkServerIdentity=s.checkServerIdentity)}}catch{}return new Promise((r,s)=>{let o=new tq(n,e,t),i=()=>{o.off("error",a),r(Rr(o))},a=d=>{o.off("open",i),s(d)};o.once("open",i),o.once("error",a)})}function MP(n,e,t,r={}){return new Promise((s,o)=>{(async()=>{let i=r.fetchImpl??fetch,a=r._streamFactory??nq,d=["acp.v1",`hydra-acp-token.${n.token}`],c=await a(n.wsUrl,d),l=new pn(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(r.reuseSessionId!==void 0)u=r.reuseSessionId;else{let h=t.replace(/\s+/g," ").trim().slice(0,60);u=(await Vh(n,e,{forkAt:r.forkAt,cwd:r.cwd,agentId:r.agentId,title:`btw: ${h}`,mode:"verbatim"},i)).sessionId}}catch(h){throw c.close().catch(()=>{}),h}let f=new Kk(l,c,u,n,i),p=!1,m=h=>{p||(p=!0,f.emit("event",h),c.close().catch(()=>{}))};l.onNotification("session/update",h=>{let g=h?.update;g!==void 0&&f.emit("event",{kind:"update",update:g})}),l.onClose(()=>{p||m({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw c.close().catch(()=>{}),Js(n,u,i).catch(()=>{}),h}s(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[ut]:{ancillary:!0}}}).then(h=>{let g=h&&typeof h=="object"?h.stopReason:void 0;m(g==="cancelled"?{kind:"cancelled"}:g==="error"||g==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{m({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(o)})}var Kk,_P=q(()=>{"use strict";Xo();Tu();ko();Sa();fn();Kk=class extends eq{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,t,r,s,o){super(),this._conn=e,this._stream=t,this._sessionId=r,this._target=s,this._fetchImpl=o}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),Js(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 Gk,Bm,$P=q(()=>{"use strict";To();Io();Gk=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t)}off(e,t){this._listeners.get(e)?.delete(t)}emit(e){this._listeners.get(e)?.forEach(r=>r())}},Bm=class extends Gk{_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=js(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 r=t.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=r;let i=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,i),i.length}this._pendingAgentText=r;let s=this._parseAgent(r),o=this._lines.length;return this._pushLines(s),this._pendingAgentRange={start:o,length:s.length},s.length}case"agent-thought":{let r=t.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=r;let i=Hc(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,i),i.length}this._pendingThoughtText=r;let s=Hc(r),o=this._lines.length;return this._pushLines(s),this._pendingThoughtRange={start:o,length:s.length},s.length}case"tool-call":{let r={initialTitle:t.title,latestTitle:t.title,status:t.status??"pending"};t.detail!==void 0&&(r.detail=t.detail),this._toolStates.set(t.toolCallId,r);let s=$u(r),o=this._lines.length;return this._pushLines(s),this._toolRanges.set(t.toolCallId,{start:o,length:s.length}),s.length}case"tool-call-update":{let r=this._toolStates.get(t.toolCallId);if(!r)return 0;t.title!==void 0&&(r.latestTitle=t.title),t.status!==void 0&&(r.status=t.status),t.detail!==void 0&&(r.detail=t.detail),t.errorText!==void 0&&(r.errorText=t.errorText);let s=$u(r),o=this._toolRanges.get(t.toolCallId);if(!o){let i=this._lines.length;return this._pushLines(s),this._toolRanges.set(t.toolCallId,{start:i,length:s.length}),s.length}return this._replaceRange(t.toolCallId,o,s),s.length}default:{let r=Ro(t);return this._pushLines(r),r.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return Ao(e,t!==void 0&&t>0?{maxWidth:t}:void 0)}_replaceAgentRange(e,t){let r=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.length,r!==0){for(let s of this._toolRanges.values())s.start>e.start&&(s.start+=r);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,t){let r=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.length,r!==0){for(let s of this._toolRanges.values())s.start>e.start&&(s.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=r)}this._emitChanged&&this.emit("changed")}_replaceRange(e,t,r){let s=r.length-t.length;if(this._lines.splice(t.start,t.length,...r),t.length=r.length,s!==0){for(let[o,i]of this._toolRanges)o!==e&&i.start>t.start&&(i.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>t.start&&(this._pendingAgentRange.start+=s),this._pendingThoughtRange&&this._pendingThoughtRange.start>t.start&&(this._pendingThoughtRange.start+=s)}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 r of e)this._lines.push(r);this._emitChanged&&this._lines.length>t&&this.emit("changed")}}});function qa(n){if(n!==void 0){if(n.remote!==void 0)return n.remote;if(n.importedFromMachine!==void 0&&!n.upstreamSessionId)return n.importedFromMachine}}function Qc(n){return n.remote!==void 0}var Jk,Hm=q(()=>{"use strict";Jk=[{id:"mode",label:"\u21E7\u21E5 mode",action:"toggle-mode"},{id:"options",label:"\u2303O options",action:"toggle-options"},{id:"pick",label:"\u2303P pick",action:"switch-session"},{id:"guide",label:"\u2303G guide",action:"show-help"},{id:"detach",label:"\u2303D detach",action:"detach"}]});function iq(n,e){let t=n.findIndex(r=>r.id===e);return t===-1?0:t}async function Yu(n,e,t,r){ls();let s=iq(e,t??rq),o=0,i=null,a=null,d=()=>{let x=Ys(n)-8;return Math.max(1,Math.min(sq,e.length,x))},c=()=>{let x=d(),A=Math.max(0,e.length-x);o>A&&(o=A),o<0&&(o=0)},l=()=>{let x=d();s<o?o=s:s>=o+x&&(o=s-x+1),c()},u=null,f=0,p=(x,A)=>{if(x<o||x>=o+f)return;let _=e[x];if(!_)return;let P=A.contentW,$=A.contentY+2+(x-o);n.moveTo(A.contentX,$);let F=x===s?"\u276F":" ",J=_.description??_.name,Y=` ${F} ${_.id}`;if(x===s){let W=`${Y} ${J}`;B(n,"list-selected",La(_t(W,P),P))}else{let W=P-Y.length-2,Z=W>1?` ${_t(J,W)}`:"";B(n,"content",Y),Z.length>0&&B(n,"list-description",Z);let ne=Y.length+Z.length;ne<P&&n.noFormat(" ".repeat(P-ne))}},m=(x,A)=>{let _=x.contentY+2+f+1;n.moveTo(x.contentX,_);let $=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>A?` (${s+1}/${e.length})`:""}`,F=La(_t($,x.contentW),x.contentW);B(n,"modal-hint",F)},h=()=>{c();let x=d(),A=x+4,_=Math.min(oq,Math.max(40,xn(n)-8)),P=pr(n,{contentHeight:A,contentWidth:_,title:r?.title??"Select agent",overlay:r?.overlay===!0});a=P,u=P,f=Math.min(x,e.length-o),i=P.contentY+2,n.moveTo(P.contentX,P.contentY),B(n,"content",` ${r?.intro??"Which agent should this session use?"}`);let $=Math.min(e.length,o+x);for(let F=o;F<$;F++)p(F,P);return m(P,x),P},g=()=>h(),w=x=>{let A=u;if(A===null){h();return}let _=d(),P=o;if(l(),o!==P){h();return}f=Math.min(_,e.length-o),x!==s&&(p(x,A),p(s,A)),m(A,_)},b=()=>{if(s<e.length-1){let x=s;s++,w(x)}},k=()=>{if(s>0){let x=s;s--,w(x)}},S=()=>{let x=u;if(x===null){h();return}let A=d();c(),f=Math.min(A,e.length-o);let _=Math.min(e.length,o+A);for(let P=o;P<_;P++)p(P,x);for(let P=f;P<A;P++){let $=x.contentY+2+P;n.moveTo(x.contentX,$),n.noFormat(" ".repeat(x.contentW))}m(x,A)},I=x=>{let A=d(),_=Math.max(0,e.length-A);if(_===0)return;let P=Math.max(0,Math.min(_,o+x));P!==o&&(o=P,S())};return Qs({term:n,render:g,overlay:r?.overlay===!0,onKey:(x,A,_,P)=>{if(x==="CTRL_C"||x==="CTRL_D"){P({kind:"cancel"});return}if(x==="ESCAPE"){P({kind:"back"});return}if(x==="ENTER"||x==="KP_ENTER"){let $=e[s];$&&P({kind:"select",agentId:$.id,persist:!1});return}if(x==="UP"||x==="SHIFT_TAB"){k();return}if(x==="DOWN"||x==="TAB"){b();return}if(_?.isCharacter){let $=x.toLowerCase();if($==="s"){let F=e[s];F&&P({kind:"select",agentId:F.id,persist:!0});return}if($==="j"){b();return}if($==="k"){k();return}}},onMouse:(x,A,_)=>{if(x==="MOUSE_WHEEL_UP"){I(-1);return}if(x==="MOUSE_WHEEL_DOWN"){I(1);return}if(x==="MOUSE_MOTION"){let W=A?.y;if(typeof W!="number"||i===null)return;let Z=W-i;if(Z<0||Z>=f)return;let ne=o+Z;if(ne<0||ne>=e.length)return;if(ne!==s){let ve=s;s=ne,w(ve)}return}if(x!=="MOUSE_LEFT_BUTTON_PRESSED")return;let P=A?.x,$=A?.y;if(a!==null&&typeof P=="number"&&typeof $=="number"&&(P<a.x||P>=a.x+a.w||$<a.y||$>=a.y+a.h)){_({kind:"back"});return}if(typeof $!="number"||i===null)return;let F=$-i;if(F<0||F>=f)return;let J=o+F;if(J<0||J>=e.length)return;let Y=e[J];Y&&_({kind:"select",agentId:Y.id,persist:!1})}})}var rq,sq,oq,Vk=q(()=>{"use strict";Na();Tn();rq="opencode",sq=20,oq=88});import aq from"path";function Qu(n){return OP[aq.extname(n).toLowerCase()]??null}function dq(n){return Qu(n)!==null}function Yk(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(!cq.has(t))return null;let r=e[2],s=r.endsWith("==")?2:r.endsWith("=")?1:0,o=Math.floor(r.length*3/4)-s;return{mimeType:t,data:r,sizeBytes:o}}function lq(n){return Yk(n)!==null}function Mr(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function FP(n){let e=n.trim();if(e.length===0)return null;let t=[],r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]??"");)r++;if(r>=e.length)break;let s=e[r],o="";if(s==="'"||s==='"'){let a=s;for(r++;r<e.length&&e[r]!==a;)o+=e[r],r++;if(r>=e.length)return null;r++}else for(;r<e.length&&!/\s/.test(e[r]??"");)e[r]==="\\"&&r+1<e.length?(o+=e[r+1],r+=2):(o+=e[r],r++);if(o.startsWith("data:")){if(!lq(o))return null;t.push(o);continue}let i=o;if(i.startsWith("file://")&&(i=decodeURI(i.slice(7))),!i.startsWith("/")||!dq(i))return null;t.push(i)}return t.length>0?t:null}var Zs,OP,cq,Um=q(()=>{"use strict";Zs=10*1024*1024,OP={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};cq=new Set(Object.values(OP))});import{spawn as uq}from"child_process";import Qk from"fs/promises";import fq from"os";import pq from"path";async function jm(n={}){let e={...Xk,...n};return e.platform==="darwin"?yq(e):e.platform==="linux"?wq(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function DP(n={}){let e={...Xk,...n},t,r;if(e.platform==="darwin")t="pbpaste",r=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Xc(e,"wl-paste"))t="wl-paste",r=["--primary","-n"];else if(e.env.DISPLAY&&await Xc(e,"xclip"))t="xclip",r=["-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 s=await Xu(e.spawn,t,r);return s.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Zk(s.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Zc(n,e={}){let{target:t="both",...r}=e,s={...Xk,...r},o=await hq(s,n,t);if(o.ok)return o;let i=mq(s,n,t);return i.ok||i.reason!==BP?i:o}async function hq(n,e,t){let r=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await Wm(n.spawn,"pbcopy",[],r),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(n.platform==="linux"){let s=t==="clipboard"||t==="both",o=t==="primary"||t==="both";return n.env.WAYLAND_DISPLAY&&await Xc(n,"wl-copy")?NP(n,r,"wl-copy",[],["--primary"],s,o):n.env.DISPLAY&&await Xc(n,"xclip")?NP(n,r,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],s,o):{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 NP(n,e,t,r,s,o,i){let a=t;if(o){try{await Wm(n.spawn,t,r,e)}catch{return{ok:!1,reason:`${t} failed`}}if(i)try{await Wm(n.spawn,t,s,e)}catch{}return{ok:!0,method:a}}try{return await Wm(n.spawn,t,s,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function mq(n,e,t){let r=Buffer.from(e,"utf-8").toString("base64");if(r.length>LP)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${r.length} > ${LP} bytes)`};let o=`\x1B]52;${t==="both"?"cp":t==="primary"?"p":"c"};${r}\x07`;return n.env.TMUX&&(o=`\x1BPtmux;${o.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(n.ttyWrite??gq)(o)?{ok:!0,method:"osc52"}:{ok:!1,reason:BP}}function gq(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 yq(n){let e=pq.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"],r=[];for(let s of t)r.push("-e",s);try{await HP(n.spawn,"osascript",r);let s=await xq(e,!0);if(s.ok||s.reason.startsWith("clipboard image is"))return s}catch{await Qk.unlink(e).catch(()=>{})}try{let s=await Xu(n.spawn,"pbpaste",[]);return s.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Zk(s.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function wq(n){let e=await bq(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await Sq(n,e),r=vq(t);if(r)try{let s=await Xu(n.spawn,e.cmd,e.imageArgs(r));if(s.length>0)return s.length>Zs?{ok:!1,reason:`clipboard image is ${Mr(s.length)}, max ${Mr(Zs)}`}:{ok:!0,kind:"image",attachment:{mimeType:r,data:s.toString("base64"),sizeBytes:s.length}}}catch{}try{let s=await Xu(n.spawn,e.cmd,e.textArgs);return s.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Zk(s.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function bq(n){return n.env.WAYLAND_DISPLAY&&await Xc(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Xc(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function vq(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of kq)if(e.has(t))return t;return null}async function Sq(n,e){try{return(await Xu(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
|
|
237
237
|
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}}function Zk(n){return n.replace(/\r\n?/g,`
|
|
238
|
-
`)}async function Xc(n,e){try{return await HP(n.spawn,"which",[e]),!0}catch{return!1}}async function xq(n,e){try{let t=await Qk.readFile(n);return e&&await Qk.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>
|
|
238
|
+
`)}async function Xc(n,e){try{return await HP(n.spawn,"which",[e]),!0}catch{return!1}}async function xq(n,e){try{let t=await Qk.readFile(n);return e&&await Qk.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>Zs?{ok:!1,reason:`clipboard image is ${Mr(t.length)}, max ${Mr(Zs)}`}:{ok:!0,kind:"image",attachment:{mimeType:Qu(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function HP(n,e,t){return new Promise((r,s)=>{let o=n(e,t);o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",s),o.on("close",i=>{i===0?r():s(new Error(`${e} exited ${i}`))})})}function Wm(n,e,t,r){return new Promise((s,o)=>{let i=n(e,t,{stdio:["pipe","ignore","ignore"]});i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",o),i.on("close",d=>{d===0?s():o(new Error(`${e} exited ${d}`))});let a=i.stdin;if(!a){o(new Error(`${e} has no stdin`));return}a.on("error",o),a.end(r)})}function Xu(n,e,t){return new Promise((r,s)=>{let o=n(e,t),i=[],a=o.stdout===null,d=null,c=!1,l=()=>{c||!a||d===null||(c=!0,d===0?r(Buffer.concat(i)):s(new Error(`${e} exited ${d}`)))};o.stdout?.on("data",u=>{i.push(typeof u=="string"?Buffer.from(u):u)}),o.stdout?.on("end",()=>{a=!0,l()}),o.stderr?.on("data",()=>{}),o.on("error",u=>{c||(c=!0,s(u))}),o.on("close",u=>{d=u??0,l()})})}var Xk,LP,BP,kq,qm=q(()=>{"use strict";Um();Xk={platform:process.platform,env:process.env,spawn:uq,tmpdir:fq.tmpdir};LP=74994;BP="no TTY available for OSC 52 clipboard write";kq=["image/png","image/jpeg","image/gif","image/webp"]});function Aq(n,e){return`[pasted #${n} +${e} lines]`}var UP,Iq,Cq,Rq,Zu,ev,Tq,Mo,zm=q(()=>{"use strict";Du();UP=bk([["ctrl-x","ctrl-e","ctrl-x-ctrl-e"]],kk),Iq=10,Cq=500,Rq=/\[pasted #(\d+) \+\d+ lines\]/g,Zu=/\[pasted #(\d+) \+\d+ lines\]$/,ev=/^\[pasted #(\d+) \+\d+ lines\]/;Tq=500,Mo=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>Tq&&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,r){this.recordEdit();let s=this.currentLine(),o=Math.max(0,Math.min(e,s.length)),i=Math.max(o,Math.min(t,s.length));this.setCurrentLine(s.slice(0,o)+r+s.slice(i)),this.col=o+r.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(`
|
|
239
239
|
`).length;if(this.collapsePastes&&t>Iq){let r=this.nextPasteId++;this.pastes.set(r,e.text),this.insertText(Aq(r,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?this.row>0&&(this.row-=1):this.col=0,[];case"ctrl-e":return this.col===this.currentLine().length?this.row<this.buffer.length-1&&(this.row+=1,this.col=this.currentLine().length):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[];case"ctrl-x-ctrl-e":return[{type:"edit-in-editor"}];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(`
|
|
240
240
|
`)}expandPastes(e){return e.replace(Rq,(t,r)=>{let s=parseInt(r,10),o=this.pastes.get(s);return o!==void 0?o:t})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=Cq?(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(`
|
|
241
241
|
`)){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(`
|
|
@@ -246,10 +246,10 @@ failed to spawn ${e.command}: ${a.message}
|
|
|
246
246
|
`+t,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let r=e.slice(0,this.col).match(Zu);if(r!==null){this.killBuffer=r[0];let i=this.col-r[0].length;this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i;return}let s=this.col;for(;s>0&&/\s/.test(e[s-1]??"");)s-=1;for(;s>0&&!/\s/.test(e[s-1]??"");)s-=1;let o=e.slice(s,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,s)+e.slice(this.col)),this.col=s}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let r=e.slice(0,this.col).match(Zu);if(r!==null){this.killBuffer=r[0];let a=this.col-r[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let s=/[A-Za-z0-9_]/,o=this.col;for(;o>0&&!s.test(e[o-1]??"");)o-=1;for(;o>0&&s.test(e[o-1]??"");)o-=1;let i=e.slice(o,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let t=this.currentLine().slice(0,this.col).match(Zu);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 r=e.slice(this.col).match(ev);if(r!==null){this.col+=r[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 s=e.slice(0,t).match(Zu);if(s!==null){this.col=t-s[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 s=e.slice(t).match(ev);if(s!==null){this.col=t+s[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 s=e.query,o=e.savedDraft;return this.historySearch=null,this.buffer=[...o.buffer],this.row=o.row,this.col=o.col,[{type:"escalate-search",query:s}]}e.cursor+=1;let r=e.matchIndices[e.cursor];return this.loadEntry(this.history[r]??""),[]}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 r=this.historySearch.savedDraft;return this.buffer=[...r.buffer],this.row=r.row,this.col=r.col,[]}let t=this.findHistoryMatches(e);if(t.length===0){let r=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...r.buffer],this.row=r.row,this.col=r.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 r=this.history.length-1;r>=0;r--){let s=this.history[r]??"";(e.length===0||s.toLowerCase().includes(e))&&t.push(r)}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(`
|
|
247
247
|
`),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 o=this.queueIndex,i=[...this.attachments];return this.clearBuffer(),t.trim().length===0?[{type:"queue-remove",index:o}]:[{type:"queue-edit",index:o,text:t,displayText:e,attachments:i}]}if(t.trim().length===0&&this.attachments.length===0)return[];let r=this.planMode,s=[...this.attachments];return this.clearBuffer(),[{type:"send",text:t,displayText:e,planMode:r,attachments:s}]}amend(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=this.planMode,a=[...this.attachments],d=t.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{type:"queue-remove",index:o}]:[{type:"queue-remove",index:o},{type:"amend",text:t,displayText:e,planMode:i,attachments:a}]}if(t.trim().length===0&&this.attachments.length===0)return[];let r=this.planMode,s=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:t,displayText:e,planMode:r,attachments:s}]}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"}]}}});function Pq(){let n=Eq.map(e=>{let t=process.listeners(e);for(let s of t)process.off(e,s);let r=()=>{};return process.on(e,r),{signal:e,listeners:t,noop:r}});return()=>{for(let{signal:e,listeners:t,noop:r}of n){process.off(e,r);for(let s of t)process.on(e,s)}}}async function Km(n,e){let t=e.write??(o=>{process.stdout.write(o)}),r=Pq();e.suspend(),t(tE),n.banner!==void 0&&t(n.banner);let s=e.spawn??(await import("child_process")).spawn;return await new Promise(o=>{let i=!1,a=d=>{if(!i){i=!0;try{e.resume()}finally{r()}d.error?e.notify?.(`${n.program} failed: ${d.error.message}`):d.exitCode!==null&&d.exitCode!==0&&e.notify?.(`${n.program} exited ${d.exitCode}`),o(d)}};try{let d=s(n.program,n.args,{stdio:"inherit",cwd:n.cwd});d.on("exit",c=>a({exitCode:c})),d.on("error",c=>a({exitCode:null,error:c}))}catch(d){a({exitCode:null,error:d})}})}var Eq,tv=q(()=>{"use strict";Fa();Eq=process.platform==="win32"?["SIGINT"]:["SIGINT","SIGQUIT"]});import{mkdtempSync as Mq,readFileSync as _q,rmSync as $q,writeFileSync as Oq}from"fs";import{tmpdir as Fq}from"os";import{join as WP}from"path";function Lq(n=process.env){let e=[n.HYDRA_EDITOR,n.VISUAL,n.EDITOR].find(r=>r!==void 0&&r.trim()!=="");if(e===void 0)return null;let t=e.split(/\s+/).filter(r=>r.length>0);return t.length>0?t:null}async function Gm(n,e){let t=Lq(e.env);if(t===null)return e.notify?.("no $HYDRA_EDITOR, $VISUAL or $EDITOR set \u2014 nothing to edit with"),null;let[r,...s]=t,o=Mq(WP(Fq(),"hydra-acp-edit-")),i=WP(o,"prompt.md");Oq(i,n,"utf8");try{let a={program:r,args:[...s,i],banner:`\u2500 ${r} \u2014 save and quit to return to hydra \u2500
|
|
248
248
|
`},c=await(e.runForeground??Km)(a,e);if(c.error||c.exitCode!==null&&c.exitCode!==0)return null;let l=_q(i,"utf8");return l.endsWith(`
|
|
249
|
-
`)?l.slice(0,-1):l}finally{$q(o,{recursive:!0,force:!0})}}var nv=q(()=>{"use strict";tv()});var el,Jm,rv=q(()=>{"use strict";el=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,r,s){if(e<1||e>this.term.height)return!1;let o=s?.region,i=o===void 0?String(e):`${o}:${e}`;return this.lastFrameRows.get(i)===t?!1:(this.lastFrameRows.set(i,t),this.term.moveTo(s?.column??1,e),r(),this.term.styleReset(),s?.erase!==!1&&this.term.eraseLineAfter(),!0)}},Jm=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 r=Date.now()-this.lastRepaintAt;if(r>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-r))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});var jP,qP=q(()=>{"use strict";jP=["toggle-mode","switch-session","show-help","detach","toggle-options","rename-session","choose-model","choose-agent","choose-mode","copy","open","open-session","none"]});import Nq from"ansi-regex";import ps from"string-width";function fs(n){let e=0;for(let t of n)e+=ps(t.text);return e}function Vm(n,e){let t=[];for(let r of n){if(t.length>0){let s=r.separator??e.separator;s.length>0&&t.push({text:s,token:e.separatorToken})}t.push(...r.chunks)}return t}function KP(n,e){let t=fs(n)-e;if(t<=0)return n;let r=n.map(o=>({...o})),s=r.map((o,i)=>({c:o,i})).filter(({c:o})=>o.flex===!0&&o.truncatable!==!1).map(({i:o})=>o);for(;t>0&&s.length>0;){let o=-1,i=0;for(let l of s){let u=r[l];if(u===void 0)continue;let f=ps(u.text)-(u.minWidth??0);f>i&&(i=f,o=l)}if(o<0)break;let a=r[o];if(a===void 0)break;let d=Math.min(t,i),c=ps(a.text)-d;a.text=Ym(a.text,c),t-=d}return r}function Dq(n){let e=[];zP.lastIndex=0;let t=0,r;for(;(r=zP.exec(n))!==null;)r.index>t&&e.push({text:n.slice(t,r.index),ansi:!1}),e.push({text:r[0],ansi:!0}),t=r.index+r[0].length;return t<n.length&&e.push({text:n.slice(t),ansi:!1}),e}function Ym(n,e){if(e<=0)return"";if(ps(n)<=e)return n;if(e===1)return"\u2026";let t="",r=0;e:for(let s of Dq(n)){if(s.ansi){t+=s.text;continue}for(let o of s.text){let i=ps(o);if(r+i>e-1)break e;t+=o,r+=i}}return t+"\u2026"}function GP(n,e){let t=[],r=0;for(let s of n){let o=e-r;if(o<=0)break;let i=ps(s.text);if(i<=o)t.push(s),r+=i;else{if(s.truncatable===!1)break;t.push({...s,text:Ym(s.text,o)});break}}return t}function sv(n,e,t,r){let s=ps(r.prefix)+ps(r.suffix),o=ps(r.pad),i=[...e],a=[...t],d=A=>{let _=0;for(let P of A){let $=ps(P.text);_+=P.flex===!0?Math.min($,P.minWidth??0):$}return _},c=()=>{let A=Vm(i,r),_=Vm(a,r);return s+(A.length>0?d(A)+o*2:0)+(_.length>0?d(_)+o*2:0)+r.minGap};for(;c()>n;){let A=null,_=-1,P=1/0;if(i.forEach(($,F)=>{$.priority<P&&(P=$.priority,A="l",_=F)}),a.forEach(($,F)=>{$.priority<P&&(P=$.priority,A="r",_=F)}),A===null||P===1/0)break;A==="l"?i=i.filter(($,F)=>F!==_):a=a.filter(($,F)=>F!==_)}let l=Vm(i,r),u=Vm(a,r),f=s+(l.length>0?o*2:0)+(u.length>0?o*2:0)+r.minGap,p=Math.max(0,n-f),m=fs(u);fs(l)+m>p&&(l=KP(l,Math.max(0,p-m))),fs(l)+fs(u)>p&&(u=KP(u,Math.max(0,p-fs(l)))),fs(l)+fs(u)>p&&(u=GP(u,p),l=GP(l,Math.max(0,p-fs(u))));let h=[],g=[],w=1,b=(A,_,P)=>{if(A.length===0)return;let $=ps(A),F={...P??{},text:A,token:_,start:w,width:$};if(h.push(F),F.id!==void 0){let J=g.find(Y=>Y.id===F.id);J!==void 0?J.end=w+$-1:g.push({id:F.id,start:w,end:w+$-1,action:F.action??"none",doubleAction:F.doubleAction??"none",value:F.value??F.text})}w+=$};if(b(r.prefix,r.ruleToken),l.length>0){b(r.pad,r.padToken);for(let A of l)b(A.text,A.token,A);b(r.pad,r.padToken)}let k=s+(l.length>0?fs(l)+o*2:0)+(u.length>0?fs(u)+o*2:0),S=Math.max(r.minGap,n-k);S>0&&r.fill.length>0&&b(r.fill.repeat(S),r.ruleToken);let I=null;if(u.length>0){I=w,b(r.pad,r.padToken);for(let A of u)b(A.text,A.token,A);b(r.pad,r.padToken)}b(r.suffix,r.ruleToken);let x=h.map(A=>`${A.token}${A.text}`).join("\0");return{chunks:h,signature:x,hits:g,rightStart:I}}var zP,JP,Qm=q(()=>{"use strict";qP();zP=Nq(),JP=jP});function ov(n){return n.banner.status==="ready"&&n.banner.armedSince!==void 0}function Bq(n){let e=n.banner.status,t=e==="busy"&&n.banner.stalled===!0,r;n.statusLabel!==void 0?r=n.statusLabel:t?r="Stalled":e==="busy"?r="Thinking":ov(n)?r="Waiting":r=e.charAt(0).toUpperCase()+e.slice(1);let s;return t||e==="disconnected"?s="status-alert":e==="busy"||ov(n)?s="status-active":e==="cold"?s="status-cold":s="status-ready",{label:r,token:s}}function Zs(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:String(n)}function Hq(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${Zs(n.used)}/${Zs(n.size)}`):e.push(Zs(n.used)):typeof n.size=="number"&&e.push(`/${Zs(n.size)}`),typeof n.costAmount=="number"&&e.push(Qh(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Uq(n){if(n.banner.hintsExhausted===!0&&!n.hintsRevealed)return null;let e=n.banner.hint;return e.length===0?null:e.map((t,r)=>{let o={text:t.id==="mode"&&(n.banner.currentMode??"")!==""?`${t.label}: ${n.banner.currentMode}`:t.label,token:"modal-hint",action:t.action};return{id:t.id,chunks:[o],priority:20+(e.length-r)}})}function VP(n){if(n.transient===null)return null;let e=n.transient.kind==="search"?"bar-indicator":"modal-note";return{id:"transient",chunks:[{text:n.transient.text,token:e}],priority:1/0}}var iv,wne,Xm=q(()=>{"use strict";Hb();ke();ir();To();iv={status:{priority:1/0,resolve:n=>{let{label:e,token:t}=Bq(n);return[{text:e,token:t}]}},elapsed:{priority:60,resolve:n=>{if(ov(n)){let r=Date.now()-n.banner.armedSince;return r<1e3?null:[{text:Pr(r),token:"status-active"}]}if(n.banner.status!=="busy"||n.banner.elapsedMs===void 0||n.banner.elapsedMs<1e3)return null;let t=n.banner.stalled===!0?"status-alert":"status-active";return[{text:Pr(n.banner.elapsedMs),token:t}]}},sessionId:{priority:40,resolve:n=>{let e=st(n.session.sessionId);if(!e)return null;let t={text:e,token:"rule-meta",doubleAction:"copy",value:e};return n.scope==="btw"&&(t.action="open-session"),[t]}},sessionIdFull:{priority:40,resolve:n=>n.session.sessionId?[{text:n.session.sessionId,token:"rule-meta",doubleAction:"copy"}]:null},queued:{priority:50,resolve:n=>n.banner.queued>0?[{text:`${n.banner.queued} queued`,token:"status-queued"}]:null},scroll:{priority:30,resolve:n=>n.scrollOffset>0?[{text:`\u2191 ${n.scrollOffset}`,token:"bar-indicator"}]:null},usage:{priority:45,resolve:n=>{let e=Hq(n.session.usage);return e?[{text:e,token:"content",doubleAction:"copy"}]:null}},tokens:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.used!="number"?null:[{text:typeof e.size=="number"&&e.size>0?`${Zs(e.used)}/${Zs(e.size)}`:Zs(e.used),token:"content",doubleAction:"copy"}]}},cost:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.costAmount!="number"?null:[{text:Qh(e.costAmount,e.costCurrency),token:"content",doubleAction:"copy"}]}},cwd:{priority:70,resolve:()=>null,resolveGroups:n=>{let e=n.session.workspace;if(e===void 0){let r=V(n.session.cwd);return r?[{id:"cwd",priority:70,chunks:[{text:r,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:n.session.cwd}]}]:null}let t=V(e.sourceCwd);return t?[{id:"cwd",priority:70,chunks:[{text:t,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:e.sourceCwd}]},{id:"cwdWorkspace",priority:69,separator:" ",chunks:[{text:`[${e.label}]`,token:"bar-text",doubleAction:"open",value:e.path}]}]:null}},cwdFull:{priority:70,resolve:n=>n.session.cwd?[{text:n.session.cwd,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open"}]:null},title:{priority:75,resolve:n=>{let e=n.session.title?.trim();return e?[{text:e,token:"bar-text",flex:!0,minWidth:8,doubleAction:"rename-session",value:e}]:null}},agent:{priority:80,resolve:n=>n.session.agent?[{text:n.session.agent,token:"content",doubleAction:"choose-agent"}]:null},model:{priority:65,resolve:n=>n.session.model?[{text:n.session.model,token:"content",doubleAction:"choose-model"}]:null},agentModel:{priority:80,resolve:n=>{let e=DT(n.session.agent,n.session.model);return e?[{text:e,token:"content",flex:!0,minWidth:6,doubleAction:"choose-model",value:e}]:null}},mode:{priority:55,resolve:n=>n.banner.currentMode?[{text:n.banner.currentMode,token:"rule-meta",doubleAction:"choose-mode",value:"mode"}]:null},helpHint:{priority:20,resolve:()=>null,resolveGroups:Uq}},wne=Object.keys(iv)});function YP(n){return typeof n=="string"?n===av?null:n:n.field??null}function QP(n,e,t){if(!t.some(a=>a===av))return t;let r=new Set;for(let a of t){let d=YP(a);d!==null&&r.add(d)}let s=Wq[n][e].filter(a=>{let d=YP(a);return d===null||!r.has(d)}),o=[],i=!1;for(let a of t){if(a===av){i||(o.push(...s),i=!0);continue}o.push(a)}return o}function qq(n){if(typeof n!="string")return n;let t=jq.exec(n)?.[1];return t!==void 0?{script:t}:{field:n}}function XP(n){if(n!==void 0)return JP.includes(n)?n:"none"}function zq(n,e){let t=`${n}:${e.id}`;return{...e,chunks:e.chunks.map(r=>({...r,id:t}))}}function Kq(n,e){let t=n;if(e.style!==void 0){let r=e.style;t=t.map(s=>({...s,token:r}))}if(e.minWidth!==void 0&&(t=t.map(r=>({...r,flex:!0,minWidth:e.minWidth}))),e.maxWidth!==void 0){let r=e.maxWidth;if(t=t.map(s=>({...s,text:Ym(s.text,r)})).filter(s=>s.text.length>0),t.length===0)return null}return e.truncate===!1&&(t=t.map(r=>({...r,truncatable:!1}))),t}function Gq(n,e){let t=n.map(o=>({...o,chunks:[...o.chunks]})),r=t[0];if(e.prefix!==void 0&&e.prefix.length>0&&r!==void 0){let o=r.chunks[0];o!==void 0&&r.chunks.unshift({text:e.prefix,token:o.token})}let s=t[t.length-1];if(e.suffix!==void 0&&e.suffix.length>0&&s!==void 0){let o=s.chunks[s.chunks.length-1];o!==void 0&&s.chunks.push({text:e.suffix,token:o.token})}return t}function ef(n,e,t){let r=[];for(let s of e){let o=qq(s),i;if(o.text!==void 0){if(o.text.length===0)continue;i=[{id:`text:${o.text}`,priority:10,chunks:[{text:o.text,token:"rule-meta"}]}]}else if(o.script!==void 0){let u=t.scriptOutputs.get(o.script);if(u===void 0||u.length===0)continue;i=[{id:`script:${o.script}`,priority:10,chunks:[{text:u,token:"rule-meta"}]}]}else{let u=o.field??"",f=iv[u];if(f===void 0)continue;if(f.resolveGroups!==void 0){let p=f.resolveGroups(t);if(p===null)continue;i=p}else{let p=f.resolve(t);if(p===null||p.length===0)continue;i=[{id:u,priority:f.priority,chunks:p}]}}let a=[];for(let u of i){let f=Kq(u.chunks,o);f!==null&&a.push({...u,priority:o.priority??u.priority,chunks:f})}if(a.length===0)continue;a=Gq(a,o);let d=XP(o.onClick),c=XP(o.onDoubleClick);(d!==void 0||c!==void 0)&&(a=a.map(u=>({...u,chunks:u.chunks.map(f=>({...f,...d!==void 0?{action:d}:{},...c!==void 0?{doubleAction:c}:{}}))})));let l=a[0];o.separator!==void 0&&l!==void 0&&(l.separator=o.separator);for(let u of a)r.push(zq(n,u))}return r}function tf(n){let e=(t,r)=>({left:QP(t,"left",r.left),right:QP(t,"right",r.right)});return{composer:{top:e("composerTop",n.composer.top),bottom:e("composerBottom",n.composer.bottom)},sessionbar:e("sessionbar",n.sessionbar)}}var dv,av,Wq,jq,cv=q(()=>{"use strict";rt();Xm();Qm();Qm();dv={composerTop:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},composerBottom:{prefix:"",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},btw:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},sessionbar:{prefix:"",suffix:"",fill:" ",pad:"",separator:" \xB7 ",separatorToken:"content",ruleToken:"content",padToken:"content",minGap:1}},av="...",Wq={composerTop:{left:Qi,right:Xi},btw:{left:Qi,right:Xi},composerBottom:{left:Fd,right:Ld},sessionbar:{left:Nd,right:Dd}};jq=/^\$\((.+)\)\s*$/});import{resolve as Jq}from"path";function uv(n){return!Vq.has(n)}function Yq(n){return n.replace(/\s+/gu," ").trim()}function Qq(n,e,t){let r=n.trim();for(let s of[e,t]){if(s===void 0||s==="")continue;let o=r.toLowerCase(),i=s.toLowerCase();if(o===i)return"";o.startsWith(`${i} `)&&(r=r.slice(s.length).trimStart())}return r}function Xq(n){let e=n.trim();return e===""?!0:!/[\s/.]/u.test(e)}function Zq(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 ZP}}function ez(n,e){if(!uv(n.status))return null;let t=Zq(n.rawKind),r=c=>c===void 0?"":Qq(Yq(c),t,n.rawKind),s=n.editDiff?.path??Ip(n.locations),o=s===void 0||s===""?void 0:e===null?s:Jq(e,s),i=r(n.latestTitle),a=t!==ZP&&Xq(i)?"":i,d=r(n.detail)||tz(o)||a;return{verb:t,detail:d===""?void 0:d,startedAt:n.startedAt,path:o}}function tz(n){return n===void 0?"":n.split(/[\\/]/).filter(t=>t!=="").at(-1)??""}function eM(n,e,t){let r=[];for(let s of n){let o=e.get(s);if(o===void 0||vc(s,o.latestTitle))continue;let i=ez(o,t);i!==null&&r.push(i)}return r}var lv,Vq,ZP,fv=q(()=>{"use strict";Jl();Yp();lv=4,Vq=new Set(["completed","succeeded","ok","failed","error","rejected","cancelled","canceled"]);ZP="tool"});function nf(n){let e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;return t<60?`${t}m ${String(r).padStart(2,"0")}s`:`${Math.floor(t/60)}h ${String(t%60).padStart(2,"0")}m`}function tM(n,e){return e<=0?n:Math.floor(Math.max(0,n)/e)*e}function pv(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 nz(n,e){if(e<=0)return"";let t=Math.max(0,Math.min(1,n)),r=Math.round(t*e*8),s=Math.floor(r/8),o=r%8,i=o===0?"":"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[o-1];return"\u2588".repeat(Math.min(e,s))+(s<e?i:"")+"\xB7".repeat(Math.max(0,e-s-(i?1:0)))}function _r(n,e){return{body:n,bodyStyle:e}}function Zm(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?{body:s(`${n} ${e}`,t.width),bodyStyle:"muted"}:{prefix:`${n}${" ".repeat(o)}`,prefixStyle:"muted",body:e,bodyStyle:"sidebar-value"}}function aM(n,e,t,r){let s={body:n,bodyStyle:t,openPath:e,item:!0};if(r!==void 0&&r.length>0){let o=n.indexOf(r);o!==-1&&(s.openSpan={start:o,end:o+r.length})}return s}function hs(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?s(`${n} ${e}`,t.width):`${n}${" ".repeat(o)}${e}`}function rM(n){return n==="in_progress"?0:n==="completed"?2:1}function dz(n){return[...n].sort((e,t)=>rM(e.status)-rM(t.status))}function dM(n){let e=n.map(r=>r.split("/").pop()??r),t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return n.map((r,s)=>{let o=e[s];return(t.get(o)??0)<=1?o:r.split("/").slice(-2).join("/")})}function fz(n,e,t){let{cellWidth:r,truncate:s}=t.metrics;if(e<=0)return"";if(r(n)<=e)return n;let o=n.slice(n.lastIndexOf("/")+1);if(o!==n&&r(o)<=e)return o;let i=o.length<n.length?o:n;for(let a=1;a<i.length;a++){let d=`\u2026${i.slice(a)}`;if(r(d)<=e)return d}return s(i,e)}function sM(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 iM(n){if(n===void 0)return"\u2013".padStart(oM);let e=n*100;return(e<100?`${e.toFixed(1)}%`:`${Math.round(e)}%`).padStart(oM)}var Si,nM,rz,sz,oz,iz,az,cz,lz,uz,pz,oM,hz,mz,gz,yz,wz,bz,cM,lM=q(()=>{"use strict";fv();Si=5;nM=5e3,rz={id:"activity",relevant:()=>!0,versionKey:n=>n.busySince!==null?`busy:${Math.floor((n.now-n.busySince)/1e3)}`:n.armedSince!==null?`running:${Math.floor((n.now-n.armedSince)/1e3)}`:n.lastTurnEndedAt!==null?`idle:${tM(n.now-n.lastTurnEndedAt,nM)}`:"fresh",render:(n,e)=>n.busySince!==null?[_r(hs("\u25CF thinking",nf(n.now-n.busySince),e),"status-active")]:n.armedSince!==null?[_r(hs("\u25D0 waiting",nf(n.now-n.armedSince),e),"status-active")]:n.lastTurnEndedAt!==null?[_r(hs("\u25CB idle",nf(tM(n.now-n.lastTurnEndedAt,nM)),e),"status-idle")]:[_r("\u25CB ready","status-idle")]},sz={id:"tasks",title:"tasks",relevant:n=>n.armedTasks.length>0,versionKey:(n,e)=>{let t=n.armedTasks.slice(0,Si);return`${e.width}|${n.armedTasks.length}|`+t.map(r=>{let s=Math.floor(Math.max(0,n.now-r.since)/1e3);return`${r.taskId??r.label}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[];for(let o of n.armedTasks.slice(0,Si)){let i=nf(Math.max(0,n.now-o.since)),a="\u25D0 ",d=e.width-r(a)-r(i)-1,c=o.label.length>0?o.label:o.taskType??"background task",l=d<4?a.trim():`${a}${t(c,d)}`;s.push(_r(hs(l,i,e),"status-active"))}return n.armedTasks.length>Si&&s.push(_r(` +${n.armedTasks.length-Si} more`,"muted")),s}},oz={id:"tools",title:"tools",relevant:n=>n.running.length>0,versionKey:(n,e)=>{let t=n.running.slice(0,lv);return`${e.width}|${n.running.length}|`+t.map(r=>{let s=r.startedAt===void 0?"":Math.floor(Math.max(0,n.now-r.startedAt)/1e3);return`${r.verb}:${r.detail??""}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[],o=n.running.slice(0,lv);for(let i of o){let a=i.startedAt===void 0?"":nf(Math.max(0,n.now-i.startedAt)),d=`\u25B8 ${i.verb}`,c=e.width-r(d)-(a===""?0:r(a)+1)-1,l=i.detail===void 0||c<4?"":` ${t(i.detail,c)}`,u=`${d}${l}`,f=a===""?u:hs(u,a,e),p={body:f,bodyStyle:"tool-status-running",openPath:i.path};if(i.path!==void 0){let m=i.path.slice(i.path.lastIndexOf("/")+1),h=m.length>0?f.indexOf(m):-1;h!==-1&&(p.openSpan={start:h,end:h+m.length})}s.push(p)}return n.running.length>o.length&&s.push(_r(` +${n.running.length-o.length} more`,"muted")),s}},iz={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:r,size:s,costAmount:o,costCurrency:i}=n.usage;if(r!==void 0&&s!==void 0&&s>0){let a=r/s;t.push(_r(hs(`${pv(r)}/${pv(s)}`,`${Math.round(a*100)}%`,e),a>=.9?"meter-warn":"metric")),t.push(_r(nz(a,e.width),a>=.9?"meter-warn":"meter-fill"))}else r!==void 0&&t.push(_r(hs("tokens",pv(r),e),"metric"));if(o!==void 0){let a=i==="USD"||i===void 0?"$":`${i} `;t.push(_r(hs("cost",`${a}${o.toFixed(2)}`,e),"muted"))}return t}},az={id:"queue",relevant:n=>n.queued>0,versionKey:(n,e)=>`${n.queued}/${e.width}`,render:(n,e)=>[_r(hs("queued",String(n.queued),e),"status-queued")]};cz={id:"todo",title:"todo",pageSize:Si,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,r=[];for(let s of dz(n.plan)){let o=s.status==="completed"?"\u2713":s.status==="in_progress"?"\u25B8":"\xB7",i=s.status==="completed"?"plan-done":s.status==="in_progress"?"plan":"plan-pending";r.push({body:t(`${o} ${s.content}`,e.width),bodyStyle:i,item:!0})}return r}};lz={id:"files",title:"edited",pageSize:Si,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:r}=e.metrics,s=[...n.editedFiles].reverse(),o=[],i=dM(s.map(a=>a.path));return s.forEach((a,d)=>{let c=a.added!==void 0||a.removed!==void 0?`+${a.added??0} -${a.removed??0}`:"",l=e.width-(c?r(c)+1:0),u=t(i[d],Math.max(1,l));o.push(aM(c?hs(u,c,e):u,a.path,"file-path",u))}),o}},uz={id:"git",title:"git",pageSize:Si,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 r=t.files.map(s=>`${s.state}:${s.path}`).join("\0");return`${e.width}|${t.branch}|${t.staged}|${t.unstaged}|${t.untracked}|${t.ahead}|${t.behind}|${r}`},render:(n,e)=>{let t=n.git;if(t===null)return[];let{truncate:r,cellWidth:s}=e.metrics,o=[];if(t.branch!==null){let d=(t.ahead>0?`\u2191${t.ahead}`:"")+(t.behind>0?`\u2193${t.behind}`:"");o.push(d?Zm(r(t.branch,e.width-d.length-1),d,e):{body:r(t.branch,e.width)})}let i=t.files,a=dM(i.map(d=>d.path));return i.forEach((d,c)=>{let l=d.state==="staged"?"git-staged":d.state==="dirty"?"git-dirty":"git-untracked",u=e.width-s(d.state)-1,f=r(a[c],Math.max(1,u));o.push(aM(hs(f,d.state,e),d.path,l,f))}),o}};pz={id:"info",title:"info",relevant:n=>n.agent!==null||n.model!==null||n.sessionId!==null||n.workspace!==null,versionKey:(n,e)=>`${e.width}|${n.agent}|${n.model}|${n.mode}|${n.sessionId}|${n.host}|${n.workspace?.label??""}`,render:(n,e)=>{let{cellWidth:t}=e.metrics,r=[],s=(o,i,a)=>{let d=e.width-t(o)-1,c=Zm(o,fz(i,d,e),e);r.push(a===void 0?c:{...c,doubleAction:a})};if(n.agent!==null&&s("agent",n.agent,{action:"choose-agent",value:"agent"}),n.model!==null&&s("model",n.model,{action:"choose-model",value:"model"}),n.mode!==null&&s("mode",n.mode,{action:"choose-mode",value:"mode"}),n.host!==null&&s("host",n.host,{action:"copy",value:n.host}),n.sessionId!==null&&s("id",n.sessionId,{action:"copy",value:n.sessionId}),n.workspace!==null){let o=Zm("workspace",n.workspace.label,e);r.push({...o,openPath:n.workspace.path})}return r}};oM=5;hz="\u25CF",mz="\u25D0",gz="\u25CB",yz="\u25E6",wz={id:"sessions",title:"sessions",pageSize:Si,relevant:n=>n.liveSessions.length>0,titleNote:(n,e,t)=>{if(!t)return;let r=n.liveSessions.filter(s=>s.blocked).length;return r>0?`${r} blocked`:`${n.liveSessions.length} live`},versionKey:(n,e)=>`${e.width}|`+n.liveSessions.map(t=>`${t.blocked?"w":""}${t.busy?"b":""}${t.armed?"r":""}:${t.sessionId}:${t.label}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=i=>(i.blocked?0:3)+(i.busy?0:i.armed?1:2);return[...n.liveSessions].sort((i,a)=>s(i)-s(a)).map(i=>{let a=i.busy||i.armed,d=`${i.blocked?yz:" "}${i.busy?hz:i.armed?mz:gz}`,c=r(d),l=t(i.label,Math.max(1,e.width-c-1)),u=Math.max(1,e.width-r(l)-c);return{prefix:`${l}${" ".repeat(u)}`,prefixStyle:a?"status-active":"sidebar-value",body:d,bodyStyle:a?"status-active":i.blocked?"status-blocked":"status-idle",doubleAction:{action:"open-session",value:i.sessionId},item:!0}})}},bz={id:"resources",title:"resources",relevant:n=>n.resources.length>0,versionKey:(n,e)=>`${e.width}|`+n.resources.map(t=>`${t.label}:${sM(t.rssBytes)}:${iM(t.cpuFraction)}:${t.processes}`).join("\0"),render:(n,e)=>{let{cellWidth:t,truncate:r}=e.metrics;return n.resources.map(s=>{let o=`${sM(s.rssBytes)} ${iM(s.cpuFraction)}`,i=s.processes>1?`${s.label} \xD7${s.processes}`:s.label,a=e.width-t(o)-1;return Zm(r(i,Math.max(1,a)),o,e)})}},cM=[rz,sz,iz,az,cz,lz,uz,wz,bz,pz,oz]});function vz(n){let e="",t=[],r=0;for(;r<n.length;){let s=n[r];if(s==="["){let o=n.indexOf("]",r+1);if(o!==-1&&n[o+1]==="("&&o>r+1){let i=-1,a=1,d=o+2;for(;d<n.length;){let c=n[d];if(c==="\\"&&d+1<n.length){d+=2;continue}if(c==="(")a+=1;else if(c===")"&&(a-=1,a===0)){i=d;break}d+=1}if(i!==-1&&i>o+2){let c=n.slice(r+1,o),l=n.slice(o+2,i),u=e.length;e+=c,t.push({start:u,end:e.length,url:l}),r=i+1;continue}}}e+=s,r+=1}return{body:e,links:t}}function uM(n){let e=zt(n).trim();return e.length===0?null:e}function Sz(n){return typeof n!="string"}function eg(n){return typeof n=="string"?n:n.id}function tg(n){return n.filter(Sz)}function hv(n,e){let t=new Map;for(let r of tg(n)){let s=r.refreshMs??e,o=t.get(r.script);t.set(r.script,o===void 0?s:Math.min(o,s))}return t}function fM(n){return{id:n.id,title:n.title??n.id,relevant:e=>e.processOutputs.has(n.script),versionKey:(e,t)=>`${t.width}:${e.processOutputs.get(n.script)??""}`,render:(e,t)=>{let r=e.processOutputs.get(n.script);if(r===void 0)return[];let{truncate:s}=t.metrics,o=r.split(`
|
|
249
|
+
`)?l.slice(0,-1):l}finally{$q(o,{recursive:!0,force:!0})}}var nv=q(()=>{"use strict";tv()});var el,Jm,rv=q(()=>{"use strict";el=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,r,s){if(e<1||e>this.term.height)return!1;let o=s?.region,i=o===void 0?String(e):`${o}:${e}`;return this.lastFrameRows.get(i)===t?!1:(this.lastFrameRows.set(i,t),this.term.moveTo(s?.column??1,e),r(),this.term.styleReset(),s?.erase!==!1&&this.term.eraseLineAfter(),!0)}},Jm=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 r=Date.now()-this.lastRepaintAt;if(r>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-r))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});var jP,qP=q(()=>{"use strict";jP=["toggle-mode","switch-session","show-help","detach","toggle-options","rename-session","choose-model","choose-agent","choose-mode","copy","open","open-session","none"]});import Nq from"ansi-regex";import ps from"string-width";function fs(n){let e=0;for(let t of n)e+=ps(t.text);return e}function Vm(n,e){let t=[];for(let r of n){if(t.length>0){let s=r.separator??e.separator;s.length>0&&t.push({text:s,token:e.separatorToken})}t.push(...r.chunks)}return t}function KP(n,e){let t=fs(n)-e;if(t<=0)return n;let r=n.map(o=>({...o})),s=r.map((o,i)=>({c:o,i})).filter(({c:o})=>o.flex===!0&&o.truncatable!==!1).map(({i:o})=>o);for(;t>0&&s.length>0;){let o=-1,i=0;for(let l of s){let u=r[l];if(u===void 0)continue;let f=ps(u.text)-(u.minWidth??0);f>i&&(i=f,o=l)}if(o<0)break;let a=r[o];if(a===void 0)break;let d=Math.min(t,i),c=ps(a.text)-d;a.text=Ym(a.text,c),t-=d}return r}function Dq(n){let e=[];zP.lastIndex=0;let t=0,r;for(;(r=zP.exec(n))!==null;)r.index>t&&e.push({text:n.slice(t,r.index),ansi:!1}),e.push({text:r[0],ansi:!0}),t=r.index+r[0].length;return t<n.length&&e.push({text:n.slice(t),ansi:!1}),e}function Ym(n,e){if(e<=0)return"";if(ps(n)<=e)return n;if(e===1)return"\u2026";let t="",r=0;e:for(let s of Dq(n)){if(s.ansi){t+=s.text;continue}for(let o of s.text){let i=ps(o);if(r+i>e-1)break e;t+=o,r+=i}}return t+"\u2026"}function GP(n,e){let t=[],r=0;for(let s of n){let o=e-r;if(o<=0)break;let i=ps(s.text);if(i<=o)t.push(s),r+=i;else{if(s.truncatable===!1)break;t.push({...s,text:Ym(s.text,o)});break}}return t}function sv(n,e,t,r){let s=ps(r.prefix)+ps(r.suffix),o=ps(r.pad),i=[...e],a=[...t],d=A=>{let _=0;for(let P of A){let $=ps(P.text);_+=P.flex===!0?Math.min($,P.minWidth??0):$}return _},c=()=>{let A=Vm(i,r),_=Vm(a,r);return s+(A.length>0?d(A)+o*2:0)+(_.length>0?d(_)+o*2:0)+r.minGap};for(;c()>n;){let A=null,_=-1,P=1/0;if(i.forEach(($,F)=>{$.priority<P&&(P=$.priority,A="l",_=F)}),a.forEach(($,F)=>{$.priority<P&&(P=$.priority,A="r",_=F)}),A===null||P===1/0)break;A==="l"?i=i.filter(($,F)=>F!==_):a=a.filter(($,F)=>F!==_)}let l=Vm(i,r),u=Vm(a,r),f=s+(l.length>0?o*2:0)+(u.length>0?o*2:0)+r.minGap,p=Math.max(0,n-f),m=fs(u);fs(l)+m>p&&(l=KP(l,Math.max(0,p-m))),fs(l)+fs(u)>p&&(u=KP(u,Math.max(0,p-fs(l)))),fs(l)+fs(u)>p&&(u=GP(u,p),l=GP(l,Math.max(0,p-fs(u))));let h=[],g=[],w=1,b=(A,_,P)=>{if(A.length===0)return;let $=ps(A),F={...P??{},text:A,token:_,start:w,width:$};if(h.push(F),F.id!==void 0){let J=g.find(Y=>Y.id===F.id);J!==void 0?J.end=w+$-1:g.push({id:F.id,start:w,end:w+$-1,action:F.action??"none",doubleAction:F.doubleAction??"none",value:F.value??F.text})}w+=$};if(b(r.prefix,r.ruleToken),l.length>0){b(r.pad,r.padToken);for(let A of l)b(A.text,A.token,A);b(r.pad,r.padToken)}let k=s+(l.length>0?fs(l)+o*2:0)+(u.length>0?fs(u)+o*2:0),S=Math.max(r.minGap,n-k);S>0&&r.fill.length>0&&b(r.fill.repeat(S),r.ruleToken);let I=null;if(u.length>0){I=w,b(r.pad,r.padToken);for(let A of u)b(A.text,A.token,A);b(r.pad,r.padToken)}b(r.suffix,r.ruleToken);let x=h.map(A=>`${A.token}${A.text}`).join("\0");return{chunks:h,signature:x,hits:g,rightStart:I}}var zP,JP,Qm=q(()=>{"use strict";qP();zP=Nq(),JP=jP});function ov(n){return n.banner.status==="ready"&&n.banner.armedSince!==void 0}function Bq(n){let e=n.banner.status,t=e==="busy"&&n.banner.stalled===!0,r;n.statusLabel!==void 0?r=n.statusLabel:t?r="Stalled":e==="busy"?r="Thinking":ov(n)?r="Waiting":r=e.charAt(0).toUpperCase()+e.slice(1);let s;return t||e==="disconnected"?s="status-alert":e==="busy"||ov(n)?s="status-active":e==="cold"?s="status-cold":s="status-ready",{label:r,token:s}}function eo(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:String(n)}function Hq(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${eo(n.used)}/${eo(n.size)}`):e.push(eo(n.used)):typeof n.size=="number"&&e.push(`/${eo(n.size)}`),typeof n.costAmount=="number"&&e.push(Qh(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Uq(n){if(n.banner.hintsExhausted===!0&&!n.hintsRevealed)return null;let e=n.banner.hint;return e.length===0?null:e.map((t,r)=>{let o={text:t.id==="mode"&&(n.banner.currentMode??"")!==""?`${t.label}: ${n.banner.currentMode}`:t.label,token:"modal-hint",action:t.action};return{id:t.id,chunks:[o],priority:20+(e.length-r)}})}function VP(n){if(n.transient===null)return null;let e=n.transient.kind==="search"?"bar-indicator":"modal-note";return{id:"transient",chunks:[{text:n.transient.text,token:e}],priority:1/0}}var iv,wne,Xm=q(()=>{"use strict";Hb();ke();ir();To();iv={status:{priority:1/0,resolve:n=>{let{label:e,token:t}=Bq(n);return[{text:e,token:t}]}},elapsed:{priority:60,resolve:n=>{if(ov(n)){let r=Date.now()-n.banner.armedSince;return r<1e3?null:[{text:Pr(r),token:"status-active"}]}if(n.banner.status!=="busy"||n.banner.elapsedMs===void 0||n.banner.elapsedMs<1e3)return null;let t=n.banner.stalled===!0?"status-alert":"status-active";return[{text:Pr(n.banner.elapsedMs),token:t}]}},sessionId:{priority:40,resolve:n=>{let e=st(n.session.sessionId);if(!e)return null;let t={text:e,token:"rule-meta",doubleAction:"copy",value:e};return n.scope==="btw"&&(t.action="open-session"),[t]}},sessionIdFull:{priority:40,resolve:n=>n.session.sessionId?[{text:n.session.sessionId,token:"rule-meta",doubleAction:"copy"}]:null},queued:{priority:50,resolve:n=>n.banner.queued>0?[{text:`${n.banner.queued} queued`,token:"status-queued"}]:null},scroll:{priority:30,resolve:n=>n.scrollOffset>0?[{text:`\u2191 ${n.scrollOffset}`,token:"bar-indicator"}]:null},usage:{priority:45,resolve:n=>{let e=Hq(n.session.usage);return e?[{text:e,token:"content",doubleAction:"copy"}]:null}},tokens:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.used!="number"?null:[{text:typeof e.size=="number"&&e.size>0?`${eo(e.used)}/${eo(e.size)}`:eo(e.used),token:"content",doubleAction:"copy"}]}},cost:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.costAmount!="number"?null:[{text:Qh(e.costAmount,e.costCurrency),token:"content",doubleAction:"copy"}]}},cwd:{priority:70,resolve:()=>null,resolveGroups:n=>{let e=n.session.workspace;if(e===void 0){let r=V(n.session.cwd);return r?[{id:"cwd",priority:70,chunks:[{text:r,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:n.session.cwd}]}]:null}let t=V(e.sourceCwd);return t?[{id:"cwd",priority:70,chunks:[{text:t,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:e.sourceCwd}]},{id:"cwdWorkspace",priority:69,separator:" ",chunks:[{text:`[${e.label}]`,token:"bar-text",doubleAction:"open",value:e.path}]}]:null}},cwdFull:{priority:70,resolve:n=>n.session.cwd?[{text:n.session.cwd,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open"}]:null},title:{priority:75,resolve:n=>{let e=n.session.title?.trim();return e?[{text:e,token:"bar-text",flex:!0,minWidth:8,doubleAction:"rename-session",value:e}]:null}},agent:{priority:80,resolve:n=>n.session.agent?[{text:n.session.agent,token:"content",doubleAction:"choose-agent"}]:null},model:{priority:65,resolve:n=>n.session.model?[{text:n.session.model,token:"content",doubleAction:"choose-model"}]:null},agentModel:{priority:80,resolve:n=>{let e=DT(n.session.agent,n.session.model);return e?[{text:e,token:"content",flex:!0,minWidth:6,doubleAction:"choose-model",value:e}]:null}},mode:{priority:55,resolve:n=>n.banner.currentMode?[{text:n.banner.currentMode,token:"rule-meta",doubleAction:"choose-mode",value:"mode"}]:null},helpHint:{priority:20,resolve:()=>null,resolveGroups:Uq}},wne=Object.keys(iv)});function YP(n){return typeof n=="string"?n===av?null:n:n.field??null}function QP(n,e,t){if(!t.some(a=>a===av))return t;let r=new Set;for(let a of t){let d=YP(a);d!==null&&r.add(d)}let s=Wq[n][e].filter(a=>{let d=YP(a);return d===null||!r.has(d)}),o=[],i=!1;for(let a of t){if(a===av){i||(o.push(...s),i=!0);continue}o.push(a)}return o}function qq(n){if(typeof n!="string")return n;let t=jq.exec(n)?.[1];return t!==void 0?{script:t}:{field:n}}function XP(n){if(n!==void 0)return JP.includes(n)?n:"none"}function zq(n,e){let t=`${n}:${e.id}`;return{...e,chunks:e.chunks.map(r=>({...r,id:t}))}}function Kq(n,e){let t=n;if(e.style!==void 0){let r=e.style;t=t.map(s=>({...s,token:r}))}if(e.minWidth!==void 0&&(t=t.map(r=>({...r,flex:!0,minWidth:e.minWidth}))),e.maxWidth!==void 0){let r=e.maxWidth;if(t=t.map(s=>({...s,text:Ym(s.text,r)})).filter(s=>s.text.length>0),t.length===0)return null}return e.truncate===!1&&(t=t.map(r=>({...r,truncatable:!1}))),t}function Gq(n,e){let t=n.map(o=>({...o,chunks:[...o.chunks]})),r=t[0];if(e.prefix!==void 0&&e.prefix.length>0&&r!==void 0){let o=r.chunks[0];o!==void 0&&r.chunks.unshift({text:e.prefix,token:o.token})}let s=t[t.length-1];if(e.suffix!==void 0&&e.suffix.length>0&&s!==void 0){let o=s.chunks[s.chunks.length-1];o!==void 0&&s.chunks.push({text:e.suffix,token:o.token})}return t}function ef(n,e,t){let r=[];for(let s of e){let o=qq(s),i;if(o.text!==void 0){if(o.text.length===0)continue;i=[{id:`text:${o.text}`,priority:10,chunks:[{text:o.text,token:"rule-meta"}]}]}else if(o.script!==void 0){let u=t.scriptOutputs.get(o.script);if(u===void 0||u.length===0)continue;i=[{id:`script:${o.script}`,priority:10,chunks:[{text:u,token:"rule-meta"}]}]}else{let u=o.field??"",f=iv[u];if(f===void 0)continue;if(f.resolveGroups!==void 0){let p=f.resolveGroups(t);if(p===null)continue;i=p}else{let p=f.resolve(t);if(p===null||p.length===0)continue;i=[{id:u,priority:f.priority,chunks:p}]}}let a=[];for(let u of i){let f=Kq(u.chunks,o);f!==null&&a.push({...u,priority:o.priority??u.priority,chunks:f})}if(a.length===0)continue;a=Gq(a,o);let d=XP(o.onClick),c=XP(o.onDoubleClick);(d!==void 0||c!==void 0)&&(a=a.map(u=>({...u,chunks:u.chunks.map(f=>({...f,...d!==void 0?{action:d}:{},...c!==void 0?{doubleAction:c}:{}}))})));let l=a[0];o.separator!==void 0&&l!==void 0&&(l.separator=o.separator);for(let u of a)r.push(zq(n,u))}return r}function tf(n){let e=(t,r)=>({left:QP(t,"left",r.left),right:QP(t,"right",r.right)});return{composer:{top:e("composerTop",n.composer.top),bottom:e("composerBottom",n.composer.bottom)},sessionbar:e("sessionbar",n.sessionbar)}}var dv,av,Wq,jq,cv=q(()=>{"use strict";rt();Xm();Qm();Qm();dv={composerTop:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},composerBottom:{prefix:"",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},btw:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},sessionbar:{prefix:"",suffix:"",fill:" ",pad:"",separator:" \xB7 ",separatorToken:"content",ruleToken:"content",padToken:"content",minGap:1}},av="...",Wq={composerTop:{left:Qi,right:Xi},btw:{left:Qi,right:Xi},composerBottom:{left:Fd,right:Ld},sessionbar:{left:Nd,right:Dd}};jq=/^\$\((.+)\)\s*$/});import{resolve as Jq}from"path";function uv(n){return!Vq.has(n)}function Yq(n){return n.replace(/\s+/gu," ").trim()}function Qq(n,e,t){let r=n.trim();for(let s of[e,t]){if(s===void 0||s==="")continue;let o=r.toLowerCase(),i=s.toLowerCase();if(o===i)return"";o.startsWith(`${i} `)&&(r=r.slice(s.length).trimStart())}return r}function Xq(n){let e=n.trim();return e===""?!0:!/[\s/.]/u.test(e)}function Zq(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 ZP}}function ez(n,e){if(!uv(n.status))return null;let t=Zq(n.rawKind),r=c=>c===void 0?"":Qq(Yq(c),t,n.rawKind),s=n.editDiff?.path??Ip(n.locations),o=s===void 0||s===""?void 0:e===null?s:Jq(e,s),i=r(n.latestTitle),a=t!==ZP&&Xq(i)?"":i,d=r(n.detail)||tz(o)||a;return{verb:t,detail:d===""?void 0:d,startedAt:n.startedAt,path:o}}function tz(n){return n===void 0?"":n.split(/[\\/]/).filter(t=>t!=="").at(-1)??""}function eM(n,e,t){let r=[];for(let s of n){let o=e.get(s);if(o===void 0||vc(s,o.latestTitle))continue;let i=ez(o,t);i!==null&&r.push(i)}return r}var lv,Vq,ZP,fv=q(()=>{"use strict";Jl();Yp();lv=4,Vq=new Set(["completed","succeeded","ok","failed","error","rejected","cancelled","canceled"]);ZP="tool"});function nf(n){let e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;return t<60?`${t}m ${String(r).padStart(2,"0")}s`:`${Math.floor(t/60)}h ${String(t%60).padStart(2,"0")}m`}function tM(n,e){return e<=0?n:Math.floor(Math.max(0,n)/e)*e}function pv(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 nz(n,e){if(e<=0)return"";let t=Math.max(0,Math.min(1,n)),r=Math.round(t*e*8),s=Math.floor(r/8),o=r%8,i=o===0?"":"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[o-1];return"\u2588".repeat(Math.min(e,s))+(s<e?i:"")+"\xB7".repeat(Math.max(0,e-s-(i?1:0)))}function _r(n,e){return{body:n,bodyStyle:e}}function Zm(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?{body:s(`${n} ${e}`,t.width),bodyStyle:"muted"}:{prefix:`${n}${" ".repeat(o)}`,prefixStyle:"muted",body:e,bodyStyle:"sidebar-value"}}function aM(n,e,t,r){let s={body:n,bodyStyle:t,openPath:e,item:!0};if(r!==void 0&&r.length>0){let o=n.indexOf(r);o!==-1&&(s.openSpan={start:o,end:o+r.length})}return s}function hs(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?s(`${n} ${e}`,t.width):`${n}${" ".repeat(o)}${e}`}function rM(n){return n==="in_progress"?0:n==="completed"?2:1}function dz(n){return[...n].sort((e,t)=>rM(e.status)-rM(t.status))}function dM(n){let e=n.map(r=>r.split("/").pop()??r),t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return n.map((r,s)=>{let o=e[s];return(t.get(o)??0)<=1?o:r.split("/").slice(-2).join("/")})}function fz(n,e,t){let{cellWidth:r,truncate:s}=t.metrics;if(e<=0)return"";if(r(n)<=e)return n;let o=n.slice(n.lastIndexOf("/")+1);if(o!==n&&r(o)<=e)return o;let i=o.length<n.length?o:n;for(let a=1;a<i.length;a++){let d=`\u2026${i.slice(a)}`;if(r(d)<=e)return d}return s(i,e)}function sM(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 iM(n){if(n===void 0)return"\u2013".padStart(oM);let e=n*100;return(e<100?`${e.toFixed(1)}%`:`${Math.round(e)}%`).padStart(oM)}var Si,nM,rz,sz,oz,iz,az,cz,lz,uz,pz,oM,hz,mz,gz,yz,wz,bz,cM,lM=q(()=>{"use strict";fv();Si=5;nM=5e3,rz={id:"activity",relevant:()=>!0,versionKey:n=>n.busySince!==null?`busy:${Math.floor((n.now-n.busySince)/1e3)}`:n.armedSince!==null?`running:${Math.floor((n.now-n.armedSince)/1e3)}`:n.lastTurnEndedAt!==null?`idle:${tM(n.now-n.lastTurnEndedAt,nM)}`:"fresh",render:(n,e)=>n.busySince!==null?[_r(hs("\u25CF thinking",nf(n.now-n.busySince),e),"status-active")]:n.armedSince!==null?[_r(hs("\u25D0 waiting",nf(n.now-n.armedSince),e),"status-active")]:n.lastTurnEndedAt!==null?[_r(hs("\u25CB idle",nf(tM(n.now-n.lastTurnEndedAt,nM)),e),"status-idle")]:[_r("\u25CB ready","status-idle")]},sz={id:"tasks",title:"tasks",relevant:n=>n.armedTasks.length>0,versionKey:(n,e)=>{let t=n.armedTasks.slice(0,Si);return`${e.width}|${n.armedTasks.length}|`+t.map(r=>{let s=Math.floor(Math.max(0,n.now-r.since)/1e3);return`${r.taskId??r.label}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[];for(let o of n.armedTasks.slice(0,Si)){let i=nf(Math.max(0,n.now-o.since)),a="\u25D0 ",d=e.width-r(a)-r(i)-1,c=o.label.length>0?o.label:o.taskType??"background task",l=d<4?a.trim():`${a}${t(c,d)}`;s.push(_r(hs(l,i,e),"status-active"))}return n.armedTasks.length>Si&&s.push(_r(` +${n.armedTasks.length-Si} more`,"muted")),s}},oz={id:"tools",title:"tools",relevant:n=>n.running.length>0,versionKey:(n,e)=>{let t=n.running.slice(0,lv);return`${e.width}|${n.running.length}|`+t.map(r=>{let s=r.startedAt===void 0?"":Math.floor(Math.max(0,n.now-r.startedAt)/1e3);return`${r.verb}:${r.detail??""}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[],o=n.running.slice(0,lv);for(let i of o){let a=i.startedAt===void 0?"":nf(Math.max(0,n.now-i.startedAt)),d=`\u25B8 ${i.verb}`,c=e.width-r(d)-(a===""?0:r(a)+1)-1,l=i.detail===void 0||c<4?"":` ${t(i.detail,c)}`,u=`${d}${l}`,f=a===""?u:hs(u,a,e),p={body:f,bodyStyle:"tool-status-running",openPath:i.path};if(i.path!==void 0){let m=i.path.slice(i.path.lastIndexOf("/")+1),h=m.length>0?f.indexOf(m):-1;h!==-1&&(p.openSpan={start:h,end:h+m.length})}s.push(p)}return n.running.length>o.length&&s.push(_r(` +${n.running.length-o.length} more`,"muted")),s}},iz={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:r,size:s,costAmount:o,costCurrency:i}=n.usage;if(r!==void 0&&s!==void 0&&s>0){let a=r/s;t.push(_r(hs(`${pv(r)}/${pv(s)}`,`${Math.round(a*100)}%`,e),a>=.9?"meter-warn":"metric")),t.push(_r(nz(a,e.width),a>=.9?"meter-warn":"meter-fill"))}else r!==void 0&&t.push(_r(hs("tokens",pv(r),e),"metric"));if(o!==void 0){let a=i==="USD"||i===void 0?"$":`${i} `;t.push(_r(hs("cost",`${a}${o.toFixed(2)}`,e),"muted"))}return t}},az={id:"queue",relevant:n=>n.queued>0,versionKey:(n,e)=>`${n.queued}/${e.width}`,render:(n,e)=>[_r(hs("queued",String(n.queued),e),"status-queued")]};cz={id:"todo",title:"todo",pageSize:Si,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,r=[];for(let s of dz(n.plan)){let o=s.status==="completed"?"\u2713":s.status==="in_progress"?"\u25B8":"\xB7",i=s.status==="completed"?"plan-done":s.status==="in_progress"?"plan":"plan-pending";r.push({body:t(`${o} ${s.content}`,e.width),bodyStyle:i,item:!0})}return r}};lz={id:"files",title:"edited",pageSize:Si,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:r}=e.metrics,s=[...n.editedFiles].reverse(),o=[],i=dM(s.map(a=>a.path));return s.forEach((a,d)=>{let c=a.added!==void 0||a.removed!==void 0?`+${a.added??0} -${a.removed??0}`:"",l=e.width-(c?r(c)+1:0),u=t(i[d],Math.max(1,l));o.push(aM(c?hs(u,c,e):u,a.path,"file-path",u))}),o}},uz={id:"git",title:"git",pageSize:Si,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 r=t.files.map(s=>`${s.state}:${s.path}`).join("\0");return`${e.width}|${t.branch}|${t.staged}|${t.unstaged}|${t.untracked}|${t.ahead}|${t.behind}|${r}`},render:(n,e)=>{let t=n.git;if(t===null)return[];let{truncate:r,cellWidth:s}=e.metrics,o=[];if(t.branch!==null){let d=(t.ahead>0?`\u2191${t.ahead}`:"")+(t.behind>0?`\u2193${t.behind}`:"");o.push(d?Zm(r(t.branch,e.width-d.length-1),d,e):{body:r(t.branch,e.width)})}let i=t.files,a=dM(i.map(d=>d.path));return i.forEach((d,c)=>{let l=d.state==="staged"?"git-staged":d.state==="dirty"?"git-dirty":"git-untracked",u=e.width-s(d.state)-1,f=r(a[c],Math.max(1,u));o.push(aM(hs(f,d.state,e),d.path,l,f))}),o}};pz={id:"info",title:"info",relevant:n=>n.agent!==null||n.model!==null||n.sessionId!==null||n.workspace!==null,versionKey:(n,e)=>`${e.width}|${n.agent}|${n.model}|${n.mode}|${n.sessionId}|${n.host}|${n.workspace?.label??""}`,render:(n,e)=>{let{cellWidth:t}=e.metrics,r=[],s=(o,i,a)=>{let d=e.width-t(o)-1,c=Zm(o,fz(i,d,e),e);r.push(a===void 0?c:{...c,doubleAction:a})};if(n.agent!==null&&s("agent",n.agent,{action:"choose-agent",value:"agent"}),n.model!==null&&s("model",n.model,{action:"choose-model",value:"model"}),n.mode!==null&&s("mode",n.mode,{action:"choose-mode",value:"mode"}),n.host!==null&&s("host",n.host,{action:"copy",value:n.host}),n.sessionId!==null&&s("id",n.sessionId,{action:"copy",value:n.sessionId}),n.workspace!==null){let o=Zm("workspace",n.workspace.label,e);r.push({...o,openPath:n.workspace.path})}return r}};oM=5;hz="\u25CF",mz="\u25D0",gz="\u25CB",yz="\u25E6",wz={id:"sessions",title:"sessions",pageSize:Si,relevant:n=>n.liveSessions.length>0,titleNote:(n,e,t)=>{if(!t)return;let r=n.liveSessions.filter(s=>s.blocked).length;return r>0?`${r} blocked`:`${n.liveSessions.length} live`},versionKey:(n,e)=>`${e.width}|`+n.liveSessions.map(t=>`${t.blocked?"w":""}${t.busy?"b":""}${t.armed?"r":""}:${t.sessionId}:${t.label}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=i=>(i.blocked?0:3)+(i.busy?0:i.armed?1:2);return[...n.liveSessions].sort((i,a)=>s(i)-s(a)).map(i=>{let a=i.busy||i.armed,d=`${i.blocked?yz:" "}${i.busy?hz:i.armed?mz:gz}`,c=r(d),l=t(i.label,Math.max(1,e.width-c-1)),u=Math.max(1,e.width-r(l)-c);return{prefix:`${l}${" ".repeat(u)}`,prefixStyle:a?"status-active":"sidebar-value",body:d,bodyStyle:a?"status-active":i.blocked?"status-blocked":"status-idle",doubleAction:{action:"open-session",value:i.sessionId},item:!0}})}},bz={id:"resources",title:"resources",relevant:n=>n.resources.length>0,versionKey:(n,e)=>`${e.width}|`+n.resources.map(t=>`${t.label}:${sM(t.rssBytes)}:${iM(t.cpuFraction)}:${t.processes}`).join("\0"),render:(n,e)=>{let{cellWidth:t,truncate:r}=e.metrics;return n.resources.map(s=>{let o=`${sM(s.rssBytes)} ${iM(s.cpuFraction)}`,i=s.processes>1?`${s.label} \xD7${s.processes}`:s.label,a=e.width-t(o)-1;return Zm(r(i,Math.max(1,a)),o,e)})}},cM=[rz,sz,iz,az,cz,lz,uz,wz,bz,pz,oz]});function vz(n){let e="",t=[],r=0;for(;r<n.length;){let s=n[r];if(s==="["){let o=n.indexOf("]",r+1);if(o!==-1&&n[o+1]==="("&&o>r+1){let i=-1,a=1,d=o+2;for(;d<n.length;){let c=n[d];if(c==="\\"&&d+1<n.length){d+=2;continue}if(c==="(")a+=1;else if(c===")"&&(a-=1,a===0)){i=d;break}d+=1}if(i!==-1&&i>o+2){let c=n.slice(r+1,o),l=n.slice(o+2,i),u=e.length;e+=c,t.push({start:u,end:e.length,url:l}),r=i+1;continue}}}e+=s,r+=1}return{body:e,links:t}}function uM(n){let e=zt(n).trim();return e.length===0?null:e}function Sz(n){return typeof n!="string"}function eg(n){return typeof n=="string"?n:n.id}function tg(n){return n.filter(Sz)}function hv(n,e){let t=new Map;for(let r of tg(n)){let s=r.refreshMs??e,o=t.get(r.script);t.set(r.script,o===void 0?s:Math.min(o,s))}return t}function fM(n){return{id:n.id,title:n.title??n.id,relevant:e=>e.processOutputs.has(n.script),versionKey:(e,t)=>`${t.width}:${e.processOutputs.get(n.script)??""}`,render:(e,t)=>{let r=e.processOutputs.get(n.script);if(r===void 0)return[];let{truncate:s}=t.metrics,o=r.split(`
|
|
250
250
|
`).filter(d=>d.length>0),i=n.cap??kz,a=o.slice(0,i).map(d=>{let{body:c,links:l}=vz(d),u=s(c,t.width),f=l.filter(p=>p.start<u.length).map(p=>({...p,end:Math.min(p.end,u.length)}));return f.length>0?{body:u,links:f}:{body:u}});return o.length>i&&a.push({body:` +${o.length-i} more`,bodyStyle:"muted"}),a}}}var kz,ng=q(()=>{"use strict";Io();kz=6});function mv(n){return n==="frame"}function pM(n=0){return{now:n,busySince:null,lastTurnEndedAt:null,armedSince:null,armedTasks:[],queued:0,usage:{},plan:[],editedFiles:[],running:[],git:null,liveSessions:[],resources:[],sessionId:null,host:null,agent:null,model:null,mode:null,workspace:null,processOutputs:new Map}}var gv=q(()=>{"use strict"});function Iz(n){let e=xz[n]??n;return cM.find(t=>t.id===e)}function kv(n){if(!n.some(o=>o===yv))return n;let e=new Set;for(let o of n)o!==yv&&e.add(eg(o));let t=bv.filter(o=>!e.has(o)),r=[],s=!1;for(let o of n){if(o===yv){s||(r.push(...t),s=!0);continue}r.push(o)}return r}function wv(n,e){return{body:"\u2500".repeat(Math.max(0,n)),bodyStyle:"sidebar-rule",gutter:e}}function Ez(n,e,t,r){if(r<=0||!Number.isFinite(r))return e;let s=rg(e);if(s<=r)return e;let o=Math.ceil(s/r),i=t.pages?.[n.id]??0,a=Math.max(0,Math.min(o-1,i)),d=a*r,c=d+r,l=[],u=0;for(let A of e){if(A.item!==!0){l.push(A);continue}let _=u++;_>=d&&_<c&&l.push(A)}if(n.title===void 0||l.length===0)return l;let{cellWidth:f,truncate:p}=t.metrics,m=`${Az} ${a+1}/${o} ${Tz}`,h=f(m),g=t.width-h-1;if(g<1)return l;let w=p(n.title,g),b=t.width-f(w)-h,k=`${w}${" ".repeat(Math.max(1,b))}${m}`,S=f(k)-h+1,I=f(k),x=[];for(let A of l[0].actions??[])"collapse"in A&&S>2&&x.push({...A,start:1,end:S-2});return a>0&&x.push({start:S,end:S,page:{gadget:n.id,index:a-1}}),a<o-1&&x.push({start:I,end:I,page:{gadget:n.id,index:a+1}}),l[0]={...l[0],body:k,actions:x},l}function rg(n){return n.reduce((e,t)=>e+(t.item===!0?1:0),0)}function mM(n,e,t,r){let s=n.title??"",o=n.titleNote?.(e,t,r),i=r?o===void 0||o.length===0?hM:`${o} ${hM}`:o,a={start:1,end:t.width,collapse:{gadget:n.id}};if(i===void 0||i.length===0)return{body:s,bodyStyle:"sidebar-title",actions:[a]};let{cellWidth:d,truncate:c}=t.metrics,l=d(i),u=t.width-l-1;if(u<1)return{body:c(s,t.width),bodyStyle:"sidebar-title",actions:[a]};let f=c(s,u),p=t.width-d(f)-l;return{body:`${f}${" ".repeat(Math.max(1,p))}${i}`,bodyStyle:"sidebar-title",actions:[a]}}function Pz(n,e,t,r){let s=n.map((c,l)=>e[l]?rg(c):0),o=n.reduce((c,l,u)=>c+(e[u]?0:rg(l)),0),i=c=>t+o+s.reduce((l,u)=>l+Math.min(u,c),0),a=Math.max(0,...s);if(i(a)<=r)return Number.POSITIVE_INFINITY;let d=1;for(let c=1;c<=a&&i(c)<=r;c++)d=c;return d}var bv,xz,yv,Cz,Rz,hM,Az,Tz,sg,vv=q(()=>{"use strict";lM();ng();gv();bv=["activity","sessions","tasks","context","queue","todo","files","git","resources","info","tools"],xz={session:"info"};yv="...";Cz=Object.freeze({body:""}),Rz=Object.freeze({body:"",gutter:"\u2502"});hM="+",Az="\u2039",Tz="\u203A";sg=class{cache=new Map;extraGadgets=new Map;rules=null;gadgets=[];configuredGadgetIds=bv;constructor(e=bv){this.setGadgets(e)}setGadgets(e){this.configuredGadgetIds=e;let t=e.map(s=>this.extraGadgets.get(s)??Iz(s)).filter(s=>s!==void 0);(t.length!==this.gadgets.length||t.some((s,o)=>s!==this.gadgets[o]))&&(this.gadgets=t,this.cache.clear())}setProcessGadgets(e){this.extraGadgets=new Map(e.map(t=>[t.id,t])),this.setGadgets(this.configuredGadgetIds)}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 r=[],s=[];for(let f of this.gadgets){if(!f.relevant(e))continue;let p=f.title!==void 0&&t.collapsed?.has(f.id)===!0,m=`${t.border}|${p?"c":"e"}|${f.versionKey(e,t)}`,h=this.cache.get(f.id),g;if(h!==void 0&&h.key===m)g=h.lines;else if(p){let w=mM(f,e,t,!0);g=[t.border==="none"?w:{...w,gutter:"\u2502"}],this.cache.set(f.id,{key:m,lines:g})}else{let w=f.render(e,t),b=f.title===void 0?w:[mM(f,e,t,!1),...w];g=w.length===0?[]:t.border==="none"?b:b.map(k=>({...k,gutter:"\u2502"})),this.cache.set(f.id,{key:m,lines:g})}g.length!==0&&(r.push(g),s.push(p?null:f))}if(r.length===0)return[];let o=mv(t.border)?r.length+1:Math.max(0,r.length-1),i=s.map(f=>f!==null&&f.pageSize!==void 0&&f.pageSize>0),a=o+r.reduce((f,p)=>f+p.length-rg(p),0),d;t.maxRows===void 0?d=Number.NaN:d=Pz(r,i,a,t.maxRows);let c=r.map((f,p)=>{let m=s[p],h=m?.pageSize;if(m==null||h===void 0)return f;let g=Number.isNaN(d)?h:d;return Ez(m,f,t,g)});r.length=0,r.push(...c);let l=[];if(mv(t.border)){this.rules?.width!==t.width&&(this.rules={width:t.width,lines:{"\u250C":wv(t.width,"\u250C"),"\u251C":wv(t.width,"\u251C"),"\u2514":wv(t.width,"\u2514")}});let f=this.rules.lines;return l.push(f["\u250C"]),r.forEach((p,m)=>{m>0&&l.push(f["\u251C"]),l.push(...p)}),l.push(f["\u2514"]),l}let u=t.border==="rule"?Rz:Cz;return r.forEach((f,p)=>{p>0&&l.push(u),l.push(...f)}),l}}});import*as yM from"path";function _z(n){n==="unknown"||za!==null||(og=n,za=setTimeout(()=>{za=null,og=null,rf()},Mz),za.unref?.())}function wM(){za!==null&&(clearTimeout(za),za=null),og=null}function bM(){if(et.permission)return"blocked";switch(et.status){case"busy":case"cancelling":return"working";case"ready":return"idle";case"disconnected":case"cold":return og??"unknown";default:return"unknown"}}function $z(n){return typeof n!="number"||!Number.isFinite(n)||n<=0?null:`$${n.toFixed(2)}`}function Oz(){let n=et.cwd?.trim();return n?yM.basename(n)||n:null}function kM(){return et.title?.trim()||Oz()}function Fz(){return{state:bM(),sessionId:et.sessionId??null,title:kM(),cwd:et.cwd?.trim()||null,agent:et.agent??null,model:et.model??null,cost:$z(et.costAmount),queued:et.queued??null,turnOrigin:et.turnOrigin,turnLabel:et.turnLabel}}function rf(){let n=on();if(!n||!et.sessionId||(et.suspended?ju(Om,{transient:!0}):ju(kM()),et.suspended)||!n.caps.report)return;let e=Fz(),t=JSON.stringify(e);xi!==t&&(xi=t,Promise.resolve(n.report(e)).catch(()=>{xi=null}))}function vM(n){on()&&(n.sessionId!==et.sessionId&&(et.turnOrigin=null,et.turnLabel=null),et.sessionId=n.sessionId,et.agent=n.agent,et.title=n.title,et.model=n.model,et.costAmount=n.costAmount,et.cwd=n.cwd,rf())}function SM(n){if(!on())return;let e=gM.has(et.status??""),t=gM.has(n.status??"");t&&!e?_z(bM()):t||wM(),et.status=n.status,et.queued=n.queued,rf()}function xM(n){on()&&(et.turnOrigin=n.origin,et.turnLabel=n.label??null)}function Sv(n){if(!(!on()||et.suspended===n)){if(et.suspended=n,n){Lz();return}xi=null,rf()}}function Lz(){let n=on();n&&(ju(Om,{transient:!0}),xi!==null&&(xi=null,n.caps.report&&Promise.resolve(n.release()).catch(()=>{})))}function IM(n){on()&&(et.permission=n,rf())}async function CM(){let n=on();if(n&&(await fP(),wM(),xi!==null)){xi=null,et.sessionId=void 0,et.turnOrigin=null,et.turnLabel=null;try{await n.release()}catch{}}}var et,xi,Mz,gM,og,za,xv=q(()=>{"use strict";Wa();Nk();et={permission:!1,turnOrigin:null,turnLabel:null,suspended:!1},xi=null,Mz=1e4,gM=new Set(["disconnected","cold"]),og=null,za=null});import{spawnSync as Nz}from"child_process";import*as _o from"fs";import*as tl from"path";function AM(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${RM}1337;SetUserVar=${n}=${t}${Dz}`)}function Hz(){if(!process.stdin.isTTY)return null;let n=t=>{try{let r=_o.readlinkSync(t);return r.startsWith("/dev/")&&r!=="/dev/tty"?tl.basename(r):null}catch{return null}},e=n("/proc/self/fd/0")??n("/dev/fd/0");if(e)return e;try{let t=Nz("tty",[],{encoding:"utf8",timeout:500});if(t.status!==0)return null;let r=t.stdout.trim();return!r.startsWith("/dev/")||r==="/dev/tty"?null:tl.basename(r)}catch{return null}}function TM(){return Iv===void 0&&(Iv=Hz()),Iv}function Uz(n){let e=TM();if(e)try{_o.mkdirSync(D.ttySessionDir(),{recursive:!0});let t=`${process.pid}:${process.ppid}:${n}
|
|
251
251
|
`;_o.writeFileSync(D.ttySessionFile(e),t,{mode:384})}catch{}}function Wz(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 r=Number.parseInt(t[0],10),s=Number.parseInt(t[1],10),o=t.slice(2).join(":");return!Number.isFinite(r)||!Number.isFinite(s)||o.length===0?null:{hydraPid:r,parentPid:s,sessionId:o}}function jz(){let n=TM();if(!n)return null;try{let e=_o.readFileSync(D.ttySessionFile(n),"utf8");return Wz(e)}catch{return null}}function qz(){let n=jz();return!n||n.parentPid>0&&n.parentPid!==process.ppid?null:n.sessionId}function Cv(n){!tl.isAbsolute(n)||!process.stdout.isTTY||process.stdout.write(`${RM}7;${m0(n)}${Bz}`)}function EM(){let n;try{n=process.cwd()}catch{return}Cv(n)}function Rv(n){AM("hydra_session",n),Uz(n)}function PM(){AM("hydra_session","")}function MM(){return qz()}var RM,Dz,Bz,Iv,Av=q(()=>{"use strict";ke();To();RM="\x1B]",Dz="\x07",Bz="\x1B\\"});import zz from"string-width";function _M(n,e){if(!n||e<=0)return 0;let t=0;for(let r of Kz.segment(n)){let s=zz(r.segment);if(e<t+s)return r.index;if(t+=s,e===t)return r.index+r.segment.length}return n.length}function $M(n,e){if(e<=0)return 0;let t=0,r=0;for(let s of n)if(s.width>0&&e<t+s.width||(t+=s.width,r+=s.text.length,s.width>0&&e===t))return r;return r}var Kz,OM=q(()=>{"use strict";Kz=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function Jz(n){return(n.split(/[/\\]/).pop()??n).replace(/\.exe$/i,"").toLowerCase()}function FM(n,e,t){let[r,...s]=n;if(!r)return null;let o=t===null?"":String(t),i=!1,a=!1,d=[];for(let l of s)l.includes("%f")&&(i=!0),!(l.includes("%n")&&(a=!0,o===""))&&d.push(l.replaceAll("%f",e).replaceAll("%n",o));if(i)return{program:r,args:d};let c=o===""||a?void 0:Gz[Jz(r)];return c==="plus"?d.push(`+${o}`,e):c==="colon"?d.push(`${e}:${o}`):d.push(e),{program:r,args:d}}var Gz,LM=q(()=>{"use strict";Gz={vi:"plus",vim:"plus","vim.basic":"plus","vim.tiny":"plus",vimdiff:"plus",view:"plus",ex:"plus",nvim:"plus",nvimdiff:"plus",gvim:"plus",mvim:"plus",nano:"plus",pico:"plus",micro:"plus",kak:"plus",joe:"plus",emacs:"plus",emacsclient:"plus",hx:"colon",helix:"colon"}});function Vz(){sf===0&&we(lE),sf++}function Yz(){sf!==0&&(sf--,sf===0&&we(uE))}function pt(n){Vz();try{n()}finally{Yz()}}var sf,Tv=q(()=>{"use strict";Fa();sf=0});function Qz(n=Ev){let e=`
|
|
252
|
-
\r`+NM;for(let t of n)e+=t+NM;return e+"\r\x1B[K"}function Xz(n){let e=[],t=/\u001b\[(\d+);(\d+)R/g,r;for(;(r=t.exec(n))!==null;)e.push([Number(r[1]),Number(r[2])]);return e}function DM(n){return/\u001b\[\d+;\d+R/.test(n)}function BM(n){return n.replace(/\u001b\[\d+;\d+R/g,"")}function Zz(n,e=Ev){if(n.length<e.length+1)return;let t={};for(let r=0;r<e.length;r++){let[s,o]=n[r],[i,a]=n[r+1];if(i!==s)return;let d=a-o;if(d!==1&&d!==2)return;t[e[r]]=d}return t}function eK(n){let e=Object.values(n);return e.length===0?!1:e.filter(r=>r===2).length>e.length/2}async function HM(n={input:process.stdin,output:process.stdout},e=200,t=Ev){let{input:r,output:s}=n;if(!(r.isTTY!==!0||s.isTTY!==!0)&&!((s.columns??80)<t.length+2))return await new Promise(o=>{let i="",a=!1,d=r.isPaused?.()??!1,c,l=f=>{if(!a){a=!0,c!==void 0&&clearTimeout(c);try{(r.off??r.removeListener)?.call(r,"data",u),r.setRawMode?.(!1),d&&r.pause?.()}catch{}o(f)}},u=f=>{i+=typeof f=="string"?f:f.toString("latin1");let p=Xz(i);if(p.length<t.length+1)return;let m=Zz(p,t);l(m===void 0?void 0:{wide:eK(m),widths:m})};try{r.setRawMode?.(!0),r.resume?.(),r.on("data",u),s.write(Qz(t))}catch{l(void 0);return}c=setTimeout(()=>l(void 0),e),c.unref?.()})}var NM,Ev,Pv=q(()=>{"use strict";NM="\x1B[6n",Ev=["\u2500","\u2502","\xB7","\u258F","\u2026","\u2713","\u25B8"]});function rK(){let n="\x1B]10;?\x07\x1B]11;?\x07";for(let e=0;e<16;e++)n+=`\x1B]4;${e};?\x07`;return n}function UM(n){let e=/\u001b\]11;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:Mv(e[1])}function sK(n){let e=/\u001b\]10;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:Mv(e[1])}function oK(n){let e=new Map;for(let t of n.matchAll(/\u001b\]4;(\d+);([^\u0007\u001b]*)(?:\u0007|\u001b\\)/g)){let r=Number(t[1]);if(!Number.isInteger(r)||r<0||r>15)continue;let s=Mv(t[2]);s!==void 0&&e.set(r,s)}return e}function Mv(n){let e=n.trim();if(/^#[0-9a-f]+$/i.test(e))return Zo(e)??void 0;let t=/^rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(e);if(t===null)return;let r=a=>{if(!(a.length===0||a.length>4))return Math.round(parseInt(a,16)/(16**a.length-1)*255)},s=r(t[1]),o=r(t[2]),i=r(t[3]);if(!(s===void 0||o===void 0||i===void 0))return Dn(s,o,i)}function iK(n){return n.replace(/\u001b\](?:10|11|4);[^\u0007\u001b]*(?:\u0007|\u001b\\)/g,"")}function aK(n){return/\u001b\](?:10|11|4);/.test(n)}async function WM(n={input:process.stdin,output:process.stdout},e=tK){let{input:t,output:r}=n;return t.isTTY!==!0||r.isTTY!==!0?{palette:new Map}:await new Promise(s=>{let o="",i=!1,a=t.isPaused?.()??!1,d,c,l=()=>({foreground:sK(o),background:UM(o),palette:oK(o)}),u=p=>{o+=typeof p=="string"?p:p.toString("latin1");let m=l();if(m.foreground!==void 0&&m.background!==void 0&&m.palette.size===16){f();return}c!==void 0&&clearTimeout(c),c=setTimeout(f,nK),c.unref?.()},f=()=>{if(i)return;i=!0;for(let m of[d,c])m!==void 0&&clearTimeout(m);let p=l();try{(t.off??t.removeListener)?.call(t,"data",u),t.setRawMode?.(!1),a&&t.pause?.()}catch{}s(p)};try{t.setRawMode?.(!0),t.resume?.(),t.on("data",u),r.write(rK())}catch{f();return}d=setTimeout(f,e),d.unref?.()})}function dK(n){let e=/\u001b\[\?997;([12])n/.exec(n);if(e!==null)return e[1]==="1"?"dark":"light"}function cK(n){return n.replace(/\u001b\[\?997;\d+n/g,"")}function zM(n){return n==="dark"?Dn(0,0,0):Dn(255,255,255)}function KM(n,e={}){if(n===null||typeof n!="object")return;let t=n,r=t.onStdin;typeof r=="function"&&(t.onStdin=function(o){let i=o.toString("latin1");if(!aK(i)&&!/\u001b\[\?997;/.test(i)&&!DM(i)){r.call(this,o);return}let a=UM(i),d=dK(i),c=BM(cK(iK(i)));c.length>0&&r.call(this,Buffer.from(c,"latin1")),a!==void 0&&e.onBackground?.(a),d!==void 0&&e.onScheme?.(d)})}var tK,nK,jM,qM,_v=q(()=>{"use strict";Yd();Pv();tK=200,nK=50;jM="\x1B[?2031h",qM="\x1B[?2031l"});import{spawn as lK}from"child_process";import{statSync as of}from"fs";import{homedir as ig}from"os";import{isAbsolute as ag,join as GM,resolve as JM,sep as dg}from"path";import r_ from"string-width";import uK from"wrap-ansi";function $K(n){let e=n.replace(/\r\n?$|\n$/,"");return _K.test(e)?e:null}function OK(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function FK(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function LK(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.links,r=e.links;if(t===void 0!=(r===void 0))return!1;if(t&&r){if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++){let o=t[s],i=r[s];if(o.start!==i.start||o.end!==i.end||o.url!==i.url)return!1}}return!0}function Hv(n,e,t,r=null,s=null,o=null){let i=s===null?"":`a${s}`,a=o===null?"":`s${o.start}:${o.end}${o.toEndOfLine?"f":""}`;return t?`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${r??""}|${i}|${a}`:`${n}|${e}|empty|${r??""}|${i}|${a}`}function ms(n,e){let t=[];for(let r=0;r<n.length;r++){let s=n[r]??"";if(s.length===0){t.push({bufferIdx:r,startCol:0,endCol:0});continue}let o=0;for(;o<s.length;){if(s.length-o<=e){t.push({bufferIdx:r,startCol:o,endCol:s.length}),o=s.length;break}let i=-1;for(let a=o+e-1;a>=o;a--){let d=s[a];if(d===" "||d===" "){i=a+1;break}}i===-1&&(i=o+e),t.push({bufferIdx:r,startCol:o,endCol:i}),o=i}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function
|
|
252
|
+
\r`+NM;for(let t of n)e+=t+NM;return e+"\r\x1B[K"}function Xz(n){let e=[],t=/\u001b\[(\d+);(\d+)R/g,r;for(;(r=t.exec(n))!==null;)e.push([Number(r[1]),Number(r[2])]);return e}function DM(n){return/\u001b\[\d+;\d+R/.test(n)}function BM(n){return n.replace(/\u001b\[\d+;\d+R/g,"")}function Zz(n,e=Ev){if(n.length<e.length+1)return;let t={};for(let r=0;r<e.length;r++){let[s,o]=n[r],[i,a]=n[r+1];if(i!==s)return;let d=a-o;if(d!==1&&d!==2)return;t[e[r]]=d}return t}function eK(n){let e=Object.values(n);return e.length===0?!1:e.filter(r=>r===2).length>e.length/2}async function HM(n={input:process.stdin,output:process.stdout},e=200,t=Ev){let{input:r,output:s}=n;if(!(r.isTTY!==!0||s.isTTY!==!0)&&!((s.columns??80)<t.length+2))return await new Promise(o=>{let i="",a=!1,d=r.isPaused?.()??!1,c,l=f=>{if(!a){a=!0,c!==void 0&&clearTimeout(c);try{(r.off??r.removeListener)?.call(r,"data",u),r.setRawMode?.(!1),d&&r.pause?.()}catch{}o(f)}},u=f=>{i+=typeof f=="string"?f:f.toString("latin1");let p=Xz(i);if(p.length<t.length+1)return;let m=Zz(p,t);l(m===void 0?void 0:{wide:eK(m),widths:m})};try{r.setRawMode?.(!0),r.resume?.(),r.on("data",u),s.write(Qz(t))}catch{l(void 0);return}c=setTimeout(()=>l(void 0),e),c.unref?.()})}var NM,Ev,Pv=q(()=>{"use strict";NM="\x1B[6n",Ev=["\u2500","\u2502","\xB7","\u258F","\u2026","\u2713","\u25B8"]});function rK(){let n="\x1B]10;?\x07\x1B]11;?\x07";for(let e=0;e<16;e++)n+=`\x1B]4;${e};?\x07`;return n}function UM(n){let e=/\u001b\]11;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:Mv(e[1])}function sK(n){let e=/\u001b\]10;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:Mv(e[1])}function oK(n){let e=new Map;for(let t of n.matchAll(/\u001b\]4;(\d+);([^\u0007\u001b]*)(?:\u0007|\u001b\\)/g)){let r=Number(t[1]);if(!Number.isInteger(r)||r<0||r>15)continue;let s=Mv(t[2]);s!==void 0&&e.set(r,s)}return e}function Mv(n){let e=n.trim();if(/^#[0-9a-f]+$/i.test(e))return Zo(e)??void 0;let t=/^rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(e);if(t===null)return;let r=a=>{if(!(a.length===0||a.length>4))return Math.round(parseInt(a,16)/(16**a.length-1)*255)},s=r(t[1]),o=r(t[2]),i=r(t[3]);if(!(s===void 0||o===void 0||i===void 0))return Dn(s,o,i)}function iK(n){return n.replace(/\u001b\](?:10|11|4);[^\u0007\u001b]*(?:\u0007|\u001b\\)/g,"")}function aK(n){return/\u001b\](?:10|11|4);/.test(n)}async function WM(n={input:process.stdin,output:process.stdout},e=tK){let{input:t,output:r}=n;return t.isTTY!==!0||r.isTTY!==!0?{palette:new Map}:await new Promise(s=>{let o="",i=!1,a=t.isPaused?.()??!1,d,c,l=()=>({foreground:sK(o),background:UM(o),palette:oK(o)}),u=p=>{o+=typeof p=="string"?p:p.toString("latin1");let m=l();if(m.foreground!==void 0&&m.background!==void 0&&m.palette.size===16){f();return}c!==void 0&&clearTimeout(c),c=setTimeout(f,nK),c.unref?.()},f=()=>{if(i)return;i=!0;for(let m of[d,c])m!==void 0&&clearTimeout(m);let p=l();try{(t.off??t.removeListener)?.call(t,"data",u),t.setRawMode?.(!1),a&&t.pause?.()}catch{}s(p)};try{t.setRawMode?.(!0),t.resume?.(),t.on("data",u),r.write(rK())}catch{f();return}d=setTimeout(f,e),d.unref?.()})}function dK(n){let e=/\u001b\[\?997;([12])n/.exec(n);if(e!==null)return e[1]==="1"?"dark":"light"}function cK(n){return n.replace(/\u001b\[\?997;\d+n/g,"")}function zM(n){return n==="dark"?Dn(0,0,0):Dn(255,255,255)}function KM(n,e={}){if(n===null||typeof n!="object")return;let t=n,r=t.onStdin;typeof r=="function"&&(t.onStdin=function(o){let i=o.toString("latin1");if(!aK(i)&&!/\u001b\[\?997;/.test(i)&&!DM(i)){r.call(this,o);return}let a=UM(i),d=dK(i),c=BM(cK(iK(i)));c.length>0&&r.call(this,Buffer.from(c,"latin1")),a!==void 0&&e.onBackground?.(a),d!==void 0&&e.onScheme?.(d)})}var tK,nK,jM,qM,_v=q(()=>{"use strict";Yd();Pv();tK=200,nK=50;jM="\x1B[?2031h",qM="\x1B[?2031l"});import{spawn as lK}from"child_process";import{statSync as of}from"fs";import{homedir as ig}from"os";import{isAbsolute as ag,join as GM,resolve as JM,sep as dg}from"path";import r_ from"string-width";import uK from"wrap-ansi";function $K(n){let e=n.replace(/\r\n?$|\n$/,"");return _K.test(e)?e:null}function OK(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function FK(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function LK(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.links,r=e.links;if(t===void 0!=(r===void 0))return!1;if(t&&r){if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++){let o=t[s],i=r[s];if(o.start!==i.start||o.end!==i.end||o.url!==i.url)return!1}}return!0}function Hv(n,e,t,r=null,s=null,o=null){let i=s===null?"":`a${s}`,a=o===null?"":`s${o.start}:${o.end}${o.toEndOfLine?"f":""}`;return t?`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${r??""}|${i}|${a}`:`${n}|${e}|empty|${r??""}|${i}|${a}`}function ms(n,e){let t=[];for(let r=0;r<n.length;r++){let s=n[r]??"";if(s.length===0){t.push({bufferIdx:r,startCol:0,endCol:0});continue}let o=0;for(;o<s.length;){if(s.length-o<=e){t.push({bufferIdx:r,startCol:o,endCol:s.length}),o=s.length;break}let i=-1;for(let a=o+e-1;a>=o;a--){let d=s[a];if(d===" "||d===" "){i=a+1;break}}i===-1&&(i=o+e),t.push({bufferIdx:r,startCol:o,endCol:i}),o=i}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function no(n,e,t){let r=0,s=0,o=-1;for(let d=0;d<n.length;d++){let c=n[d];if(!(!c||c.bufferIdx!==e.row)&&(o=d,e.col>=c.startCol&&e.col<c.endCol)){r=d,s=e.col-c.startCol,o=-1;break}}if(o!==-1){let d=n[o];d&&(r=o,s=e.col-d.startCol)}let i=Math.min(t,Math.max(1,n.length)),a=0;return n.length>i&&(a=Math.max(0,Math.min(n.length-i,r-(i-1))),r<a&&(a=r),r>=a+i&&(a=r-i+1)),{cursorVisualRow:r,cursorVisualCol:s,windowStart:a,rendered:i}}function s_(n,e){if(e.length===0)return[];if(!n.includes("\x1B")){let c=[],l=n.toLowerCase(),u=0;for(;u<l.length;){let f=l.indexOf(e,u);if(f===-1)break;c.push({start:f,end:f+e.length}),u=f+e.length}return c}let t="",r=[],s=[],o=0;for(;o<n.length;){let c=$r(n,o);if(c!==null&&c.width===0){o+=c.text.length;continue}t+=n[o],r.push(o),s.push(o+1),o+=1}let i=[],a=t.toLowerCase(),d=0;for(;d<a.length;){let c=a.indexOf(e,d);if(c===-1)break;let l=c+e.length-1;i.push({start:r[c],end:s[l]}),d=c+e.length}return i}function NK(n,e,t,r,s=null,o=0,i=!1){if(e.length===0)return;if(r.length===0){to(n,e,t,i);return}let a=0;for(let d of s_(e,r)){if(d.start<a)continue;d.start>a&&to(n,e.slice(a,d.start),t,i);let c=s!==null&&d.start===s;to(n,ug(e.slice(d.start,d.end)),c?"search-highlight-active":"search-highlight",i),a=d.end}a<e.length&&to(n,e.slice(a),t,i)}function df(n){return rI(n)}function to(n,e,t,r=!1){if(e.length===0)return;let s=Qd(n),o=(r?sI(t,s):void 0)??ec(t,s),i=o.transform?o.transform(e):e;s==="none"&&(i=i.replace(pK,""));let a=d=>{d.length>0&&n.noFormat(d)};a(o.open),n.noFormat(i),o.inlineSgr&&fK.test(i)&&a(ns),a(o.close)}function DK(n,e){return e<=0?[n]:n.length===0?[""]:uK(n,e,{hard:!0,trim:!1}).split(`
|
|
253
253
|
`)}function a_(n){i_=n}function d_(n,e,t){if(n==="wide")return!0;if(n==="narrow")return!1;if(t!==void 0)return t;let r=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!/^(ja|ko|zh)(_|\.|@|$)/i.test(r)}function Pt(n){return r_(n,{ambiguousIsNarrow:!i_})}function BK(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 HK(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let s=n.charCodeAt(t);if(s<48||s>63)break;t+=1}for(;t<n.length;){let s=n.charCodeAt(t);if(s<32||s>47)break;t+=1}if(t>=n.length)return null;let r=n.charCodeAt(t);return r<64||r>126?null:n.slice(e,t+1)}function $r(n,e){if(n.charCodeAt(e)===27){let t=BK(n,e);if(t!==null)return{text:t,width:0};let r=HK(n,e);return r!==null?{text:r,width:0}:null}return null}function lg(n){let e=new Array(n.length+1).fill(0),t="",r=0;for(;r<n.length;){e[r]=t.length;let s=$r(n,r);if(s){s.width>0&&(t+="^");for(let o=1;o<s.text.length;o++)e[r+o]=t.length;r+=s.text.length;continue}t+=n[r],r+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function UK(n){let{clean:e,rawToClean:t}=lg(n),r=new Array(e.length+1).fill(n.length);for(let s=n.length;s>=0;s--){let o=t[s];o!==void 0&&(r[o]=s)}return r}function Uv(n,e,t){let r=0,s=e;for(;s<t;){let o=$r(n,s);if(o){s+=o.text.length,o.width>0&&(r+=1);continue}r+=1,s+=1}return r}function Wv(n,e,t){let r=e;for(;t>0&&r<n.length;){let s=$r(n,r);if(s){r+=s.text.length,s.width>0&&(t-=1);continue}r+=1,t-=1}return r}function ug(n){if(!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let r=$r(n,t);if(r){r.width>0&&(e+="^"),t+=r.text.length;continue}e+=n[t],t+=1}return e}function WK(n){if(!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let r=$r(n,t);if(r){if(r.width===0){let s=r.text.charCodeAt(0);(s===94||s===27&&r.text.charCodeAt(1)===91)&&(e+=r.text)}t+=r.text.length;continue}t+=1}return e}function c_(n){if(!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if($r(n,e))return!0;return!1}function ZM(n,e){return n.indexOf("\x1B",e)}function*Kv(n){let e=0;for(;e<n.length;){let t=$r(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let r=n.length,s=ZM(n,e);for(;s!==-1&&s<n.length;){if($r(n,s)){r=s;break}s=ZM(n,s+1)}if(r===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:o}of zv.segment(n.slice(e,r)))yield{text:o,width:Pt(o)};e=r}}function jK(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let r=t.escapeAware===!0&&c_(n);return!r&&!o_.test(n)?qK(n,e):zK(n,e,r)}function qK(n,e){let t=[],r=n;for(;r.length>e;){let s=r.slice(0,e+1),o=-1;for(let i=Math.min(e,s.length-1);i>=0;i--)if(s[i]===" "){o=i;break}o<=0?(t.push(r.slice(0,e)),r=r.slice(e)):(t.push(r.slice(0,o)),r=r.slice(o+1))}return t.push(r),t}function zK(n,e,t){let r=[],s=t?[...Kv(n)]:KK(n),o=0;for(;o<s.length;){let i="",a=0,d=-1,c="";for(;o<s.length;){let l=s[o];if(a+l.width>e){l.text===" "&&l.width===1&&(d=o,c=i);break}l.text===" "&&l.width===1&&(d=o,c=i),i+=l.text,a+=l.width,o+=1}if(o>=s.length){r.push(i);break}d>=0?(r.push(c),o=d+1):i.length===0?(r.push(s[o].text),o+=1):r.push(i)}return r}function KK(n){let e=[];for(let{segment:t}of zv.segment(n))e.push({text:t,width:Pt(t)});return e}function mn(n,e,t={}){if(e<=0)return"";let r=t.escapeAware===!0&&c_(n);if(!r&&n.length<=e&&!o_.test(n))return n;if(!r)return Pt(n)<=e?n:e<=1?qv(n,e):qv(n,e-1)+"\u2026";let s=[...Kv(n)],o=0;for(let i of s)o+=i.width;return o<=e?n:e<=1?e_(s,e):e_(s,e-1)+"\u2026"}function qv(n,e){if(e<=0)return"";let t="",r=0;for(let{segment:s}of zv.segment(n)){let o=Pt(s);if(r+o>e)break;t+=s,r+=o}return t}function e_(n,e){if(e<=0)return"";let t="",r=0;for(let s of n){if(r+s.width>e)break;t+=s.text,r+=s.width}return t}function GK(n,e,t){if(n<=t||t<=0)return 0;let r=Math.floor((t-1)/2);return Math.max(0,Math.min(e-r,n-t))}function JK(n,e,t,r){if(e<=r||r<=0)return 0;let s=e-r,o=Math.max(0,Math.min(n,s));return t<o?o=t:t>o+r-1&&(o=t-r+1),Math.max(0,Math.min(o,s))}function jv(n,e){let t=Math.max(0,e-1),r=[],s=" \xB7 ",o="";for(let i of n){let a=o.length===0?i.label:`${s}${i.label}`;if(1+Pt(o)+Pt(a)>t)break;let d=1+Pt(o)+Pt(a)-Pt(i.label)+1;o+=a,i.action!==void 0&&r.push({start:d,end:d+Pt(i.label)-1,action:i.action})}return{text:o,spans:r}}function t_(n,e,t,r){let s=Math.max(0,e-1),o=n.rows.length>1,i=o?Math.max(...n.rows.map((c,l)=>`${l+1}. `.length)):0,a=Math.max(0,...n.rows.map(c=>Pt(c.kind==="text"?`${c.label} `:c.label))),d=[];for(let c=t;c<Math.min(n.rows.length,t+r);c++){let l=n.rows[c];if(!l)continue;let u=c===n.selectedIndex,f=u?"\u276F":" ",p=o?`${c+1}. `.padStart(i):"";if(l.kind==="text"){let k=mn(` ${f} ${p}${l.label} `,s),{field:S,caretOffset:I,fieldStart:x}=QK(l.text,l.cursor,s-Pt(k));d.push({kind:"text",index:c,selected:u,body:"",prefix:k,field:S,fieldStart:x,caretCol:1+Pt(k)+I,sig:`form|r|${e}|${c}|${u?1:0}|text|${k}|${S}`});continue}let m=` ${f} ${p}`,h=l.kind==="choice"?l.current===!0?"\u2022 ":" ":"",g=l.kind==="select"?l.value:l.note??"",w=g.length>0?`${h}${YK(l.label,a)} ${g}`:`${h}${l.label}`,b=`${m}${mn(w,s-Pt(m))}`;d.push({kind:l.kind,index:c,selected:u,body:b,prefix:"",field:"",fieldStart:0,caretCol:1,sig:`form|r|${e}|${c}|${u?1:0}|${l.kind}|${b}`})}return d}function YK(n,e){let t=e-Pt(n);return t>0?n+" ".repeat(t):n}function QK(n,e,t){if(t<=0)return{field:"",caretOffset:0,fieldStart:0};let r=Math.max(0,Math.min(e,n.length));if(Pt(n)+1<=t)return{field:n,caretOffset:Pt(n.slice(0,r)),fieldStart:0};let s=r,o=1;for(;s>0;){let i=Pt(n[s-1]??"");if(o+i>t)break;o+=i,s-=1}return{field:qv(n.slice(s),t),caretOffset:Pt(n.slice(s,r)),fieldStart:s}}function XK(n){let e=n.indexOf(`
|
|
254
254
|
`);return e===-1?n:`${n.slice(0,e)} \u21B5`}function pg(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_X_CTRL_E":return"ctrl-x-ctrl-e";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function Ii(){let n=[ns,jc,qc,oE,zc,iE,wk,Po,$a,Oa,_a,Ma,"\x1B>",Lu,wm,bm,qM,"\x1B]9;4;0\x07",eE].join("");try{we(n)}catch{}}function l_(n){let e=[["width",80],["height",24]];for(let[t,r]of e){let s=Object.getOwnPropertyDescriptor(n,t);if(s&&s.get)continue;let o=Symbol(`raw-${t}`),i=n;i[o]=s?s.value:void 0,Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){let a=this[o];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:r},set(a){this[o]=a}})}}function n_(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 fK,pK,nl,rl,hK,Ka,VM,$v,Ov,mK,YM,gK,$t,Bt,yK,Ht,cg,QM,wK,af,Fv,bK,kK,Lv,vK,SK,XM,xK,IK,CK,RK,Nv,Dv,Bv,AK,TK,EK,PK,MK,_K,fg,o_,zv,i_,VK,Gv=q(()=>{"use strict";rv();Qm();cv();Xm();Hm();rt();vv();ng();gv();ke();ir();Um();xv();Av();To();zm();Du();OM();qm();tv();LM();Tv();Tn();_v();sa();na();Fa();fK=/\x1b\[[0-9;]*m/,pK=/\x1b\[[0-9;]*m/g,nl=500,rl=1,hK=700,Ka=/[A-Za-z0-9_:\-]/,VM=/[:\-]/,$v=/[A-Za-z0-9_./\-~+@]/,Ov=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,mK=/[.,;:!?)\]}'"]/,YM=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,gK=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,$t=1,Bt=0,yK=1,Ht=1,cg=8,QM=20,wK=36,af=2,Fv=1,bK=80,kK=12,Lv=5,vK=12,SK=12,XM=350,xK=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"1-9 quick-pick"}],IK=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"y/n quick-pick"}],CK=3,RK=30,Nv=6,Dv=4,Bv=2,AK=1e3,TK=1e4,EK=30,PK=.45,MK=2,_K=/^(https?|ftp):\/\/\S+$/;fg=class n{term;dispatcher;onKey;onSidebarCollapseChange;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 sg;sidebarBorder="frame";sidebarSnapshot=pM();sidebarRowPaths=new Map;sidebarRowDoubleActions=new Map;sidebarRowLinks=new Map;sidebarRowActions=new Map;sidebarPages={};sidebarCollapsed=new Set;lastSidebarClick=null;sidebarScrollOffset=0;sidebarOverflowRows=0;permissionPrompt=null;formPrompt=null;formRowHits=new Map;formHintHits=[];formRegion=null;formPressHit=null;formWindowTop=0;formWindowKey=null;permissionRowHits=new Map;permissionHintHits=[];permissionRegion=null;permissionPressHit=null;permissionArmedAt=0;confirmPrompt=null;compactionPrompt=null;compactionRowHits=new Map;compactionHintHits=[];compactionRegion=null;compactionPressHit=null;compactionArmedAt=0;helpRegion=null;helpPressed=!1;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;slideTarget=0;slideTimer=null;slideEnabled;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;workspaceIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayScroll=0;btwOverlayRegion=null;btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:Jk,queued:0};barHits=new Map;hoveredBarHit=null;composerBottomRow=null;hintZoneStart=null;hintHoverReveal=!1;hintHoverHideTimer=null;hintKeyReveal=!1;barPressHit=null;lastBarClick=null;onBarAction;onFormClick;onPermissionClick;onCompactionClick;onHelpClick;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};barConfig={composer:{top:{left:Qi,right:Xi},bottom:{left:Fd,right:Ld}},sessionbar:{left:Nd,right:Dd}};scriptOutputs=new Map;lastWindowTitle=null;lastReportedCwd=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;selectionGranularity="char";selectionAnchorWordBounds=null;selectionAnchorLineId=null;promptSelectionAnchor=null;promptSelectionDragStarted=!1;promptSelection=null;promptSelectionGranularity="char";promptSelectionAnchorWordBounds=null;promptSelectionAnchorLineRow=null;promptDoubleClickPending=!1;promptPendingClickCount=1;promptLastLeftClick=null;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;chordMatcher=new wi(UP);mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;openFileForeground;runForeground;foregroundChildActive=!1;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=o=>{this.selection!==null&&o.length>0&&this.clearSelection(),this.promptSelection!==null&&o.length>0&&this.clearPromptSelection(),t(o)},this.onBlockClick=e.onBlockClick,this.onSidebarCollapseChange=e.onSidebarCollapseChange,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onBarAction=e.onBarAction,this.onFormClick=e.onFormClick,this.onPermissionClick=e.onPermissionClick,this.onCompactionClick=e.onCompactionClick,this.onHelpClick=e.onHelpClick,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.onLayoutChange=e.onLayoutChange,this.contentRepaintThrottleMs=e.repaintThrottleMs??AK,this.painter=new el(this.term),this.scheduler=new Jm({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??TK,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let r=e.openFileCommand,s=typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):r;this.openFileCommand=s&&s.length>0?s:null,this.openFileForeground=e.openFileInTerminal??e.openFileSource==="env",this.runForeground=e.runForeground??Km,this.progressIndicatorEnabled=e.progressIndicator??!0,this.slideEnabled=e.turnSlide??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>{this.painter.clearCache(),this.sidebarRenderer.invalidate(),this.onLayoutChange?.(),this.repaint()},this.keyHandler=(o,i,a)=>this.handleKey(o,a),this.mouseHandler=(o,i)=>this.handleMouse(o,i),this.rawStdinHandler=o=>this.handleRawStdin(o)}start(e={}){this.started||(this.started=!0,Sv(!1),e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,we(yk),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),ge({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&&(Sv(!0),this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.cancelHintHoverHide(),this.cancelSlide(),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),ge({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(we(bm),this.currentPointerShape="default"),e.keepFullscreen||we(Lu),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Ii(),this.term.fullscreen(!1),this.term(`
|
|
255
255
|
`)))}installBracketedPaste(){we(ym),we(rE),we(sE),we(nE),we(km);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(){we(Po),we($a),we(Oa),we(_a),we(Nu),we(Ma),we("\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,we(aE),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(we(wk),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Ii(),this.onProcessSignal=e=>{Ii(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Ii(),process.stderr.write(`
|
|
@@ -260,29 +260,29 @@ uncaught: ${e.stack??e.message}
|
|
|
260
260
|
`);this.pasteBuffer="";let a=FP(i);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:i}]);continue}let s=e.indexOf(t);if(s===-1){let o=$K(e);o!==null?this.onKey([{type:"paste",text:o}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}s>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,s),"binary")),e=e.slice(s+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<bK)return 0;let t=this.sidebarConfiguredWidth??Math.min(wK,Math.max(QM,Math.floor(e*.28))),r=e-kK-af-Fv;return Math.min(t,Math.max(QM,r))+af+Fv}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-af-Fv}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.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarRowLinks.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()}setSidebarProcessGadgets(e){this.sidebarRenderer.setProcessGadgets(e.map(fM)),this.scheduleRepaint()}isSidebarGadgetConfigured(e){return this.sidebarRenderer.isConfigured(e)}isSidebarGadgetActive(e){return this.sidebarRenderer.isConfigured(e)&&!this.sidebarCollapsed.has(e)}toggleSidebarGadgetCollapsed(e){let t=!this.sidebarCollapsed.has(e);return t?this.sidebarCollapsed.add(e):this.sidebarCollapsed.delete(e),this.sidebarRenderer.invalidate(),this.onSidebarCollapseChange?.(e,t),t}setSidebarCollapsed(e){this.sidebarCollapsed=new Set(e),this.sidebarRenderer.invalidate()}sidebarCollapsedIds(){return[...this.sidebarCollapsed]}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()}setScriptOutput(e,t){if(t===null){if(!this.scriptOutputs.has(e))return;this.scriptOutputs.delete(e)}else{if(this.scriptOutputs.get(e)===t)return;this.scriptOutputs.set(e,t)}this.scheduleRepaint()}setProcessOutput(e,t){let r=this.sidebarSnapshot.processOutputs.get(e);if(t===null){if(r===void 0)return;let s=new Map(this.sidebarSnapshot.processOutputs);s.delete(e),this.sidebarSnapshot={...this.sidebarSnapshot,processOutputs:s}}else{if(r===t)return;let s=new Map(this.sidebarSnapshot.processOutputs);s.set(e,t),this.sidebarSnapshot={...this.sidebarSnapshot,processOutputs:s}}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){if(e!==0){if(this.scrollOffset>0){this.cancelSlide(!0),this.scrollOffset=Math.max(0,this.scrollOffset+e);return}this.slideTimer!==null&&(this.slideTarget=Math.max(0,this.slideTarget+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 r of e)t+=this.wrappedRowsOf(r);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 r of t)this.forgetLine(r);this.invalidateSelectionIfTouches(t);for(let[r,s]of[...this.keyedBlocks.entries()])s.start-=e,s.start<0&&this.keyedBlocks.delete(r)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let i of t)i.blockKey=e;let r=this.keyedBlocks.get(e),s=!1,o=0;if(r){let i=r.start+r.count;s=i>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(r.start,i)),d=t.length-r.count,c=this.lines.slice(r.start,i),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=c[f],m=t[f];p!==void 0&&LK(p,m)?l[f]=p:(p!==void 0&&u.push(p),l[f]=m)}for(let f=t.length;f<c.length;f++)u.push(c[f]);this.lines.splice(r.start,r.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),r.count=t.length,d!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>r.start&&(p.start+=d);o=this.wrappedRowsOfMany(t)-a}else s=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),o=this.wrappedRowsOfMany(t);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(o),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,r,s){if(e.length===0)return;let o=e.split(`
|
|
261
261
|
`),[i,...a]=o,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+=i??"",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:i??"",bodyStyle:r};s!==void 0&&(l.prefixStyle=s),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:r};this.lines.push(u),this.trackLine(u),d+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setBarConfig(e){this.barConfig=tf(e),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.syncReportedCwd(),vM({sessionId:this.sessionbar.sessionId,agent:this.sessionbar.agent,title:this.sessionbar.title,model:this.sessionbar.model,costAmount:this.sessionbar.usage?.costAmount,cwd:this.sessionbar.cwd}),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=e&&e.length>0?e:"New Hydra Session",s=(this.readonly?`${t} [VIEW ONLY]`:t).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);s!==this.lastWindowTitle&&(this.lastWindowTitle=s,we(`\x1B]0;${s}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,we("\x1B]0;\x1B\\")}syncReportedCwd(){let e=this.sessionbar.cwd?.trim();e&&e!==this.lastReportedCwd&&(this.lastReportedCwd=e,Cv(e))}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),SM({status:this.banner.status,queued:this.banner.queued}),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&pt(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}sessionTitle(){return this.sessionbar.title}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()))}setWorkspaceIndicator(e){this.workspaceIndicator!==e&&(this.workspaceIndicator=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)),ge({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 r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.sourceLineId),o=r<s||r===s&&e.offset<=t.offset,i=o?e:t,a=o?t:e;if(i.sourceLineId===a.sourceLineId&&i.offset===a.offset){this.clearSelection();return}let d={startLineId:i.sourceLineId,startOffset:i.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,r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.startLineId),o=this.lineIndexById(t.endLineId);if(r<0||s<0||o<0)return null;let i=(u,f,p,m)=>u!==p?u-p:f-m,a=i(r,e.offset,s,t.startOffset),d=i(r,e.offset,o,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(r-s)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(r-o)*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 r=e.loIdx;r<=e.hiIdx;r++){let s=this.lines[r];if(!s)continue;let o=this.lineIds.get(s),i=o===void 0?void 0:e.byId.get(o);if(!i)continue;let d=(s.body??"").slice(i.start,i.end);(df(s.bodyStyle)||s.ansi)&&(d=ug(d)),t.push(d)}return t.join(`
|
|
262
262
|
`)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),r=this.lineIndexById(e.endLineId);if(t===-1||r===-1)return null;let s=t,o=r,i=e.startOffset,a=e.endOffset;t>r&&(s=r,o=t,i=e.endOffset,a=e.startOffset);let d=new Map,c=-1;for(let l=o;l>=s;l--){let u=this.lines[l];if(u&&!this.isHiddenLine(u)){c=l;break}}for(let l=s;l<=o;l++){let u=this.lines[l];if(!u||this.isHiddenLine(u))continue;let f=this.lineIds.get(u);if(f===void 0)continue;let p=(u.body??"").length,m=l===s?Math.max(0,Math.min(p,i)):0,h=l===o?Math.max(0,Math.min(p,a)):p;d.set(f,{start:m,end:h,toEnd:l<c})}return{loIdx:s,hiIdx:o,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let r=this.wrapOrigin.get(e);if(!r)return null;let s=t.get(r.sourceLineId);if(!s)return null;let o=r.sourceColOffset,i=r.bodyDisplayShift??0,a=r.sourceColEnd??o+e.body.length-i,d=Math.max(s.start,o),c=Math.min(s.end,a);if(c<=d)return null;let l,u;if(r.sourceColEnd!==void 0){let f=this.sourceBodyForId(r.sourceLineId);if(f===null)return null;let p=Uv(f,o,d),m=Uv(f,d,c);l=Wv(e.body,i,p),u=Wv(e.body,l,m)}else l=d-o+i,u=c-o+i;return{start:l,end:u,toEndOfLine:s.toEnd||s.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.workspaceIndicator!==null?{text:this.workspaceIndicator,kind:"workspace"}: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 r=this.lineIds.get(t);if(r!==void 0&&(r===this.selection.startLineId||r===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 r=t.start+t.count,s=r>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(t.start,r)),i=this.lines.splice(t.start,t.count);for(let a of i)this.forgetLine(a);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-o),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 r=this.lines.splice(e.start,e.count);for(let[s,o]of this.keyedBlocks)s!==this.stickyBottomKey&&o.start>=t&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...r),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count>=this.lines.length,s=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),o=this.lines.splice(t.start,t.count);for(let i of o)this.forgetLine(i);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>t.start&&(i.start-=t.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-s),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let r=[...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),s=r.findIndex(d=>d.key===e);if(s<0)return[];let o=(d,c)=>{for(let[l,u]of this.keyedBlocks)if(!t.has(l)&&u.start>=d&&u.start<c)return!0;return!1},i=s;for(;i>0&&!o(r[i-1].start+r[i-1].count,r[i].start);)i--;let a=s;for(;a<r.length-1&&!o(r[a].start+r[a].count,r[a+1].start);)a++;return r.slice(i,a+1).map(d=>d.key)}setRunCollapsed(e,t,r){if(e.length===0)return;let s=e[0];if(!this.keyedBlocks.has(s))return;this.upsertLines(s,r);let o=this.keyedBlocks.get(s),i=o.start+o.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(i=Math.max(i,d.start+d.count))}for(let a=o.start+o.count;a<i;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,we(yk),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.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),IM(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(t=>({...t}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==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.compactionArmedAt=Date.now()),this.compactionPrompt=e?{...e}:null,e===null&&(this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion=null,this.compactionPressHit=null),this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,e===null&&(this.helpRegion=null,this.helpPressed=!1),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.btwOverlayScroll=0,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 r=this.btwOverlayUsage,s=e.usage;(!r||r.used!==s.used||r.size!==s.size||r.costAmount!==s.costAmount||r.costCurrency!==s.costCurrency)&&(this.btwOverlayUsage={...s},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let r=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){r=!1;break}if(r)return}let t=this.btwOverlayLines.length;if(this.btwOverlayLines=[...e],this.btwOverlayScroll>0&&e.length>t){let r=this.term.width,s=0;for(let o=t;o<this.btwOverlayLines.length;o++)s+=r>4?this.wrapOne(this.btwOverlayLines[o],r).length:1;this.btwOverlayScroll+=s}this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,r=this.btwOverlayStatus===e.style;t&&r||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayRegion=null,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((r,s)=>{let o=this.completions[s];return o!==void 0&&o.name===r.name&&o.description===r.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,r=t!==void 0&&t.start+t.count===this.lines.length,s=r?t.start-1:this.lines.length-1;if(s<0)return;let o=this.lines[s];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),r?(this.lines.splice(t.start,0,i),t.start+=1):this.lines.push(i),this.trackLine(i),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(i)),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&&ge({tag:"key",name:e,isChar:!!t.isCharacter}),t.isCharacter){this.chordMatcher.clear(),this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.chordMatcher.clear(),this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.chordMatcher.clear(),this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.chordMatcher.clear(),this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.chordMatcher.clear(),this.scrollToNextTurn();return}let r=pg(e);if(r){this.dispatchKeyName(r);return}e.startsWith("CTRL_")&&(this.chordMatcher.clear(),this.revealHints())}dispatchKeyName(e){let t=this.chordMatcher.feed(e);switch(t.kind){case"pass":this.onKey([{type:"key",name:t.token}]);return;case"armed":return;case"aborted":this.revealHints();return}}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let u=e==="MOUSE_WHEEL_UP"?3:-3,f=this.mouseCell(t);if(f!==null&&this.isFormCell(f.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(f!==null&&this.isCompactionCell(f.y)){this.stepCompactionCursor(e==="MOUSE_WHEEL_UP"?-1:1);return}if(f!==null&&this.isSidebarCell(f.x,f.y)&&this.scrollSidebarBy(u)||f!==null&&this.isBtwOverlayCell(f.y)&&this.scrollBtwOverlayBy(u))return;this.scrollBy(u);return}let s=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||s)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let i=this.mouseCell(t),a=FK(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&i!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:i.x,y:i.y,name:e});let c=i!==null?this.barHitAt(i.x,i.y):null;if(d==="move"){let u=c?.id??null,f=i!==null&&i.y===this.composerBottomRow&&this.hintZoneStart!==null&&i.x>=this.hintZoneStart,p=this.trackHintHover(f);if((u!==this.hoveredBarHit||p)&&(this.hoveredBarHit=u,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),i!==null&&this.isPermissionCell(i.y)){let m=this.permissionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.permissionPrompt!==null&&m.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isCompactionCell(i.y)){let m=this.compactionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.compactionPrompt!==null&&m.index!==this.compactionPrompt.selectedIndex&&this.onCompactionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isFormCell(i.y)){let m=this.formHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="row"&&this.formPrompt!==null&&m.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:m.row,select:!0})}}let l=i!==null&&c===null&&this.barHits.get(i.y)===void 0&&i.x>=1&&i.x<=this.transcriptVisibleWidth();if(i!==null&&l&&d!=="release"){let u=this.keyAndSubAtRow(i.y),f=u!==null&&u.key.startsWith("agent:")?null:u;if(f===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(i.y),m=this.nearestKeyBelowRow(i.y);p!==null&&m!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(m)&&(f={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(f!==null?"pointer":"default"),d==="move"){let p=f?.key??null,m=f?.sub??null;(p!==this.hoveredBlockKey||m!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=m,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(i!==null&&!l&&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 u=this.lastLeftClick;if(u!==null&&i!==null&&Math.abs(i.x-u.x)<=rl&&Math.abs(i.y-u.y)<=rl&&Date.now()-u.t<=nl||this.flushPendingBlockClick(),i!==null&&this.handleBarPress(i)){this.pressCell=null;return}if(i!==null&&this.handlePermissionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleCompactionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleHelpPress(i)){this.pressCell=null;return}if(i!==null&&this.handleFormPress(i)){this.pressCell=null;return}if(this.handleSidebarPress(i)){this.pressCell=null,this.clearSelection();return}if(this.pressCell=i,i!==null&&this.handlePromptSelectionPress(i)){this.lastLeftClick=null;return}this.handleSelectionPress(i,OK(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&i!==null&&this.extendSelectionByClick(i))){if(e==="MOUSE_DRAG"&&i!==null){if(this.promptSelectionAnchor!==null){this.handlePromptSelectionDrag(i);return}this.handleSelectionDrag(i);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"){if(this.handleBarRelease(i)){this.pressCell=null;return}if(this.handlePermissionRelease(i)){this.pressCell=null;return}if(this.handleCompactionRelease(i)){this.pressCell=null;return}if(this.handleHelpRelease(i)){this.pressCell=null;return}if(this.handleFormRelease(i)){this.pressCell=null;return}let u=this.pressCell;if(this.pressCell=null,this.promptSelectionAnchor!==null){this.handlePromptSelectionRelease(i);return}let f=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(u!==null&&i!==null&&i.x===u.x&&i.y===u.y&&!f&&this.onBlockClick){let p=this.keyAndSubAtRow(i.y),m=p?.key??null;if(m!==null){let h=i.y;for(;h>1&&this.keyAtRow(h-1)===m;)h-=1;this.schedulePendingBlockClick(m,i.y-h,p?.sub??null)}}(i===null||!this.isSidebarCell(i.x,i.y))&&this.handleSelectionRelease(i)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,this.selectionGranularity="char",this.selectionAnchorWordBounds=null,this.selectionAnchorLineId=null,!this.inAppSelectionEnabled||e===null)return;let r=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(r===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(r)){this.lastLeftClick=null;return}this.selectionAnchor=r;let s=Date.now(),o=this.lastLeftClick,i=o!==null&&s-o.t<=nl&&Math.abs(e.x-o.x)<=rl&&Math.abs(e.y-o.y)<=rl&&o.sourceLineId!==null&&o.sourceLineId===r.sourceLineId;if(i&&o.count===2&&e.x===o.x&&e.y===o.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(r.sourceLineId),this.selectionGranularity="line",this.selectionAnchorLineId=r.sourceLineId,this.doubleClickPending=!0;return}if(i&&o.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(r,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(r);c!==null&&(this.setSelection({sourceLineId:r.sourceLineId,offset:c.start},{sourceLineId:r.sourceLineId,offset:c.end}),this.doubleClickPending=!0,this.selectionGranularity="word",this.selectionAnchorWordBounds={sourceLineId:r.sourceLineId,start:c.start,end:c.end})}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let r=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:r})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null)return;this.extendSelectionForGesture(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()}extendSelectionForGesture(e){this.selectionGranularity==="word"?this.extendWordSelectionToCell(e):this.selectionGranularity==="line"?this.extendLineSelectionToCell(e):this.extendSelectionToCell(e)}extendWordSelectionToCell(e){if(this.selectionAnchorWordBounds===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.selectionAnchorWordBounds,s=this.lineIndexById(r.sourceLineId),o=this.lineIndexById(t.sourceLineId);if(s<0||o<0)return;let i=o<s||o===s&&t.offset<r.start,a=o>s||o===s&&t.offset>r.end,d={sourceLineId:r.sourceLineId,offset:r.start},c={sourceLineId:r.sourceLineId,offset:r.end};if(i){let l=this.wordBoundsAt(t);d=l!==null?{sourceLineId:t.sourceLineId,offset:l.start}:t}else if(a){let l=this.wordBoundsAt(t);c=l!==null?{sourceLineId:t.sourceLineId,offset:l.end}:t}this.selectionDragStarted=!0,this.setSelection(d,c)}extendLineSelectionToCell(e){if(this.selectionAnchorLineId===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.lineIndexById(this.selectionAnchorLineId),s=this.lineIndexById(t.sourceLineId);if(r<0||s<0)return;let o=s<=r?t.sourceLineId:this.selectionAnchorLineId,i=s<=r?this.selectionAnchorLineId:t.sourceLineId,a=this.lineById(i);a!==null&&(this.selectionDragStarted=!0,this.setSelection({sourceLineId:o,offset:0},{sourceLineId:i,offset:(a.body??"").length}))}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let r=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return r===null?!1:this.extendSelectionByClickResolved(r)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let r=this.contentWidth(),{rows:s}=this.wrapTail(r,t+this.scrollOffset),o=s.length-this.scrollOffset,i=Math.max(0,o-t),a=s.slice(i,o),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 m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:0}}}if(c>=t-1&&u){let p=this.lines[this.lines.length-1];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let r=this.scrollbackVisibleRows();if(r<=0)return null;let s=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let o=1;o<r;o++){let i=t-o;if(i>=1){let d=this.resolveCellToSource(s,i);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+o;if(a<=r){let d=this.resolveCellToSource(s,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 r=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===r){this.stopAutoscroll();return}this.extendSelectionForGesture(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,r=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let s=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:s?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||r){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=lg(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length,a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!Ka.test(s[a])&&!Ov.test(s[a]))return null;let d=a;for(;d>0&&Ov.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&Ov.test(s[c]);)c++;for(;c>d+1&&mK.test(s[c-1]);)c--;if(s.slice(d,c).includes("://")){let p=d,m=c;return this.projectCleanRangeToRaw(o,r.length,p,m)}if(!Ka.test(s[a]))return null;let u=a;for(;u>0&&Ka.test(s[u-1]);)u--;let f=a+1;for(;f<s.length&&Ka.test(s[f]);)f++;for(;f>u+1&&VM.test(s[f-1]);)f--;for(;u<f-1&&VM.test(s[u]);)u++;return this.projectCleanRangeToRaw(o,r.length,u,f)}projectCleanRangeToRaw(e,t,r,s){let o=t,i=t;for(let a=0;a<e.length;a++)if(e[a]===r&&o===t&&(o=a),e[a]===s&&i===t){i=a;break}return{start:o,end:i}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=lg(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;if(t.links){for(let p of t.links)if(i>=p.start&&i<p.end){let m=p.url,h=m.startsWith("file://")?m.slice(7):m,g=null,w=h.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(h=w[1],g=Number.parseInt(w[2],10)),{raw:h,line:g}}}let a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!$v.test(s[a]))return null;let d=a;for(;d>0&&$v.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&$v.test(s[c]);)c++;let l=s.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let u=null,f=s.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 r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=lg(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;for(let a of t.links)if(i>=a.start&&i<a.end)return a.url;return null}osc8UrlFor(e){if(YM.test(e))return null;if(e.startsWith("file://"))return Qc(this.sessionbar)?null:e;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;if(Qc(this.sessionbar))return null;let t=e.indexOf("#"),r=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t);if(r.length===0)return null;let o=r;return r==="~"||r.startsWith("~/")?o=r==="~"?ig():`${ig()}/${r.slice(2)}`:ag(r)||(o=JM(this.sessionbar.cwd,r)),Vb(o+s)}linkSpansForWindow(e,t,r,s,o){let i=UK(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=i[d.start]??e.length,u=i[d.end]??e.length,f=Math.max(l,r),p=Math.min(u,s);p>f&&a.push({start:f-r+o,end:p-r+o,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?ig():`${ig()}/${t.slice(2)}`);let r=ag(t)||e.startsWith("~"),s=ag(t)?t:JM(this.sessionbar.cwd,t);if(r)return s;try{if(of(s).isFile())return s}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+r)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.raw;if(!gK.test(r))return!1;let s=r.startsWith(sn)?[r]:[sn+r,r],o=null;for(let i of s)try{if(of(D.sessionFile(i)).isFile()){o=i;break}}catch{}return o===null?!1:this.onHydraLinkClick(o)}dispatchLinkUrl(e){let t=e.match(YM);if(t){let o=t[1]??null;return o!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(o):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let r=e;if(r.startsWith("file://")){let o=r.slice(7),i=o.indexOf("/");r=i===-1?"":o.slice(i);try{r=decodeURIComponent(r)}catch{}}if(r.length===0)return!1;let s=r.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return s?this.tryOpenPathString(`${s[1]}:${s[2]}`):this.tryOpenPathString(r)}tryOpenLinkAt(e,t){let r=this.findLinkUrlAt(e);if(r!==null)return this.dispatchLinkUrl(r);let o=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(o!==void 0)return this.dispatchLinkUrl(o);if(t!==null){let i=this.blockLinkUrlAt(t);if(i!==null)return this.dispatchLinkUrl(i)}return!1}reconcileWorkspacePath(e){let t=GM(D.home(),"workspaces")+dg;if(!e.startsWith(t))return e;let s=this.sessionbar.cwd;if(s.length>0&&(e===s||e.startsWith(s+dg)))return e;let o=!1;try{of(e),o=!0}catch{o=!1}if(o)return this.notify("opening a file in a workspace this session left \u2014 edits there will not reach your project",5e3),e;let i=e.slice(t.length).split(dg).slice(2).join(dg);if(i.length>0&&s.length>0){let a=GM(s,i);try{if(of(a).isFile())return this.notify("that workspace is gone \u2014 opened the file in your project instead",4e3),a}catch{}}return this.notify("that file was in a workspace that no longer exists",4e3),null}tryOpenPathString(e){if(Qc(this.sessionbar))return this.notify(`can't open \u2014 this session's files are on ${this.sessionbar.remote}`,4e3),!0;if(this.openFileCommand===null)return!1;let t=e,r=null,s=e.match(/^(.*?):(\d+)(?::\d+)?$/);s&&(t=s[1],r=Number.parseInt(s[2],10));let o=this.resolvePathToken(t);if(o===null)return!1;let i=this.reconcileWorkspacePath(o);if(i===null)return!1;let a=FM(this.openFileCommand,i,r);if(a===null)return!1;let d=r===null?i:`${i}:${r}`;if(this.openFileForeground)return this.openInForeground(a,d),!0;try{let c=lK(a.program,a.args,{detached:!0,stdio:"ignore",cwd:this.spawnCwd()});c.on("error",l=>{this.notify(`open file failed: ${l.message}`)}),c.unref(),this.notify(`opening ${d}`)}catch(c){this.notify(`open file failed: ${c.message}`)}return!0}spawnCwd(){let e=this.sessionbar.cwd;if(!(!e||!ag(e)))try{return of(e).isDirectory()?e:void 0}catch{return}}openInForeground(e,t){this.foregroundChildActive||(this.foregroundChildActive=!0,this.runForeground({program:e.program,args:e.args,cwd:this.spawnCwd(),banner:`\u2500 ${e.program} ${t} \u2014 quit the editor to return to hydra \u2500
|
|
263
|
-
`},{suspend:()=>this.stop(),resume:()=>this.start(),notify:r=>this.notify(r)}).finally(()=>{this.foregroundChildActive=!1}))}schedulePendingBlockClick(e,t,r){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t,r);return}this.cancelPendingBlockClick();let s=this.onBlockClick,o=setTimeout(()=>{this.pendingBlockClick=null,s(e,t,r)},nl);typeof o.unref=="function"&&o.unref(),this.pendingBlockClick={timer:o,key:e,rowOffset:t,subKey:r}}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 r=this.lines[t];if(r&&this.lineIds.get(r)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Zc(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===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,r=Number(t.x),s=Number(t.y);return!Number.isFinite(r)||!Number.isFinite(s)?null:{x:r,y:s}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,we(e==="pointer"?cE:bm))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null||t.startsWith("agent:"))return null;let r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let{rows:i}=this.wrapTail(r,o+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-o),c=i.slice(d,a),l=Math.max(0,o-c.length),u=e-s-l,f=d+u,p=null,m=1/0;for(let h=0;h<i.length;h++){let g=i[h];if(g.blockKey!==t||g.linkSpans===void 0||g.linkSpans.length===0)continue;let w=Math.abs(h-f);w<m&&(m=w,p=g.linkSpans[0]?.url??null)}return p}keyAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-l;return u<0||u>=c.length?null:c[u]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let r=this.keyAtRow(t);if(r!==null)return r}return null}nearestKeyBelowRow(e){let r=this.scrollbackVisibleRows();for(let s=e+1;s<=r;s++){let o=this.keyAtRow(s);if(o!==null)return o}return null}keyAndSubAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-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 r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let i=t-s;if(i<0||i>=o||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(r,o+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-o),l=a.slice(c,d),u=Math.max(0,o-l.length),f=i-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=Pt(p.prefix??""),g=m.bodyDisplayShift??0,w=e-1-h;if(w<g)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let b=w,S=df(p.bodyStyle)||p.ansi===!0?$M(Kv(p.body),b):_M(p.body,b);if(m.sourceColEnd!==void 0){let I=this.sourceBodyForId(m.sourceLineId);if(I!==null){let x=Uv(p.body,g,S),A=Wv(I,m.sourceColOffset,x);return{sourceLineId:m.sourceLineId,offset:A}}}return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset+S-g}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),r=Math.min(t,Math.max(0,this.scrollOffset+e));r!==this.scrollOffset&&(this.scrollOffset=r,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){if(this.pageWhenNoTurns(1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=e.find(s=>s>t);this.stepToTurnStop(r??this.maxScrollOffset())}scrollToNextTurn(){if(this.pageWhenNoTurns(-1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=0;for(let s of e){if(s>=t)break;r=s}this.stepToTurnStop(r)}pageWhenNoTurns(e){return this.turnScrollOffsets().length>0?!1:(this.scrollBy(e*this.scrollPageSize()),!0)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),t=[0,...this.turnScrollOffsets(),e].filter(r=>r>=0&&r<=e).sort((r,s)=>r-s);return t.filter((r,s)=>s===0||r!==t[s-1])}notifyTurnPosition(e){let t=this.turnScrollOffsets();if(t.length===0)return;let r=t.findIndex(o=>o>=e),s=r===-1?1:t.length-r;this.notify(`turn ${s}/${t.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),t=this.scrollbackVisibleRows();if(t<=0)return[];let r=[],s=0,o=null;for(let i=this.lines.length-1;i>=0;i--){let a=this.lines[i];if(!(!a||this.isHiddenLine(a))){if(s+=this.wrapOne(a,e).length,a.bodyStyle==="user"){o={offset:Math.max(0,s-t),lineIndex:i,recordedAt:a.recordedAt};continue}o!==null&&(r.push(o),o=null)}}return o!==null&&r.push(o),r}scrollToTurnAt(e){let t=this.turnAnchors();if(t.length===0)return;let r=t.find(s=>s.recordedAt!==void 0&&s.recordedAt<=e)??t[t.length-1];this.setScrollOffset(r.offset),this.notifyTurnPosition(r.offset)}slideScrollTo(e){this.cancelSlide();let t=Math.min(this.maxScrollOffset(),Math.max(0,e)),r=Math.abs(t-this.scrollOffset);if(r!==0){if(r<=MK||!this.slideEnabled){this.setScrollOffset(t);return}this.slideTarget=t,this.slideTimer=setInterval(()=>{let s=this.slideTarget-this.scrollOffset,o=Math.sign(s)*Math.max(1,Math.round(Math.abs(s)*PK)),i=Math.abs(s)<=Math.abs(o)?this.slideTarget:this.scrollOffset+o;this.scrollOffset=i,this.syncedPartialRepaint(()=>this.drawScrollback()),i===this.slideTarget&&this.cancelSlide()},EK)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=Math.min(this.maxScrollOffset(),Math.max(0,e));t!==this.scrollOffset&&(this.scrollOffset=t,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(),r=[];if(t.length>0)for(let s=this.lines.length-1;s>=0;s--){let o=this.lines[s];if(!o||o.body.length===0||o.ansi)continue;let i=s_(o.body,t);for(let a=i.length-1;a>=0;a--)r.push({lineIdx:s,col:i[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=r,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=t.length>0?t:null,r.length>0&&this.scrollToMatch(r[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 r=this.lineIds.get(t);return r===void 0?null:{lineId:r,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let r=this.wrapOrigin.get(e);if(!r||r.sourceLineId!==t.lineId)return null;let s=r.bodyDisplayShift??0,o=t.col-r.sourceColOffset+s;return o<s||o>=e.body.length?null:o}scrollToMatch(e){let t=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return;let s=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(s+=this.wrapOne(u,t).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,t),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let m=p.body.length;if(e.col<u+m){i=l.length-1-f;break}u+=m}}let a=s+i,d=Math.max(0,a-Math.floor(r/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()-$t-Ht-Bt-yK-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,r,s){return this.started?this.painter.paintRow(e,t,r,s):!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),this.barHits.clear(),pt(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let r=this.promptRows(),s=t-r-Bt-Ht-$t;this.drawBar("composerTop",s),this.drawPrompt(),this.drawBar("composerBottom",t-$t),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=r}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:this.hintsRevealed(),scriptOutputs:this.scriptOutputs}}trackHintHover(e){return e?(this.cancelHintHoverHide(),this.hintHoverReveal?!1:(this.hintHoverReveal=!0,!0)):(!this.hintHoverReveal||this.hintHoverHideTimer!==null||(this.hintHoverHideTimer=setTimeout(()=>{this.hintHoverHideTimer=null,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars())},hK)),!1)}cancelHintHoverHide(){this.hintHoverHideTimer!==null&&(clearTimeout(this.hintHoverHideTimer),this.hintHoverHideTimer=null)}hintsRevealed(){return this.terminalFocused?this.hintHoverReveal||this.hintKeyReveal:!1}revealHints(){this.hintKeyReveal||(this.hintKeyReveal=!0,this.syncedPartialRepaint(()=>this.drawBars()))}clearHintReveal(){this.cancelHintHoverHide(),!(!this.hintKeyReveal&&!this.hintHoverReveal)&&(this.hintKeyReveal=!1,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars()))}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:[],queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:!1,scriptOutputs:this.scriptOutputs}}drawBar(e,t){let r=dv[e],s=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,o=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top;e==="composerBottom"&&(this.composerBottomRow=t);let i=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?VP(i):null,d=a!==null?[a]:ef(e,o.right,i),c=sv(s,ef(e,o.left,i),d,r);e==="composerBottom"&&(this.hintZoneStart=this.hintZoneStartFor(s,o,i,a,c));let l=this.terminalFocused?this.hoveredBarHit:null,u=`${e}|${s}|${l??""}|${c.signature}`;this.paintRow(t,u,()=>{for(let f of c.chunks){let p=f.id!==void 0&&f.id===l?"hint-hover":f.token;B(this.term,p,f.text)}}),this.barHits.set(t,c.hits)}hintZoneStartFor(e,t,r,s,o){if(s!==null)return null;if(r.hintsRevealed)return o.rightStart;let i={...r,hintsRevealed:!0};return sv(e,ef("composerBottom",t.left,i),ef("composerBottom",t.right,i),dv.composerBottom).rightStart}barHitAt(e,t){let r=this.barHits.get(t);return r===void 0?null:r.find(s=>e>=s.start&&e<=s.end)??null}bannerHitAt(e,t){let r=this.barHitAt(e,t);if(r===null)return null;let s=r.id.slice(r.id.indexOf(":")+1);return Jk.some(o=>o.id===s)?s:null}stepFormCursor(e){let t=this.formPrompt;if(t===null||t.rows.length===0)return;let r=Math.max(0,Math.min(t.rows.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onFormClick?.({kind:"row",row:r,select:!0})}isFormCell(e){let t=this.formRegion;return this.formPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}formHitAt(e,t){if(!this.isFormCell(t))return null;for(let s of this.formHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.formRowHits.get(t);if(r===void 0)return null;if(r.field!==void 0&&e>=r.field.startCol){let{slice:s,sliceStart:o,startCol:i}=r.field,a=o,d=i;for(let c of s){let l=d+Pt(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:r.row,caretOffset:a}}return{kind:"row",row:r.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let t=this.formPressHit;if(this.formPressHit=null,t===null||e===null||!this.isFormCell(e.y))return t!==null;let r=this.formHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="row"&&t.kind==="row"&&r.row!==t.row||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action||this.onFormClick?.(r),!0}handleBarPress(e){let t=this.barHitAt(e.x,e.y);if(t===null)return this.barPressHit=null,!1;let r=Date.now(),s=this.lastBarClick;return s!==null&&s.id===t.id&&r-s.t<=nl&&t.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(t.doubleAction,t.value),!0):(this.lastBarClick={id:t.id,t:r},this.barPressHit=t,!0)}handleBarRelease(e){let t=this.barPressHit;if(this.barPressHit=null,t===null||e===null)return!1;let r=this.barHitAt(e.x,e.y);return r===null||r.id!==t.id?!1:(r.action==="none"||this.dispatchBarAction(r.action,r.value),!0)}dispatchBarAction(e,t){if(e!=="none"){if(e==="copy"){Zc(t,{target:this.selectionClipboard}).then(r=>{this.notify(r.ok?`copied ${t}`:`clipboard copy failed: ${r.reason}`)},r=>{this.notify(`clipboard copy failed: ${r.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(t);return}if(e==="open"){this.tryOpenPathString(t)||this.notify(this.hasOpenFileCommand()?`can't open ${t}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,t)}}drawScrollback(){let e=this.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),r=this.sidebarBodyWidth()>0,s=1,o=this.scrollbackVisibleRows();if(o<=0)return;let{rows:i,exhausted:a}=this.wrapTail(e,o+this.scrollOffset);if(a){let g=Math.max(0,i.length-o);this.scrollOffset>g&&(this.scrollOffset=g)}let d=i.length-this.scrollOffset,c=Math.max(0,d-o),l=i.slice(c,d),u=Math.max(0,o-l.length),f=this.currentMatchInfo(),p=f?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let m=-1,h=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let g=0;g<l.length;g++){let w=l[g]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(m===-1&&(m=g),h=g)}for(let g=0;g<o;g++){let w=s+g,b=g-u,k=b>=0?l[b]:void 0,S=this.activeMatchCol(k,f),I=k?this.selectionRangeForChunk(k):null,x=k!==void 0&&k.blockKey!==void 0&&(k.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(k.blockKey)),A=k!==void 0&&k.blockKey===void 0&&m!==-1&&b>=m&&b<=h,_=x||A,P=this.terminalFocused&&_&&(this.hoveredSubKey===null||(k.hoverSubKey??null)===this.hoveredSubKey),$=Hv("sb",e,k,this.scrollbackHighlight,S,I)+(P?"|H":"");this.paintRow(w,$,()=>{k?this.writeFormattedLine(k,e,S,p,I,P,t,k.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&r&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let g=new Set;for(let b of l)b.blockKey!==void 0&&g.add(b.blockKey);let w=[];for(let b of this.pendingVisibleKeys)g.has(b)&&w.push(b);for(let b of w)this.pendingVisibleKeys.delete(b),this.onBlockVisible(b)}}drawSidebar(e,t){let r=this.sidebarBodyWidth();if(r<=0||t<=0){this.sidebarOverflowRows=0;return}let s=this.sidebarColumnStart(),o={metrics:{cellWidth:Pt,truncate:mn},width:r,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:t},i={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(i,o);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarRowLinks.clear();let c=s+af;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?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(u,p.doubleAction),p?.links!==void 0&&p.links.length>0&&this.sidebarRowLinks.set(u,p.links.map(w=>({start:c+w.start,end:c+w.end,url:w.url}))),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,..."page"in w?{gadget:w.page.gadget,index:w.page.index}:{gadget:w.collapse.gadget,collapse:!0}})));let m=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",h=(()=>{let w=[];if(p?.openPath!==void 0&&p.openPath.startsWith("/")&&p.openSpan!==void 0&&w.push({...p.openSpan,url:Vb(p.openPath)}),p?.links!==void 0){let b=this.linkSpansForWindow(p.body,p.links,0,p.body.length,0);b!==null&&w.push(...b)}return w.length>0?w:null})(),g=Hv("sbar",r,p,null,null,null)+`|${m}|${h===null?"":h.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(u,g,()=>{this.term(" ".repeat(Math.max(0,af-1))),m===" "?this.term(" "):eo(this.term,m,"sidebar-rule",!1),p?this.writeFormattedLine(p,r,null,0,null,!1,!0,h):this.term(" ".repeat(r))},{region:"sidebar",column:s})}}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 r=this.sidebarColumnStart();return r===0?!1:e>=r&&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 o of this.sidebarRowActions.get(e.y)??[])if(!(e.x<o.start||e.x>o.end))return o.collapse===!0?this.toggleSidebarGadgetCollapsed(o.gadget):this.sidebarPages={...this.sidebarPages,[o.gadget]:o.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),r=this.lastSidebarClick;if(r!==null&&t-r.t<=nl&&e.y===r.y){this.lastSidebarClick=null;let o=this.sidebarRowDoubleActions.get(e.y);if(o!==void 0)return this.dispatchBarAction(o.action,o.value),!0;let a=this.sidebarRowLinks.get(e.y)?.find(c=>e.x>=c.start&&e.x<c.end);if(a!==void 0)return this.dispatchLinkUrl(a.url),!0;let d=this.sidebarRowPaths.get(e.y);return d!==void 0&&!this.dispatchLinkUrl(d)&&this.notify(this.hasOpenFileCommand()?`can't open ${d}`:"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(Lv,this.queuedTexts.length)}chipRows(){return Math.min(Dv,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,r)=>t===e[r])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Nv,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-$t-Ht-Bt,o=this.queuedRows(),i=this.chipRows(),d=s-1-o-i-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>Nv,m=this.completions.length-Nv+1,h=f?p?`comp|${t}|overflow|${m}`:`comp|${t}|${c}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,h,()=>{if(!f)return;if(p){B(this.term,"modal-hint",` + ${m} more match(es)`);return}let g=f.name.padEnd(c),w=f.description??"",b=t-g.length-4,k=b>0?mn(w,b):"";this.term.noFormat(" "),B(this.term,"completion-name",g),k.length>0&&(this.term.noFormat(" "),B(this.term,"completion-desc",k))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),i=this.term.height-r-$t-Ht-Bt-1-e+1;for(let a=0;a<e;a++){let d=i+a,c=a===e-1&&this.attachments.length>Dv,l=this.attachments.length-Dv,u=this.attachments[a],f=u?`${u.name??"image"} \xB7 ${Mr(u.sizeBytes)}`:"",p=c?`chip|${t}|overflow|${l}`:u?`chip|${t}|${f}`:`chip|${t}|empty`;this.paintRow(d,p,()=>{if(c){B(this.term,"modal-hint",` \u{1F4CE} + ${l+1} more attached`);return}u&&(this.term.noFormat(" "),B(this.term,"attachment",`\u{1F4CE} ${f}`))})}}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-$t-Ht-Bt,o=this.chipRows(),a=s-1-o-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>Lv,p=this.queuedTexts.length-Lv,m=u===void 0?"":f?`+ ${p+1} more queued`:mn(XK(u),t-4),h=!f&&c===d,g=u===void 0?`queued|${t}|empty`:`queued|${t}|${h?"edit":f?"ovf":"row"}|${m}`;this.paintRow(l,g,()=>{if(u===void 0)return;let w=`\u23F3 ${m}`,b=w+" ".repeat(Math.max(0,t-1-w.length));h?B(this.term,"queue-cursor","\u25B8"):B(this.term,"queue-blank"," "),B(this.term,"queue-row",b)})}}promptVisualLayout(){if(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt||this.scrollbackSearch||this.readonly)return null;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=ms(r.buffer,t),o=to(s,r,cg);return{top:this.term.height-o.rendered-Bt-Ht-$t+1,layout:o,visualRows:s}}resolveCellToPromptOffset(e,t){let r=this.promptVisualLayout();if(r===null)return null;let{top:s,layout:o,visualRows:i}=r,a=t-s;if(a<0||a>=o.rendered||e<1||e>this.term.width)return null;let d=i[o.windowStart+a];if(!d)return null;let l=Math.max(0,Math.min(d.endCol-d.startCol,e-1-2));return{row:d.bufferIdx,col:d.startCol+l}}setPromptSelection(e,t){let r=e.row<t.row||e.row===t.row&&e.col<=t.col,s=r?e:t,o=r?t:e;if(s.row===o.row&&s.col===o.col){this.clearPromptSelection();return}let i={startRow:s.row,startCol:s.col,endRow:o.row,endCol:o.col},a=this.promptSelection;a&&a.startRow===i.startRow&&a.startCol===i.startCol&&a.endRow===i.endRow&&a.endCol===i.endCol||(this.promptSelection=i,this.syncedPartialRepaint(()=>this.drawPrompt()))}clearPromptSelection(){this.promptSelection!==null&&(this.promptSelection=null,this.syncedPartialRepaint(()=>this.drawPrompt()))}getPromptSelectionText(){if(this.promptSelection===null)return"";let{startRow:e,startCol:t,endRow:r,endCol:s}=this.promptSelection,o=this.dispatcher.state().buffer;if(e===r)return(o[e]??"").slice(t,s);let i=[(o[e]??"").slice(t)];for(let a=e+1;a<r;a++)i.push(o[a]??"");return i.push((o[r]??"").slice(0,s)),i.join(`
|
|
264
|
-
`)}promptWordBoundsAt(e){let t=this.dispatcher.state().buffer[e.row]??"";if(t.length===0)return null;let r=Math.max(0,Math.min(t.length-1,e.col));if(!Ka.test(t[r]))return null;let s=r;for(;s>0&&Ka.test(t[s-1]);)s--;let o=r+1;for(;o<t.length&&Ka.test(t[o]);)o++;return{start:s,end:o}}selectPromptWholeLine(e){let t=this.dispatcher.state().buffer[e]??"";this.setPromptSelection({row:e,col:0},{row:e,col:t.length})}extendPromptWordSelectionTo(e){let t=this.promptSelectionAnchorWordBounds;if(t===null)return;let r=e.row<t.row||e.row===t.row&&e.col<t.start,s=e.row>t.row||e.row===t.row&&e.col>t.end,o={row:t.row,col:t.start},i={row:t.row,col:t.end};if(r){let a=this.promptWordBoundsAt(e);o=a!==null?{row:e.row,col:a.start}:e}else if(s){let a=this.promptWordBoundsAt(e);i=a!==null?{row:e.row,col:a.end}:e}this.setPromptSelection(o,i)}extendPromptLineSelectionTo(e){let t=this.promptSelectionAnchorLineRow;if(t===null)return;let r=Math.min(t,e.row),s=Math.max(t,e.row),o=this.dispatcher.state().buffer[s]??"";this.setPromptSelection({row:r,col:0},{row:s,col:o.length})}handlePromptSelectionPress(e){if(!this.inAppSelectionEnabled)return!1;let t=this.resolveCellToPromptOffset(e.x,e.y);if(t===null)return!1;this.promptSelectionAnchor=t,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,this.promptPendingClickCount=1,this.promptSelectionGranularity="char",this.promptSelectionAnchorWordBounds=null,this.promptSelectionAnchorLineRow=null,this.clearPromptSelection();let r=Date.now(),s=this.promptLastLeftClick,o=s!==null&&r-s.t<=nl&&Math.abs(e.x-s.x)<=rl&&Math.abs(e.y-s.y)<=rl&&s.row!==null&&s.row===t.row;if(o&&s.count===2&&e.x===s.x&&e.y===s.y)return this.promptPendingClickCount=3,this.selectPromptWholeLine(t.row),this.promptSelectionGranularity="line",this.promptSelectionAnchorLineRow=t.row,this.promptDoubleClickPending=!0,!0;if(o&&s.count===1){this.promptPendingClickCount=2;let d=this.promptWordBoundsAt(t);d!==null&&(this.setPromptSelection({row:t.row,col:d.start},{row:t.row,col:d.end}),this.promptDoubleClickPending=!0,this.promptSelectionGranularity="word",this.promptSelectionAnchorWordBounds={row:t.row,start:d.start,end:d.end})}return!0}handlePromptSelectionDrag(e){if(this.promptSelectionAnchor===null)return;let t=this.promptVisualLayout();if(t===null)return;let r=Math.max(1,Math.min(this.term.width,e.x)),s=Math.max(t.top,Math.min(t.top+t.layout.rendered-1,e.y)),o=this.resolveCellToPromptOffset(r,s);o!==null&&(this.promptSelectionDragStarted=!0,this.promptSelectionGranularity==="word"?this.extendPromptWordSelectionTo(o):this.promptSelectionGranularity==="line"?this.extendPromptLineSelectionTo(o):this.setPromptSelection(this.promptSelectionAnchor,o))}handlePromptSelectionRelease(e){let t=this.promptSelectionDragStarted,r=this.promptDoubleClickPending;if(this.promptSelectionAnchor=null,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,e!==null){let s=this.resolveCellToPromptOffset(e.x,e.y);this.promptLastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.promptPendingClickCount,row:s?.row??null}}if(this.promptPendingClickCount=1,t||r){this.finalizePromptSelection();return}this.clearPromptSelection()}finalizePromptSelection(){let e=this.getPromptSelectionText();e.length!==0&&Zc(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}drawPrompt(){if((this.permissionPrompt||this.formPrompt||this.confirmPrompt)&&(this.compactionRegion=null),(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt)&&(this.helpRegion=null),this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();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),r=this.dispatcher.state(),s=ms(r.buffer,t),o=to(s,r,cg),i=this.term.height-o.rendered-Bt-Ht-$t+1,a=!1;for(let d=0;d<o.rendered;d++){let c=s[o.windowStart+d],l=i+d,u="wrap",f="";c&&(c.bufferIdx===0&&c.startCol===0?u="first":c.startCol===0&&(u="newline"),f=(r.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=-1,m=-1;if(c&&this.promptSelection!==null){let g=this.promptSelection;if(c.bufferIdx>=g.startRow&&c.bufferIdx<=g.endRow){let w=c.bufferIdx===g.startRow?g.startCol:c.startCol,b=c.bufferIdx===g.endRow?g.endCol:c.endCol,k=Math.max(w,c.startCol),S=Math.min(b,c.endCol);S>k&&(p=k-c.startCol,m=S-c.startCol)}}let h=c?`prompt|${this.term.width}|${u}|${f}|${p}:${m}`:`prompt|${this.term.width}|empty`;this.paintRow(l,h,()=>{c&&(u==="first"?a?B(this.term,"composer-inactive","> "):B(this.term,"composer-gutter","> "):u==="newline"?B(this.term,"composer-continuation","\xB7 "):this.term(" "),a?B(this.term,"composer-inactive",f):p>=0&&m>p?(p>0&&B(this.term,"content",f.slice(0,p)),B(this.term,"selection-highlight",f.slice(p,m)),m<f.length&&B(this.term,"content",f.slice(m))):B(this.term,"content",f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,r=this.term.height-Bv-Bt-Ht-$t+1;this.paintRow(r,`confirm|q|${t}|${e.question}`,()=>{B(this.term,"prompt-text",` ? ${mn(e.question,t-4)}`)}),this.paintRow(r+1,`confirm|h|${t}|${e.hint}`,()=>{B(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,r=this.compactionRows(),s=this.term.height-r-Bt-Ht-$t+1,o=s;this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion={top:s,bottom:s+r-1};let i=(c,l)=>{o>=s+r||(this.paintRow(o,c,l),o+=1)};i(`cpct|msg|${t}|${e.message}`,()=>{B(this.term,"prompt-text",` ${mn(e.message,t-2)}`)}),i(`cpct|q|${t}`,()=>{B(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let c=0;c<e.options.length&&!(o>=s+r-1);c++){let l=e.options[c];if(!l)continue;let u=c===e.selectedIndex,p=` ${u?"\u276F":" "} ${c+1}. ${mn(l.label,t-8)}`;this.compactionRowHits.set(o,c),i(`cpct|o|${t}|${c}|${u?"1":"0"}|${l.label}`,()=>{u?B(this.term,"modal-option-selected",p):B(this.term,"modal-option",p)})}let a=jv(IK,t),d=o;for(let c of a.spans)(c.action==="commit"||c.action==="cancel")&&this.compactionHintHits.push({row:d,start:c.start,end:c.end,action:c.action});i(`cpct|hint|${t}|${a.text}`,()=>{B(this.term,"modal-hint",` ${a.text}`)})}isCompactionCell(e){let t=this.compactionRegion;return this.compactionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}compactionHitAt(e,t){if(!this.isCompactionCell(t))return null;for(let s of this.compactionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.compactionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}stepCompactionCursor(e){let t=this.compactionPrompt;if(t===null||t.options.length===0)return;let r=Math.max(0,Math.min(t.options.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onCompactionClick?.({kind:"option",index:r,select:!0})}handleCompactionPress(e){return this.isCompactionCell(e.y)?(this.compactionPressHit=this.compactionHitAt(e.x,e.y),!0):(this.compactionPressHit=null,!1)}handleCompactionRelease(e){let t=this.compactionPressHit;if(this.compactionPressHit=null,t===null||e===null||!this.isCompactionCell(e.y))return t!==null;let r=this.compactionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.compactionArmedAt<XM?(this.notify("compaction prompt just appeared, click again to confirm"),!0):(this.onCompactionClick?.(r),!0)}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let t=this.term.width,r=this.helpRows(),s=this.term.height-r-Bt-Ht-$t+1,o=s;this.helpRegion={top:s,bottom:s+r-1};let i=(d,c)=>{o>=s+r||(this.paintRow(o,d,c),o+=1)};i(`help|t|${t}|${e.title}`,()=>{B(this.term,"prompt-text",` \u2753 ${mn(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(o>=s+r-1)break;if(d===null){i(`help|sep|${t}|${o}`,()=>{});continue}let[c,l]=d,u=c.padEnd(a);i(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),B(this.term,"modal-key",u),B(this.term,"content",` ${mn(l,t-2-a-1)}`)})}i(`help|hint|${t}|${e.hint}`,()=>{B(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(RK,2+this.helpPrompt.entries.length):0}isHelpCell(e){let t=this.helpRegion;return this.helpPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}handleHelpPress(e){return this.isHelpCell(e.y)?(this.helpPressed=!0,!0):(this.helpPressed=!1,!1)}handleHelpRelease(e){let t=this.helpPressed;return this.helpPressed=!1,t?(e!==null&&this.isHelpCell(e.y)&&this.onHelpClick?.(),!0):!1}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,r=this.permissionRows(),s=this.term.height-r-Bt-Ht-$t+1,o=s;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:s,bottom:s+r-1};let i=(l,u)=>{o>=s+r||(this.paintRow(o,l,u),o+=1)};i(`perm|t|${t}|${e.title}`,()=>{B(this.term,"prompt-text",` \u{1F512} ${mn(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${t}|${a}`,()=>{B(this.term,"modal-hint",` ${mn(a,t-2)}`)}),i(`perm|q|${t}`,()=>{B(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(o>=s+r-1);l++){let u=e.options[l];if(!u)continue;let f=l===e.selectedIndex,m=` ${f?"\u276F":" "} ${l+1}. ${mn(u.label,t-8)}`;this.permissionRowHits.set(o,l),i(`perm|o|${t}|${l}|${f?"1":"0"}|${u.label}`,()=>{f?B(this.term,"modal-option-selected",m):B(this.term,"modal-option",m)})}let d=jv(xK,t),c=o;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});i(`perm|hint|${t}|${d.text}`,()=>{B(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let t=this.permissionRegion;return this.permissionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}permissionHitAt(e,t){if(!this.isPermissionCell(t))return null;for(let s of this.permissionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.permissionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let t=this.permissionPressHit;if(this.permissionPressHit=null,t===null||e===null||!this.isPermissionCell(e.y))return t!==null;let r=this.permissionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.permissionArmedAt<XM?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(r),!0)}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 ":""}drawBanner(){let e=this.term.height,t=this.promptRows(),r=e-t-Bt-Ht-$t;this.drawBar("composerTop",r),this.drawBar("composerBottom",e-$t)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Bt-Ht-$t+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Bt-Ht-$t;this.term.moveTo(2,Math.min(f,p));return}if(this.formPrompt){let l=this.formPrompt,u=this.formWindowSize(),f=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-f),m=this.term.height-Bt-Ht-$t,h=Math.min(p,m),w=t_(l,this.term.width,f,u).find(b=>b.selected);if(w?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(w.caretCol,this.term.width),h);return}if(this.confirmPrompt){let l=this.term.height-Bv-Bt-Ht-$t+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Bt-Ht-$t+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Bt-Ht-$t;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Bt-Ht-$t+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),r=this.dispatcher.state(),s=ms(r.buffer,t),o=to(s,r,cg),a=this.term.height-o.rendered-Bt-Ht-$t+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Bt-Ht-$t;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return Bv;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),r=this.dispatcher.state(),s=ms(r.buffer,t);return Math.min(cg,Math.max(1,s.length))}permissionRows(){return this.permissionPrompt?Math.min(vK,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(CK,this.formPrompt.maxRows??SK),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Bt-Ht-$t+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let t=this.term.width,r=this.formRows(),s=this.formTop(),o=this.formWindowSize(),i=`${e.title}|${e.rows.length}|${o}`;i!==this.formWindowKey?(this.formWindowKey=i,this.formWindowTop=GK(e.rows.length,e.selectedIndex,o)):this.formWindowTop=JK(this.formWindowTop,e.rows.length,e.selectedIndex,o);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:s,bottom:s+r-1};let d=s,c=(h,g)=>{d>=s+r||(this.paintRow(d,h,g),d+=1)},l=e.rows.length>o?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${t}|${e.title}|${l}`,()=>{B(this.term,"prompt-text",` \u2699 ${mn(`${e.title}${l}`,t-5)}`)});let u=t_(e,t,a,o);for(let h of u){if(d>=s+r-1)break;this.formRowHits.set(d,{row:h.index,...h.kind==="text"?{field:{startCol:1+Pt(h.prefix),slice:h.field,sliceStart:h.fieldStart}}:{}}),c(h.sig,()=>{if(h.kind==="text"){B(this.term,h.selected?"modal-option-selected":"modal-option",h.prefix),B(this.term,"content",h.field);return}B(this.term,h.selected?"modal-option-selected":"modal-option",h.body)})}let f=e.hints??VK,p=d,m=jv(f,t);for(let h of m.spans)this.formHintHits.push({row:p,...h});c(`form|hint|${t}|${m.text}`,()=>{B(this.term,"modal-hint",` ${m.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,r=this.wrapBtwWindow(t,e,0).rows.length;return Math.min(this.btwOverlayMaxHeight,1+r)}wrapBtwWindow(e,t,r){let s=this.btwOverlayLines.length;if(t<=0||s===0)return{rows:[],offset:0,more:!1};if(e<=4){let f=Math.min(Math.max(0,r),Math.max(0,s-t)),p=s-f,m=Math.max(0,p-t);return{rows:this.btwOverlayLines.slice(m,p),offset:f,more:m>0}}let o=Math.max(0,r),i=[],a=0;for(let f=s-1;f>=0;f--){let p=this.btwOverlayLines[f],m=this.wrapOne(p,e);if(i.push(m),a+=m.length,a>t+o)break}let d=[];for(let f=i.length-1;f>=0;f--)d.push(...i[f]);let c=Math.min(o,Math.max(0,d.length-t)),l=d.length-c,u=Math.max(0,l-t);return{rows:d.slice(u,l),offset:c,more:u>0}}scrollBtwOverlayBy(e){let t=this.btwOverlayRegion;if(!this.btwOverlayOpen||t===null||t.contentRows<=0)return!1;let r=Math.max(0,this.btwOverlayScroll+e),s=this.wrapBtwWindow(this.term.width,t.contentRows,r);return!s.more&&s.offset===0?!1:(s.offset===this.btwOverlayScroll||(this.btwOverlayScroll=s.offset,this.repaintNow()),!0)}isBtwOverlayCell(e){let t=this.btwOverlayRegion;return t!==null&&e>=t.top&&e<=t.bottom}btwOverlayScrollState(){let t=this.btwOverlayRegion?.contentRows??0;return{offset:this.btwOverlayScroll,more:this.wrapBtwWindow(this.term.width,t,this.btwOverlayScroll).more}}drawBtwOverlay(){if(!this.btwOverlayOpen){this.btwOverlayRegion=null;return}let e=this.btwOverlayRows();if(e===0){this.btwOverlayRegion=null;return}let t=this.term.width,s=this.term.height-this.promptRows()-Bt-Ht-$t,o=this.chipRows()+this.queuedRows()+this.completionRows(),i=s-1-o,a=i-e+1,d=e-1,c=a;this.btwOverlayRegion={top:c,bottom:i,contentRows:d},this.drawBar("btw",c);let l=this.wrapBtwWindow(t,d,this.btwOverlayScroll);this.btwOverlayScroll=l.offset;let u=l.rows;for(let f=0;f<d;f++){let p=c+1+f,m=u.length-d+f,h=m>=0?u[m]:void 0,g=Hv(`btw|c${f}`,t,h);this.paintRow(p,g,()=>{h?this.writeFormattedLine(h,t):this.term.noFormat(" ".repeat(t))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,t){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(t,d.length);return{rows:d.slice(d.length-c),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],s=0,o=0,i=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(i=!0);continue}let l=this.wrapOne(c,e);if(r.push(l),s+=l.length,o=d,s>=t)break}let a=[];for(let d=r.length-1;d>=0;d--)a.push(...r[d]);return{rows:a,exhausted:o===0||i}}wrapOne(e,t){let r=this.lineIds.get(e);if(r!==void 0){let g=this.wrapCache.get(r);if(g)return g}let s=e.prefix??"",o=Pt(s),i=Math.max(1,t-o-1),a=Math.max(0,Math.min(e.hangingIndent??0,i-1)),d=Math.max(1,i-a),c=df(e.bodyStyle),l=e.ansi?DK(e.body,a>0?d:i):jK(e.body,a>0?d:i,{escapeAware:c}),u=e.ansi?0:e.maxWrapRows??0,f=u>0&&l.length>u;f&&(l.length=u);let p=[],m=0,h=0;for(let g=0;g<l.length;g++){let w=l[g]??"",b=g===0||a===0?w:" ".repeat(a)+w;f&&g===l.length-1&&(b=mn(`${b}\u2026`,i,{escapeAware:c}));let k={prefix:g===0?e.prefix:" ".repeat(o),body:b};if(e.prefixStyle!==void 0&&(k.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(k.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(k.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(k.hoverSubKey=e.hoverSubKey),e.fillRow&&(k.fillRow=!0),e.ansi&&(k.ansi=!0),r!==void 0&&w.length>0)if(e.ansi){let S=m,I=0;for(let P=0;P<w.length;){let $=$r(w,P);if($){P+=$.text.length,$.width>0&&(I+=1);continue}I+=1,P+=1}let x=I;for(;x>0&&m<e.body.length;){let P=$r(e.body,m);if(P){m+=P.text.length,P.width>0&&(x-=1);continue}m+=1,x-=1}let A=m;if(g===l.length-1){for(;A<e.body.length;){let P=$r(e.body,A);if(!P)break;A+=P.text.length}m=A}let _={sourceLineId:r,sourceColOffset:S,sourceColEnd:A};if(g>0&&a>0&&(_.bodyDisplayShift=a),this.wrapOrigin.set(k,_),e.links!==void 0){let P=this.linkSpansForWindow(e.body,e.links,S,A,g===0||a===0?0:a);P!==null&&(k.linkSpans=P)}}else{let S=e.body.indexOf(w,h),I=S===-1?h:S,x={sourceLineId:r,sourceColOffset:I};if(g>0&&a>0&&(x.bodyDisplayShift=a),this.wrapOrigin.set(k,x),e.links!==void 0){let A=this.linkSpansForWindow(e.body,e.links,I,I+w.length,g===0||a===0?0:a);A!==null&&(k.linkSpans=A)}h=I+w.length}p.push(k)}return r!==void 0&&this.wrapCache.set(r,p),p}writeFormattedLine(e,t,r=null,s=0,o=null,i=!1,a=!1,d=null){e.prefix&&eo(this.term,e.prefix,e.prefixStyle??e.bodyStyle,i);let c=Math.max(0,t-Pt(e.prefix??"")),l=df(e.bodyStyle),u=e.ansi?e.body:mn(e.body,c,{escapeAware:l}),f=d===null||d.length===0?null:d.map(h=>({start:Math.max(0,Math.min(u.length,h.start)),end:Math.max(0,Math.min(u.length,h.end)),url:h.url})).filter(h=>h.end>h.start).sort((h,g)=>h.start-g.start),p=(h,g,w)=>{if(f===null){w(h,g);return}let b=g+h.length,k=g;for(let S of f){if(S.end<=k||S.start>=b)continue;let I=Math.max(S.start,k),x=Math.min(S.end,b);I>k&&w(h.slice(k-g,I-g),k),process.stdout.write(`\x1B]8;;${S.url}\x1B\\`),w(h.slice(I-g,x-g),I),process.stdout.write("\x1B]8;;\x1B\\"),k=x}k<b&&w(h.slice(k-g),k)},m=(h,g)=>{h.length!==0&&p(h,g,(w,b)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let k=r!==null&&r>=b?r-b:null;NK(this.term,w,e.bodyStyle,this.scrollbackHighlight,k,s,i)}else eo(this.term,w,e.bodyStyle,i)})};if(o!==null){let h=Math.max(0,Math.min(u.length,o.start)),g=Math.max(h,Math.min(u.length,o.end)),w=df(e.bodyStyle)||e.ansi===!0;if(m(u.slice(0,h),0),g>h){let k=u.slice(h,g);w&&(k=ug(k)),w?eo(this.term,k,"selection-highlight",i):p(k,h,S=>{eo(this.term,S,"selection-highlight",i)})}let b=u.slice(g);if(w&&g>h){let k=WK(u.slice(0,g));k.length>0&&(b=k+b)}m(b,g)}else m(u,0);if(e.fillRow||i||a){let h=e.ansi?r_(u):Pt(l?ug(u):u),g=c-h;if(g>0){let w=o!==null&&o.toEndOfLine?"selection-highlight":e.fillRow||i?e.bodyStyle:void 0;eo(this.term," ".repeat(g),w,i)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset()}};o_=/[^\x20-\x7e]/,zv=new Intl.Segmenter(void 0,{granularity:"grapheme"}),i_=!1;VK=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]});function ZK(n,e,t=$o){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let r=t[n];return r?{kind:"resolve",action:r.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 r=e.ch.toLowerCase();if(r==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(r==="p")return{kind:"continue",selected:Math.max(0,n-1)};let s=t.findIndex(o=>o.hotkey.toLowerCase()===r);if(s>=0){let o=t[s];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:n}}async function u_(n,e){ls();let t=st(e.sessionId),r=e.importedFromMachine??"another machine",s=V(e.cwd),o=$o.findIndex(p=>p.key==="view");o<0&&(o=0);let i=null,a=null,d=()=>{let m=7+$o.length*2+2,h=pr(n,{contentHeight:m,title:"Imported session"}),g=h.contentW,w=[{label:"session: ",value:t},{label:"from: ",value:r},{label:"cwd: ",value:s}],b=0;for(let S of w)n.moveTo(h.contentX,h.contentY+b),B(n,"modal-label",` ${S.label}`),B(n,"content",_t(S.value,g-S.label.length-2)),b++;b++;let k=f_(n,h,b,{intro:"What do you want to do?",choices:$o,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"});return i=h,a=k.firstChoiceRow,h},c=()=>{let p=i,m=a;if(!(p===null||m===null))for(let h=0;h<$o.length;h++){let g=$o[h];g&&Jv(n,p,m+h*2,g.label,h===o)}},l=p=>{p<0||p>=$o.length||p===o||(o=p,c())},u=null,f=p_({choiceCount:$o.length,layout:()=>i,firstChoiceRow:()=>a,selected:()=>o,select:l,commit:p=>{let m=$o[p];m&&u?.(m.key)},back:()=>u?.("back")});return Ys({term:n,render:d,onKey:(p,m,h,g)=>{let w=eG(p,h);if(!w)return;let b=ZK(o,w);if(b.kind==="cancel"){g("cancel");return}if(b.kind==="back"){g("back");return}if(b.kind==="resolve"){g(b.action);return}l(b.selected)},onMouse:(p,m,h)=>{u=h,f(p,m)}})}function f_(n,e,t,r){let s=t;n.moveTo(e.contentX,e.contentY+s),B(n,"content",` ${r.intro}`),s+=2;let o=e.contentY+s;for(let i=0;i<r.choices.length;i++){let a=r.choices[i];a&&(Jv(n,e,e.contentY+s,a.label,i===r.selected),s++,n.moveTo(e.contentX,e.contentY+s),B(n,"list-description",` ${a.description}`),s++)}return s++,n.moveTo(e.contentX,e.contentY+s),B(n,"modal-hint",` ${r.footer}`),{firstChoiceRow:o}}function p_(n){let e=null,t=r=>{let s=n.firstChoiceRow();if(s===null)return null;let o=r-s;if(o<0)return null;let i=Math.floor(o/2);return i<n.choiceCount?i:null};return(r,s)=>{if(r==="MOUSE_WHEEL_UP"){n.select(n.selected()-1);return}if(r==="MOUSE_WHEEL_DOWN"){n.select(n.selected()+1);return}if(r==="MOUSE_LEFT_BUTTON_PRESSED"){e={x:s?.x??-1,y:s?.y??-1};return}let o=s?.y;if(typeof o!="number")return;if(r==="MOUSE_MOTION"){let l=t(o);l!==null&&n.select(l);return}if(r!=="MOUSE_LEFT_BUTTON_RELEASED")return;let i=s?.x,a=e!==null&&i===e.x&&o===e.y;if(e=null,!a)return;let d=n.layout();if(d!==null&&typeof i=="number"&&(i<d.x||i>=d.x+d.w||o<d.y||o>=d.y+d.h)){n.back();return}let c=t(o);c!==null&&n.commit(c)}}function Jv(n,e,t,r,s){let i=La(` ${s?"\u276F":" "} ${r}`,e.contentW);n.moveTo(e.contentX,t),B(n,s?"list-selected":"content",i)}function eG(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 h_(n,e,t){let r=st(e.sessionId),s=e.title??V(e.cwd),o=1,i=[{key:"launch",label:"Launch",hotkey:"l",description:"start a new agent session"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=null,d=null,c=()=>{let f=pr(n,{contentHeight:11,title:"Open session",overlay:!0}),p=f.contentW,m=0;n.moveTo(f.contentX,f.contentY+m),B(n,"modal-label"," session: "),B(n,"content",_t(r,p-10)),m++,n.moveTo(f.contentX,f.contentY+m),B(n,"content"," "+_t(s,p-2)),m++,m++;let h=f_(n,f,m,{intro:"What do you want to do?",choices:i,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"});a=f,d=h.firstChoiceRow},l=()=>{let f=a,p=d;if(!(f===null||p===null))for(let m=0;m<i.length;m++){let h=i[m];h&&Jv(n,f,p+m*2,h.label,m===o)}},u=f=>{f<0||f>=i.length||f===o||(o=f,l())};return c(),n.hideCursor(),await new Promise(f=>{let p=!1,m=()=>{p=!0},h=b=>{m(),t.pop(),f(b)},g=(b,k,S)=>{if(b==="CTRL_C"||b==="CTRL_D"){h("cancel");return}if(b==="ESCAPE"){h("back");return}if(b==="ENTER"||b==="KP_ENTER"){h(i[o]?.key??"view");return}if(b==="UP"||b==="SHIFT_TAB"){u(o-1);return}if(b==="DOWN"||b==="TAB"){u(o+1);return}if(S?.isCharacter){let I=b.toLowerCase();if(I==="l"){h("launch");return}if(I==="v"){h("view");return}if(I==="n"){u(o+1);return}if(I==="p"){u(o-1);return}}},w=p_({choiceCount:i.length,layout:()=>a,firstChoiceRow:()=>d,selected:()=>o,select:u,commit:b=>{let k=i[b];k&&h(k.key)},back:()=>h("back")});t.push({onKey:(b,k,S)=>{p||g(b,k,S)},onMouse:(b,k)=>{p||w(b,k)},onResize:()=>{p||c()}})})}var $o,Vv=q(()=>{"use strict";ke();ir();Na();Tn();$o=[{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 lf(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let r=n[t]??"",s=0;for(;s<e.length&&s<r.length&&e[s]===r[s];)s+=1;if(e=e.slice(0,s),e.length===0)break}return e}function m_(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let r=t.indexOf(" "),s=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r);if(e.length===1){let a=e[0]??"",d=o.startsWith(" ")?"":" ";return a+d+o}let i=lf(e);return i.length<=s.length?null:i+o}var hg=q(()=>{"use strict"});import*as g_ from"os";async function Ja(n,e,t={}){let r=t.defaultCwd??(e?await wP(e.cwd):void 0)??g_.homedir();ls();let s=t.title??"Fork locally \u2014 choose cwd",o=t.intro??"Pick a local cwd for this session:",i=e?[{label:"session: ",value:st(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:V(e.cwd)}]:[],a=new vi(r.endsWith("/")?r:r+"/"),d=()=>{let $=gP(a.text);$>0&&a.setText(a.text.slice($))},c=null,l=!1,u=null,f=null,p=null,m=null,h=" Enter accept \xB7 Esc back",g="Enter accept",w="Esc back",b=h.indexOf(g),k=h.indexOf(w),S=()=>{let $=i.length+6;u=pr(n,{contentHeight:$,title:s,overlay:t.overlay===!0});let F=u.contentW,J=0;for(let W of i)n.moveTo(u.contentX,u.contentY+J),B(n,"modal-label",` ${W.label}`),B(n,"content",_t(W.value,F-W.label.length-2)),J++;J++,n.moveTo(u.contentX,u.contentY+J),B(n,"content",` ${o}`),J+=2,A(J),J+=2;let Y=u.contentY+J;c!==null?(n.moveTo(u.contentX,Y),B(n,"input-error",` ${_t(c,F-2)}`),f=null,p=null,m=null):(n.moveTo(u.contentX,Y),B(n,"modal-hint",h),f=Y,p={start:u.contentX+b,end:u.contentX+b+g.length-1},m={start:u.contentX+k,end:u.contentX+k+w.length-1})},I=()=>i.length+3,x=0,A=$=>{if(!u)return;let F=$??I();n.moveTo(u.contentX,u.contentY+F).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+F),B(n,"box-border","\u2502"),n.moveTo(u.contentX,u.contentY+F),n.noFormat(" ");let Y=Math.max(1,u.contentW-1-2),W=a.text,Z=a.cursor;Z<x&&(x=Z),Z-x>=Y&&(x=Z-Y+1),x<0&&(x=0);let ne=W.slice(x,x+Y);x>0&&ne.length>0&&(ne="\u2026"+ne.slice(1));let ve=Wk(W),Ne=(Ge,Ae)=>{if(Ae.length===0)return;let de=Ge+Ae.length;if(ve<=Ge)B(n,"content",Ae);else if(ve>=de)B(n,"modal-hint",Ae);else{let De=ve-Ge;B(n,"modal-hint",Ae.slice(0,De)),B(n,"content",Ae.slice(De))}},Re=Z-x;if(l){Ne(x,ne);return}Re>=ne.length?(Ne(x,ne),B(n,"input-cursor"," ")):(Ne(x,ne.slice(0,Re)),B(n,"input-cursor",ne[Re]??" "),Ne(x+Re+1,ne.slice(Re+1)))},_=()=>{if(A(),!u)return;let $=I()+2;n.moveTo(u.contentX,u.contentY+$).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+$),B(n,"box-border","\u2502");let F=u.contentY+$;n.moveTo(u.contentX,F),c!==null?(B(n,"input-error",` ${_t(c,u.contentW-2)}`),f=null,p=null,m=null):(B(n,"modal-hint",h),f=F,p={start:u.contentX+b,end:u.contentX+b+g.length-1},m={start:u.contentX+k,end:u.contentX+k+w.length-1})},P=$=>{if(l)return;let F=a.text;l=!0,c=null,_(),Ju(F).then(J=>{if(l=!1,J.ok){$({kind:"ok",path:J.path});return}c=J.reason,_()})};return Ys({term:n,render:S,overlay:t.overlay===!0,onKey:($,F,J,Y)=>{if(!l){if($==="ENTER"||$==="KP_ENTER"){P(Y);return}if($==="ESCAPE"){Y({kind:"back"});return}if($==="CTRL_C"||$==="CTRL_D"){Y({kind:"cancel"});return}if($==="TAB"){l=!0,bP(a.text).then(W=>{if(l=!1,W.matches.length===0)return;let Z;if(W.matches.length===1)Z=W.prefix+W.matches[0];else{let ne=lf(W.matches);if(ne.length<=W.basePrefix.length)return;Z=W.prefix+ne}Z!==a.text&&(a.setText(Z,{recordUndo:!0}),d(),c=null,_())});return}if(a.handleKey($,J?.isCharacter===!0)){d(),c=null,_();return}}},onMouse:($,F,J)=>{if(l||$!=="MOUSE_LEFT_BUTTON_PRESSED")return;let Y=F?.x,W=F?.y;if(!(typeof Y!="number"||typeof W!="number")){if(u!==null&&(Y<u.x||Y>=u.x+u.w||W<u.y||W>=u.y+u.h)){J({kind:"back"});return}if(f!==null&&W===f){if(p!==null&&Y>=p.start&&Y<=p.end){P(J);return}if(m!==null&&Y>=m.start&&Y<=m.end){J({kind:"back"});return}}}}})}var Yv=q(()=>{"use strict";ke();ir();jk();hg();Na();Dm();Tn()});import*as w_ from"fs";import*as b_ from"os";import*as mg from"path";function gg(n,e){let t=e;for(;t>0;){let r=n[t-1]??"";if(/\s/.test(r)){if(r===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function tG(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function nG(n){return n.replace(/\\ /g," ")}function y_(n){return n.replace(/ /g,"\\ ")}function rG(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function sG(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=b_.homedir()+t.slice(1)),mg.isAbsolute(t)?t:mg.resolve(e,t)}function oG(n){let e;try{e=w_.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function yg(n,e,t=oG){let r=nG(n),{dirPrefix:s,base:o}=rG(r);if(s.length===0&&!tG(n)&&o.length===0)return null;let i=sG(s,e),a=t(i);if(a===null)return null;let d=o.startsWith("."),c=a.filter(f=>f.name.startsWith(o)&&(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:y_(s+p),candidates:l}}let u=lf(c.map(f=>f.name));return{replacement:y_(s+u),candidates:l}}var Qv=q(()=>{"use strict";hg()});import{spawn as iG}from"child_process";function aG(n,e){let t="";for(let r=0;r<n.length;r++){let s=n[r];if(s!=="%"||r===n.length-1){t+=s;continue}switch(n[r+1]){case"%":t+="%",r++;break;case"s":t+=e.sessionId,r++;break;case"c":t+=e.cwd,r++;break;case"a":t+=e.agentId,r++;break;case"u":t+=e.baseUrl,r++;break;case"t":t+=e.tokenFile,r++;break;default:t+=s;break}}return t}function dG(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function cG(n,e){let t=dG(n.command);if(t.length===0)return null;let r=t.map(a=>mt(aG(a,e))),[s,...o]=r;if(!s)return null;let i={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:s,args:o,env:i}}function lG(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(r,s)=>{if(e.truncated)return;let o=n-e.bytes;if(o<=0){e.truncated=!0;return}let i=r.length<=o?r.toString("utf8"):r.subarray(0,o).toString("utf8");r.length>o&&(e.truncated=!0),e[s]+=i,e.bytes+=Math.min(r.length,o)};return{onStdout:r=>t(r,"stdout"),onStderr:r=>t(r,"stderr"),onExit:(r,s)=>{let o=[],i=(a,d)=>{let c=a.split(/\r?\n/);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(let l of c)o.push({text:l,style:d})};return e.stdout&&i(e.stdout,"stdout"),e.stderr&&i(e.stderr,"stderr"),e.truncated&&o.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),s?o.push({text:`[killed by ${s}]`,style:"error"}):typeof r=="number"&&r!==0&&o.push({text:`[exit ${r}]`,style:"error"}),o}}}function wg(n,e,t){let r=cG(n,e);if(r===null){t.notify("hotkey: empty command");return}let s=lG(t.maxOutputBytes??uG),o=t.spawnFn??iG,i;try{i=o(r.program,r.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...r.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}i.stdout?.on("data",s.onStdout),i.stderr?.on("data",s.onStderr),i.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),i.on("close",(a,d)=>{t.emitLines(s.onExit(a,d))})}var uG,Xv=q(()=>{"use strict";rt();uG=16*1024});function fG(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function pG(n,e,t){let r=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${r} via npm\u2026`:t.phase==="installed"?`${n} ${r} installed`:`${n} installing ${r} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let s=t.receivedBytes??0,o=t.totalBytes??0,i=(s/1e6).toFixed(1);if(o>0){let a=(o/1e6).toFixed(1),d=Math.min(100,Math.floor(s/o*100));return`${n} downloading ${r} ${i}/${a} MB (${d}%)`}return`${n} downloading ${r} ${i} MB`}return t.phase==="download_done"?`${n} downloaded ${r}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${r}\u2026`:t.phase==="installed"?`${n} ${r} installed`:e||n}function bg(n,e){let t=!1,r="",s=!1,o=n,i=a=>{t||a===3&&s||a===0&&!s||(s=a===3,fG(a))};return{write(a){t||(o=a,r=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"?i(3):a.phase==="installed"&&i(0);let c=pG(o,r,a);r=c,e.write(c)},finalize(){t||(t=!0,i(0),e.finalize())}}}function k_(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),B(n,"status-active",t))},finalize(){e||(e=!0,process.stdout.write(`
|
|
265
|
-
`))}}}var Zv=q(()=>{"use strict";Tn()});function tS(n="local"){let e={filters:{cwdOnly:!1,hostFilter:n==="all"?"__all":"__local",includeNonInteractive:!1}};return n!=="local"&&n!=="all"&&(e.pendingDefaultHost=n),e}function Va(){return on()?.id??"terminal"}function gG(){if(!qu())return S_;let n=[];for(let e of S_)n.push(e),e?.[0]==="*"&&n.push(["^t",Lm()?"go to selected session's tab (opening one if needed), or send the composer to a new one":"new tab: selected session, or send the composer to a new one"]);return n}async function nS(n,e){let t=()=>{we(ns),we(_a),we(Po),we($a),we(Oa),we(jc),we(qc),we(zc),we(Ma),we("\x1B>")};t();let r=e.prefs??tS();if(e.prefs===void 0&&e.currentSessionId!==void 0){let E=e.sessions.find(M=>M.sessionId===e.currentSessionId);(E?.importedFromMachine||E?.remote)&&(r.filters.hostFilter="__all")}if(r.pendingDefaultHost!==void 0){let E=kG(r.pendingDefaultHost,e.sessions);r.filters.hostFilter=E,E!=="__local"&&(r.pendingDefaultHost=void 0)}let s=e.cwd,o=vg(e.sessions,s),i,a=E=>{let M=E;return r.filters.cwdOnly&&(M=M.filter(U=>U.cwd===s)),r.filters.includeNonInteractive||(M=M.filter(U=>U.interactive===!0)),M=bG(M,r.filters.hostFilter),M},d=a(o),c={columns:e.config.tui.sessionColumns??mi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},l=d.map(E=>ds(E,Date.now())),u=
|
|
266
|
-
`)},ad=()=>{let E=id();E.length!==0&&Zc(E,{target:Ti}).then(M=>{let U=E.length;de=M.ok?`copied ${U} char${U===1?"":"s"} to clipboard`:`clipboard copy failed: ${M.reason}`,Gn()},M=>{de=`clipboard copy failed: ${M.message}`,Gn()})},R=E=>{let M=Me.state().buffer[E.row]??"";if(M.length===0)return null;let U=Math.max(0,Math.min(M.length-1,E.col));if(!ws.test(M[U]))return null;let K=U;for(;K>0&&ws.test(M[K-1]);)K--;let se=U+1;for(;se<M.length&&ws.test(M[se]);)se++;return{start:K,end:se}},xf=E=>{let M=Me.state().buffer[E]??"";tr({row:E,col:0},{row:E,col:M.length})},_g=E=>{let M=an;if(M===null)return;let U=E.row<M.row||E.row===M.row&&E.col<M.start,K=E.row>M.row||E.row===M.row&&E.col>M.end,se={row:M.row,col:M.start},oe={row:M.row,col:M.end};if(U){let pe=R(E);se=pe!==null?{row:E.row,col:pe.start}:E}else if(K){let pe=R(E);oe=pe!==null?{row:E.row,col:pe.end}:E}tr(se,oe)},If=E=>{let M=Xa;if(M===null)return;let U=Math.min(M,E.row),K=Math.max(M,E.row),se=Me.state().buffer[K]??"";tr({row:U,col:0},{row:K,col:se.length})},Cf=E=>{if(!ys)return;let M=Ni(E.x,E.y);if(M===null)return;mr=M,ce=!1,Lr=!1,Nr=1,xe="char",an=null,Xa=null,Ur();let U=Date.now(),K=Oo,se=K!==null&&U-K.t<=Mg&&Math.abs(E.x-K.x)<=sl&&Math.abs(E.y-K.y)<=sl&&K.row!==null&&K.row===M.row;if(se&&K.count===2&&E.x===K.x&&E.y===K.y){Nr=3,xf(M.row),xe="line",Xa=M.row,Lr=!0;return}if(se&&K.count===1){Nr=2;let nt=R(M);nt!==null&&(tr({row:M.row,col:nt.start},{row:M.row,col:nt.end}),Lr=!0,xe="word",an={row:M.row,start:nt.start,end:nt.end})}},dd=E=>{if(mr===null)return;let M=Math.max(1,Math.min(Ut,E.x)),U=Math.max($n+1,Math.min($n+gn,E.y)),K=Ni(M,U);K!==null&&(ce=!0,xe==="word"?_g(K):xe==="line"?If(K):tr(mr,K))},Do=E=>{let M=ce,U=Lr;if(mr=null,ce=!1,Lr=!1,E!==null){let K=Ni(E.x,E.y);Oo={x:E.x,y:E.y,t:Date.now(),count:Nr,row:K?.row??null}}if(Nr=1,M||U){ad();return}Ur()},gr=()=>tt?p===0?"f":It?"h":"u":"x",Rf=()=>`ct|${gr()}|${me()}|${Za}|${$i()}|${Xt??""}`,al=()=>`cb|${gr()}|${me()}`,
|
|
263
|
+
`},{suspend:()=>this.stop(),resume:()=>this.start(),notify:r=>this.notify(r)}).finally(()=>{this.foregroundChildActive=!1}))}schedulePendingBlockClick(e,t,r){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t,r);return}this.cancelPendingBlockClick();let s=this.onBlockClick,o=setTimeout(()=>{this.pendingBlockClick=null,s(e,t,r)},nl);typeof o.unref=="function"&&o.unref(),this.pendingBlockClick={timer:o,key:e,rowOffset:t,subKey:r}}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 r=this.lines[t];if(r&&this.lineIds.get(r)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Zc(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===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,r=Number(t.x),s=Number(t.y);return!Number.isFinite(r)||!Number.isFinite(s)?null:{x:r,y:s}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,we(e==="pointer"?cE:bm))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null||t.startsWith("agent:"))return null;let r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let{rows:i}=this.wrapTail(r,o+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-o),c=i.slice(d,a),l=Math.max(0,o-c.length),u=e-s-l,f=d+u,p=null,m=1/0;for(let h=0;h<i.length;h++){let g=i[h];if(g.blockKey!==t||g.linkSpans===void 0||g.linkSpans.length===0)continue;let w=Math.abs(h-f);w<m&&(m=w,p=g.linkSpans[0]?.url??null)}return p}keyAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-l;return u<0||u>=c.length?null:c[u]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let r=this.keyAtRow(t);if(r!==null)return r}return null}nearestKeyBelowRow(e){let r=this.scrollbackVisibleRows();for(let s=e+1;s<=r;s++){let o=this.keyAtRow(s);if(o!==null)return o}return null}keyAndSubAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-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 r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let i=t-s;if(i<0||i>=o||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(r,o+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-o),l=a.slice(c,d),u=Math.max(0,o-l.length),f=i-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=Pt(p.prefix??""),g=m.bodyDisplayShift??0,w=e-1-h;if(w<g)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let b=w,S=df(p.bodyStyle)||p.ansi===!0?$M(Kv(p.body),b):_M(p.body,b);if(m.sourceColEnd!==void 0){let I=this.sourceBodyForId(m.sourceLineId);if(I!==null){let x=Uv(p.body,g,S),A=Wv(I,m.sourceColOffset,x);return{sourceLineId:m.sourceLineId,offset:A}}}return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset+S-g}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),r=Math.min(t,Math.max(0,this.scrollOffset+e));r!==this.scrollOffset&&(this.scrollOffset=r,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){if(this.pageWhenNoTurns(1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=e.find(s=>s>t);this.stepToTurnStop(r??this.maxScrollOffset())}scrollToNextTurn(){if(this.pageWhenNoTurns(-1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=0;for(let s of e){if(s>=t)break;r=s}this.stepToTurnStop(r)}pageWhenNoTurns(e){return this.turnScrollOffsets().length>0?!1:(this.scrollBy(e*this.scrollPageSize()),!0)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),t=[0,...this.turnScrollOffsets(),e].filter(r=>r>=0&&r<=e).sort((r,s)=>r-s);return t.filter((r,s)=>s===0||r!==t[s-1])}notifyTurnPosition(e){let t=this.turnScrollOffsets();if(t.length===0)return;let r=t.findIndex(o=>o>=e),s=r===-1?1:t.length-r;this.notify(`turn ${s}/${t.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),t=this.scrollbackVisibleRows();if(t<=0)return[];let r=[],s=0,o=null;for(let i=this.lines.length-1;i>=0;i--){let a=this.lines[i];if(!(!a||this.isHiddenLine(a))){if(s+=this.wrapOne(a,e).length,a.bodyStyle==="user"){o={offset:Math.max(0,s-t),lineIndex:i,recordedAt:a.recordedAt};continue}o!==null&&(r.push(o),o=null)}}return o!==null&&r.push(o),r}scrollToTurnAt(e){let t=this.turnAnchors();if(t.length===0)return;let r=t.find(s=>s.recordedAt!==void 0&&s.recordedAt<=e)??t[t.length-1];this.setScrollOffset(r.offset),this.notifyTurnPosition(r.offset)}slideScrollTo(e){this.cancelSlide();let t=Math.min(this.maxScrollOffset(),Math.max(0,e)),r=Math.abs(t-this.scrollOffset);if(r!==0){if(r<=MK||!this.slideEnabled){this.setScrollOffset(t);return}this.slideTarget=t,this.slideTimer=setInterval(()=>{let s=this.slideTarget-this.scrollOffset,o=Math.sign(s)*Math.max(1,Math.round(Math.abs(s)*PK)),i=Math.abs(s)<=Math.abs(o)?this.slideTarget:this.scrollOffset+o;this.scrollOffset=i,this.syncedPartialRepaint(()=>this.drawScrollback()),i===this.slideTarget&&this.cancelSlide()},EK)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=Math.min(this.maxScrollOffset(),Math.max(0,e));t!==this.scrollOffset&&(this.scrollOffset=t,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(),r=[];if(t.length>0)for(let s=this.lines.length-1;s>=0;s--){let o=this.lines[s];if(!o||o.body.length===0||o.ansi)continue;let i=s_(o.body,t);for(let a=i.length-1;a>=0;a--)r.push({lineIdx:s,col:i[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=r,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=t.length>0?t:null,r.length>0&&this.scrollToMatch(r[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 r=this.lineIds.get(t);return r===void 0?null:{lineId:r,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let r=this.wrapOrigin.get(e);if(!r||r.sourceLineId!==t.lineId)return null;let s=r.bodyDisplayShift??0,o=t.col-r.sourceColOffset+s;return o<s||o>=e.body.length?null:o}scrollToMatch(e){let t=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return;let s=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(s+=this.wrapOne(u,t).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,t),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let m=p.body.length;if(e.col<u+m){i=l.length-1-f;break}u+=m}}let a=s+i,d=Math.max(0,a-Math.floor(r/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()-$t-Ht-Bt-yK-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,r,s){return this.started?this.painter.paintRow(e,t,r,s):!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),this.barHits.clear(),pt(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let r=this.promptRows(),s=t-r-Bt-Ht-$t;this.drawBar("composerTop",s),this.drawPrompt(),this.drawBar("composerBottom",t-$t),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=r}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:this.hintsRevealed(),scriptOutputs:this.scriptOutputs}}trackHintHover(e){return e?(this.cancelHintHoverHide(),this.hintHoverReveal?!1:(this.hintHoverReveal=!0,!0)):(!this.hintHoverReveal||this.hintHoverHideTimer!==null||(this.hintHoverHideTimer=setTimeout(()=>{this.hintHoverHideTimer=null,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars())},hK)),!1)}cancelHintHoverHide(){this.hintHoverHideTimer!==null&&(clearTimeout(this.hintHoverHideTimer),this.hintHoverHideTimer=null)}hintsRevealed(){return this.terminalFocused?this.hintHoverReveal||this.hintKeyReveal:!1}revealHints(){this.hintKeyReveal||(this.hintKeyReveal=!0,this.syncedPartialRepaint(()=>this.drawBars()))}clearHintReveal(){this.cancelHintHoverHide(),!(!this.hintKeyReveal&&!this.hintHoverReveal)&&(this.hintKeyReveal=!1,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars()))}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:[],queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:!1,scriptOutputs:this.scriptOutputs}}drawBar(e,t){let r=dv[e],s=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,o=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top;e==="composerBottom"&&(this.composerBottomRow=t);let i=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?VP(i):null,d=a!==null?[a]:ef(e,o.right,i),c=sv(s,ef(e,o.left,i),d,r);e==="composerBottom"&&(this.hintZoneStart=this.hintZoneStartFor(s,o,i,a,c));let l=this.terminalFocused?this.hoveredBarHit:null,u=`${e}|${s}|${l??""}|${c.signature}`;this.paintRow(t,u,()=>{for(let f of c.chunks){let p=f.id!==void 0&&f.id===l?"hint-hover":f.token;B(this.term,p,f.text)}}),this.barHits.set(t,c.hits)}hintZoneStartFor(e,t,r,s,o){if(s!==null)return null;if(r.hintsRevealed)return o.rightStart;let i={...r,hintsRevealed:!0};return sv(e,ef("composerBottom",t.left,i),ef("composerBottom",t.right,i),dv.composerBottom).rightStart}barHitAt(e,t){let r=this.barHits.get(t);return r===void 0?null:r.find(s=>e>=s.start&&e<=s.end)??null}bannerHitAt(e,t){let r=this.barHitAt(e,t);if(r===null)return null;let s=r.id.slice(r.id.indexOf(":")+1);return Jk.some(o=>o.id===s)?s:null}stepFormCursor(e){let t=this.formPrompt;if(t===null||t.rows.length===0)return;let r=Math.max(0,Math.min(t.rows.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onFormClick?.({kind:"row",row:r,select:!0})}isFormCell(e){let t=this.formRegion;return this.formPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}formHitAt(e,t){if(!this.isFormCell(t))return null;for(let s of this.formHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.formRowHits.get(t);if(r===void 0)return null;if(r.field!==void 0&&e>=r.field.startCol){let{slice:s,sliceStart:o,startCol:i}=r.field,a=o,d=i;for(let c of s){let l=d+Pt(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:r.row,caretOffset:a}}return{kind:"row",row:r.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let t=this.formPressHit;if(this.formPressHit=null,t===null||e===null||!this.isFormCell(e.y))return t!==null;let r=this.formHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="row"&&t.kind==="row"&&r.row!==t.row||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action||this.onFormClick?.(r),!0}handleBarPress(e){let t=this.barHitAt(e.x,e.y);if(t===null)return this.barPressHit=null,!1;let r=Date.now(),s=this.lastBarClick;return s!==null&&s.id===t.id&&r-s.t<=nl&&t.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(t.doubleAction,t.value),!0):(this.lastBarClick={id:t.id,t:r},this.barPressHit=t,!0)}handleBarRelease(e){let t=this.barPressHit;if(this.barPressHit=null,t===null||e===null)return!1;let r=this.barHitAt(e.x,e.y);return r===null||r.id!==t.id?!1:(r.action==="none"||this.dispatchBarAction(r.action,r.value),!0)}dispatchBarAction(e,t){if(e!=="none"){if(e==="copy"){Zc(t,{target:this.selectionClipboard}).then(r=>{this.notify(r.ok?`copied ${t}`:`clipboard copy failed: ${r.reason}`)},r=>{this.notify(`clipboard copy failed: ${r.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(t);return}if(e==="open"){this.tryOpenPathString(t)||this.notify(this.hasOpenFileCommand()?`can't open ${t}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,t)}}drawScrollback(){let e=this.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),r=this.sidebarBodyWidth()>0,s=1,o=this.scrollbackVisibleRows();if(o<=0)return;let{rows:i,exhausted:a}=this.wrapTail(e,o+this.scrollOffset);if(a){let g=Math.max(0,i.length-o);this.scrollOffset>g&&(this.scrollOffset=g)}let d=i.length-this.scrollOffset,c=Math.max(0,d-o),l=i.slice(c,d),u=Math.max(0,o-l.length),f=this.currentMatchInfo(),p=f?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let m=-1,h=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let g=0;g<l.length;g++){let w=l[g]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(m===-1&&(m=g),h=g)}for(let g=0;g<o;g++){let w=s+g,b=g-u,k=b>=0?l[b]:void 0,S=this.activeMatchCol(k,f),I=k?this.selectionRangeForChunk(k):null,x=k!==void 0&&k.blockKey!==void 0&&(k.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(k.blockKey)),A=k!==void 0&&k.blockKey===void 0&&m!==-1&&b>=m&&b<=h,_=x||A,P=this.terminalFocused&&_&&(this.hoveredSubKey===null||(k.hoverSubKey??null)===this.hoveredSubKey),$=Hv("sb",e,k,this.scrollbackHighlight,S,I)+(P?"|H":"");this.paintRow(w,$,()=>{k?this.writeFormattedLine(k,e,S,p,I,P,t,k.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&r&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let g=new Set;for(let b of l)b.blockKey!==void 0&&g.add(b.blockKey);let w=[];for(let b of this.pendingVisibleKeys)g.has(b)&&w.push(b);for(let b of w)this.pendingVisibleKeys.delete(b),this.onBlockVisible(b)}}drawSidebar(e,t){let r=this.sidebarBodyWidth();if(r<=0||t<=0){this.sidebarOverflowRows=0;return}let s=this.sidebarColumnStart(),o={metrics:{cellWidth:Pt,truncate:mn},width:r,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:t},i={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(i,o);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarRowLinks.clear();let c=s+af;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?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(u,p.doubleAction),p?.links!==void 0&&p.links.length>0&&this.sidebarRowLinks.set(u,p.links.map(w=>({start:c+w.start,end:c+w.end,url:w.url}))),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,..."page"in w?{gadget:w.page.gadget,index:w.page.index}:{gadget:w.collapse.gadget,collapse:!0}})));let m=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",h=(()=>{let w=[];if(p?.openPath!==void 0&&p.openPath.startsWith("/")&&p.openSpan!==void 0&&w.push({...p.openSpan,url:Vb(p.openPath)}),p?.links!==void 0){let b=this.linkSpansForWindow(p.body,p.links,0,p.body.length,0);b!==null&&w.push(...b)}return w.length>0?w:null})(),g=Hv("sbar",r,p,null,null,null)+`|${m}|${h===null?"":h.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(u,g,()=>{this.term(" ".repeat(Math.max(0,af-1))),m===" "?this.term(" "):to(this.term,m,"sidebar-rule",!1),p?this.writeFormattedLine(p,r,null,0,null,!1,!0,h):this.term(" ".repeat(r))},{region:"sidebar",column:s})}}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 r=this.sidebarColumnStart();return r===0?!1:e>=r&&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 o of this.sidebarRowActions.get(e.y)??[])if(!(e.x<o.start||e.x>o.end))return o.collapse===!0?this.toggleSidebarGadgetCollapsed(o.gadget):this.sidebarPages={...this.sidebarPages,[o.gadget]:o.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),r=this.lastSidebarClick;if(r!==null&&t-r.t<=nl&&e.y===r.y){this.lastSidebarClick=null;let o=this.sidebarRowDoubleActions.get(e.y);if(o!==void 0)return this.dispatchBarAction(o.action,o.value),!0;let a=this.sidebarRowLinks.get(e.y)?.find(c=>e.x>=c.start&&e.x<c.end);if(a!==void 0)return this.dispatchLinkUrl(a.url),!0;let d=this.sidebarRowPaths.get(e.y);return d!==void 0&&!this.dispatchLinkUrl(d)&&this.notify(this.hasOpenFileCommand()?`can't open ${d}`:"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(Lv,this.queuedTexts.length)}chipRows(){return Math.min(Dv,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,r)=>t===e[r])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Nv,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-$t-Ht-Bt,o=this.queuedRows(),i=this.chipRows(),d=s-1-o-i-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>Nv,m=this.completions.length-Nv+1,h=f?p?`comp|${t}|overflow|${m}`:`comp|${t}|${c}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,h,()=>{if(!f)return;if(p){B(this.term,"modal-hint",` + ${m} more match(es)`);return}let g=f.name.padEnd(c),w=f.description??"",b=t-g.length-4,k=b>0?mn(w,b):"";this.term.noFormat(" "),B(this.term,"completion-name",g),k.length>0&&(this.term.noFormat(" "),B(this.term,"completion-desc",k))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),i=this.term.height-r-$t-Ht-Bt-1-e+1;for(let a=0;a<e;a++){let d=i+a,c=a===e-1&&this.attachments.length>Dv,l=this.attachments.length-Dv,u=this.attachments[a],f=u?`${u.name??"image"} \xB7 ${Mr(u.sizeBytes)}`:"",p=c?`chip|${t}|overflow|${l}`:u?`chip|${t}|${f}`:`chip|${t}|empty`;this.paintRow(d,p,()=>{if(c){B(this.term,"modal-hint",` \u{1F4CE} + ${l+1} more attached`);return}u&&(this.term.noFormat(" "),B(this.term,"attachment",`\u{1F4CE} ${f}`))})}}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-$t-Ht-Bt,o=this.chipRows(),a=s-1-o-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>Lv,p=this.queuedTexts.length-Lv,m=u===void 0?"":f?`+ ${p+1} more queued`:mn(XK(u),t-4),h=!f&&c===d,g=u===void 0?`queued|${t}|empty`:`queued|${t}|${h?"edit":f?"ovf":"row"}|${m}`;this.paintRow(l,g,()=>{if(u===void 0)return;let w=`\u23F3 ${m}`,b=w+" ".repeat(Math.max(0,t-1-w.length));h?B(this.term,"queue-cursor","\u25B8"):B(this.term,"queue-blank"," "),B(this.term,"queue-row",b)})}}promptVisualLayout(){if(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt||this.scrollbackSearch||this.readonly)return null;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=ms(r.buffer,t),o=no(s,r,cg);return{top:this.term.height-o.rendered-Bt-Ht-$t+1,layout:o,visualRows:s}}resolveCellToPromptOffset(e,t){let r=this.promptVisualLayout();if(r===null)return null;let{top:s,layout:o,visualRows:i}=r,a=t-s;if(a<0||a>=o.rendered||e<1||e>this.term.width)return null;let d=i[o.windowStart+a];if(!d)return null;let l=Math.max(0,Math.min(d.endCol-d.startCol,e-1-2));return{row:d.bufferIdx,col:d.startCol+l}}setPromptSelection(e,t){let r=e.row<t.row||e.row===t.row&&e.col<=t.col,s=r?e:t,o=r?t:e;if(s.row===o.row&&s.col===o.col){this.clearPromptSelection();return}let i={startRow:s.row,startCol:s.col,endRow:o.row,endCol:o.col},a=this.promptSelection;a&&a.startRow===i.startRow&&a.startCol===i.startCol&&a.endRow===i.endRow&&a.endCol===i.endCol||(this.promptSelection=i,this.syncedPartialRepaint(()=>this.drawPrompt()))}clearPromptSelection(){this.promptSelection!==null&&(this.promptSelection=null,this.syncedPartialRepaint(()=>this.drawPrompt()))}getPromptSelectionText(){if(this.promptSelection===null)return"";let{startRow:e,startCol:t,endRow:r,endCol:s}=this.promptSelection,o=this.dispatcher.state().buffer;if(e===r)return(o[e]??"").slice(t,s);let i=[(o[e]??"").slice(t)];for(let a=e+1;a<r;a++)i.push(o[a]??"");return i.push((o[r]??"").slice(0,s)),i.join(`
|
|
264
|
+
`)}promptWordBoundsAt(e){let t=this.dispatcher.state().buffer[e.row]??"";if(t.length===0)return null;let r=Math.max(0,Math.min(t.length-1,e.col));if(!Ka.test(t[r]))return null;let s=r;for(;s>0&&Ka.test(t[s-1]);)s--;let o=r+1;for(;o<t.length&&Ka.test(t[o]);)o++;return{start:s,end:o}}selectPromptWholeLine(e){let t=this.dispatcher.state().buffer[e]??"";this.setPromptSelection({row:e,col:0},{row:e,col:t.length})}extendPromptWordSelectionTo(e){let t=this.promptSelectionAnchorWordBounds;if(t===null)return;let r=e.row<t.row||e.row===t.row&&e.col<t.start,s=e.row>t.row||e.row===t.row&&e.col>t.end,o={row:t.row,col:t.start},i={row:t.row,col:t.end};if(r){let a=this.promptWordBoundsAt(e);o=a!==null?{row:e.row,col:a.start}:e}else if(s){let a=this.promptWordBoundsAt(e);i=a!==null?{row:e.row,col:a.end}:e}this.setPromptSelection(o,i)}extendPromptLineSelectionTo(e){let t=this.promptSelectionAnchorLineRow;if(t===null)return;let r=Math.min(t,e.row),s=Math.max(t,e.row),o=this.dispatcher.state().buffer[s]??"";this.setPromptSelection({row:r,col:0},{row:s,col:o.length})}handlePromptSelectionPress(e){if(!this.inAppSelectionEnabled)return!1;let t=this.resolveCellToPromptOffset(e.x,e.y);if(t===null)return!1;this.promptSelectionAnchor=t,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,this.promptPendingClickCount=1,this.promptSelectionGranularity="char",this.promptSelectionAnchorWordBounds=null,this.promptSelectionAnchorLineRow=null,this.clearPromptSelection();let r=Date.now(),s=this.promptLastLeftClick,o=s!==null&&r-s.t<=nl&&Math.abs(e.x-s.x)<=rl&&Math.abs(e.y-s.y)<=rl&&s.row!==null&&s.row===t.row;if(o&&s.count===2&&e.x===s.x&&e.y===s.y)return this.promptPendingClickCount=3,this.selectPromptWholeLine(t.row),this.promptSelectionGranularity="line",this.promptSelectionAnchorLineRow=t.row,this.promptDoubleClickPending=!0,!0;if(o&&s.count===1){this.promptPendingClickCount=2;let d=this.promptWordBoundsAt(t);d!==null&&(this.setPromptSelection({row:t.row,col:d.start},{row:t.row,col:d.end}),this.promptDoubleClickPending=!0,this.promptSelectionGranularity="word",this.promptSelectionAnchorWordBounds={row:t.row,start:d.start,end:d.end})}return!0}handlePromptSelectionDrag(e){if(this.promptSelectionAnchor===null)return;let t=this.promptVisualLayout();if(t===null)return;let r=Math.max(1,Math.min(this.term.width,e.x)),s=Math.max(t.top,Math.min(t.top+t.layout.rendered-1,e.y)),o=this.resolveCellToPromptOffset(r,s);o!==null&&(this.promptSelectionDragStarted=!0,this.promptSelectionGranularity==="word"?this.extendPromptWordSelectionTo(o):this.promptSelectionGranularity==="line"?this.extendPromptLineSelectionTo(o):this.setPromptSelection(this.promptSelectionAnchor,o))}handlePromptSelectionRelease(e){let t=this.promptSelectionDragStarted,r=this.promptDoubleClickPending;if(this.promptSelectionAnchor=null,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,e!==null){let s=this.resolveCellToPromptOffset(e.x,e.y);this.promptLastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.promptPendingClickCount,row:s?.row??null}}if(this.promptPendingClickCount=1,t||r){this.finalizePromptSelection();return}this.clearPromptSelection()}finalizePromptSelection(){let e=this.getPromptSelectionText();e.length!==0&&Zc(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}drawPrompt(){if((this.permissionPrompt||this.formPrompt||this.confirmPrompt)&&(this.compactionRegion=null),(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt)&&(this.helpRegion=null),this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();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),r=this.dispatcher.state(),s=ms(r.buffer,t),o=no(s,r,cg),i=this.term.height-o.rendered-Bt-Ht-$t+1,a=!1;for(let d=0;d<o.rendered;d++){let c=s[o.windowStart+d],l=i+d,u="wrap",f="";c&&(c.bufferIdx===0&&c.startCol===0?u="first":c.startCol===0&&(u="newline"),f=(r.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=-1,m=-1;if(c&&this.promptSelection!==null){let g=this.promptSelection;if(c.bufferIdx>=g.startRow&&c.bufferIdx<=g.endRow){let w=c.bufferIdx===g.startRow?g.startCol:c.startCol,b=c.bufferIdx===g.endRow?g.endCol:c.endCol,k=Math.max(w,c.startCol),S=Math.min(b,c.endCol);S>k&&(p=k-c.startCol,m=S-c.startCol)}}let h=c?`prompt|${this.term.width}|${u}|${f}|${p}:${m}`:`prompt|${this.term.width}|empty`;this.paintRow(l,h,()=>{c&&(u==="first"?a?B(this.term,"composer-inactive","> "):B(this.term,"composer-gutter","> "):u==="newline"?B(this.term,"composer-continuation","\xB7 "):this.term(" "),a?B(this.term,"composer-inactive",f):p>=0&&m>p?(p>0&&B(this.term,"content",f.slice(0,p)),B(this.term,"selection-highlight",f.slice(p,m)),m<f.length&&B(this.term,"content",f.slice(m))):B(this.term,"content",f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,r=this.term.height-Bv-Bt-Ht-$t+1;this.paintRow(r,`confirm|q|${t}|${e.question}`,()=>{B(this.term,"prompt-text",` ? ${mn(e.question,t-4)}`)}),this.paintRow(r+1,`confirm|h|${t}|${e.hint}`,()=>{B(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,r=this.compactionRows(),s=this.term.height-r-Bt-Ht-$t+1,o=s;this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion={top:s,bottom:s+r-1};let i=(c,l)=>{o>=s+r||(this.paintRow(o,c,l),o+=1)};i(`cpct|msg|${t}|${e.message}`,()=>{B(this.term,"prompt-text",` ${mn(e.message,t-2)}`)}),i(`cpct|q|${t}`,()=>{B(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let c=0;c<e.options.length&&!(o>=s+r-1);c++){let l=e.options[c];if(!l)continue;let u=c===e.selectedIndex,p=` ${u?"\u276F":" "} ${c+1}. ${mn(l.label,t-8)}`;this.compactionRowHits.set(o,c),i(`cpct|o|${t}|${c}|${u?"1":"0"}|${l.label}`,()=>{u?B(this.term,"modal-option-selected",p):B(this.term,"modal-option",p)})}let a=jv(IK,t),d=o;for(let c of a.spans)(c.action==="commit"||c.action==="cancel")&&this.compactionHintHits.push({row:d,start:c.start,end:c.end,action:c.action});i(`cpct|hint|${t}|${a.text}`,()=>{B(this.term,"modal-hint",` ${a.text}`)})}isCompactionCell(e){let t=this.compactionRegion;return this.compactionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}compactionHitAt(e,t){if(!this.isCompactionCell(t))return null;for(let s of this.compactionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.compactionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}stepCompactionCursor(e){let t=this.compactionPrompt;if(t===null||t.options.length===0)return;let r=Math.max(0,Math.min(t.options.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onCompactionClick?.({kind:"option",index:r,select:!0})}handleCompactionPress(e){return this.isCompactionCell(e.y)?(this.compactionPressHit=this.compactionHitAt(e.x,e.y),!0):(this.compactionPressHit=null,!1)}handleCompactionRelease(e){let t=this.compactionPressHit;if(this.compactionPressHit=null,t===null||e===null||!this.isCompactionCell(e.y))return t!==null;let r=this.compactionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.compactionArmedAt<XM?(this.notify("compaction prompt just appeared, click again to confirm"),!0):(this.onCompactionClick?.(r),!0)}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let t=this.term.width,r=this.helpRows(),s=this.term.height-r-Bt-Ht-$t+1,o=s;this.helpRegion={top:s,bottom:s+r-1};let i=(d,c)=>{o>=s+r||(this.paintRow(o,d,c),o+=1)};i(`help|t|${t}|${e.title}`,()=>{B(this.term,"prompt-text",` \u2753 ${mn(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(o>=s+r-1)break;if(d===null){i(`help|sep|${t}|${o}`,()=>{});continue}let[c,l]=d,u=c.padEnd(a);i(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),B(this.term,"modal-key",u),B(this.term,"content",` ${mn(l,t-2-a-1)}`)})}i(`help|hint|${t}|${e.hint}`,()=>{B(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(RK,2+this.helpPrompt.entries.length):0}isHelpCell(e){let t=this.helpRegion;return this.helpPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}handleHelpPress(e){return this.isHelpCell(e.y)?(this.helpPressed=!0,!0):(this.helpPressed=!1,!1)}handleHelpRelease(e){let t=this.helpPressed;return this.helpPressed=!1,t?(e!==null&&this.isHelpCell(e.y)&&this.onHelpClick?.(),!0):!1}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,r=this.permissionRows(),s=this.term.height-r-Bt-Ht-$t+1,o=s;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:s,bottom:s+r-1};let i=(l,u)=>{o>=s+r||(this.paintRow(o,l,u),o+=1)};i(`perm|t|${t}|${e.title}`,()=>{B(this.term,"prompt-text",` \u{1F512} ${mn(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${t}|${a}`,()=>{B(this.term,"modal-hint",` ${mn(a,t-2)}`)}),i(`perm|q|${t}`,()=>{B(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(o>=s+r-1);l++){let u=e.options[l];if(!u)continue;let f=l===e.selectedIndex,m=` ${f?"\u276F":" "} ${l+1}. ${mn(u.label,t-8)}`;this.permissionRowHits.set(o,l),i(`perm|o|${t}|${l}|${f?"1":"0"}|${u.label}`,()=>{f?B(this.term,"modal-option-selected",m):B(this.term,"modal-option",m)})}let d=jv(xK,t),c=o;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});i(`perm|hint|${t}|${d.text}`,()=>{B(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let t=this.permissionRegion;return this.permissionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}permissionHitAt(e,t){if(!this.isPermissionCell(t))return null;for(let s of this.permissionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.permissionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let t=this.permissionPressHit;if(this.permissionPressHit=null,t===null||e===null||!this.isPermissionCell(e.y))return t!==null;let r=this.permissionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.permissionArmedAt<XM?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(r),!0)}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 ":""}drawBanner(){let e=this.term.height,t=this.promptRows(),r=e-t-Bt-Ht-$t;this.drawBar("composerTop",r),this.drawBar("composerBottom",e-$t)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Bt-Ht-$t+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Bt-Ht-$t;this.term.moveTo(2,Math.min(f,p));return}if(this.formPrompt){let l=this.formPrompt,u=this.formWindowSize(),f=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-f),m=this.term.height-Bt-Ht-$t,h=Math.min(p,m),w=t_(l,this.term.width,f,u).find(b=>b.selected);if(w?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(w.caretCol,this.term.width),h);return}if(this.confirmPrompt){let l=this.term.height-Bv-Bt-Ht-$t+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Bt-Ht-$t+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Bt-Ht-$t;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Bt-Ht-$t+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),r=this.dispatcher.state(),s=ms(r.buffer,t),o=no(s,r,cg),a=this.term.height-o.rendered-Bt-Ht-$t+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Bt-Ht-$t;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return Bv;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),r=this.dispatcher.state(),s=ms(r.buffer,t);return Math.min(cg,Math.max(1,s.length))}permissionRows(){return this.permissionPrompt?Math.min(vK,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(CK,this.formPrompt.maxRows??SK),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Bt-Ht-$t+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let t=this.term.width,r=this.formRows(),s=this.formTop(),o=this.formWindowSize(),i=`${e.title}|${e.rows.length}|${o}`;i!==this.formWindowKey?(this.formWindowKey=i,this.formWindowTop=GK(e.rows.length,e.selectedIndex,o)):this.formWindowTop=JK(this.formWindowTop,e.rows.length,e.selectedIndex,o);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:s,bottom:s+r-1};let d=s,c=(h,g)=>{d>=s+r||(this.paintRow(d,h,g),d+=1)},l=e.rows.length>o?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${t}|${e.title}|${l}`,()=>{B(this.term,"prompt-text",` \u2699 ${mn(`${e.title}${l}`,t-5)}`)});let u=t_(e,t,a,o);for(let h of u){if(d>=s+r-1)break;this.formRowHits.set(d,{row:h.index,...h.kind==="text"?{field:{startCol:1+Pt(h.prefix),slice:h.field,sliceStart:h.fieldStart}}:{}}),c(h.sig,()=>{if(h.kind==="text"){B(this.term,h.selected?"modal-option-selected":"modal-option",h.prefix),B(this.term,"content",h.field);return}B(this.term,h.selected?"modal-option-selected":"modal-option",h.body)})}let f=e.hints??VK,p=d,m=jv(f,t);for(let h of m.spans)this.formHintHits.push({row:p,...h});c(`form|hint|${t}|${m.text}`,()=>{B(this.term,"modal-hint",` ${m.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,r=this.wrapBtwWindow(t,e,0).rows.length;return Math.min(this.btwOverlayMaxHeight,1+r)}wrapBtwWindow(e,t,r){let s=this.btwOverlayLines.length;if(t<=0||s===0)return{rows:[],offset:0,more:!1};if(e<=4){let f=Math.min(Math.max(0,r),Math.max(0,s-t)),p=s-f,m=Math.max(0,p-t);return{rows:this.btwOverlayLines.slice(m,p),offset:f,more:m>0}}let o=Math.max(0,r),i=[],a=0;for(let f=s-1;f>=0;f--){let p=this.btwOverlayLines[f],m=this.wrapOne(p,e);if(i.push(m),a+=m.length,a>t+o)break}let d=[];for(let f=i.length-1;f>=0;f--)d.push(...i[f]);let c=Math.min(o,Math.max(0,d.length-t)),l=d.length-c,u=Math.max(0,l-t);return{rows:d.slice(u,l),offset:c,more:u>0}}scrollBtwOverlayBy(e){let t=this.btwOverlayRegion;if(!this.btwOverlayOpen||t===null||t.contentRows<=0)return!1;let r=Math.max(0,this.btwOverlayScroll+e),s=this.wrapBtwWindow(this.term.width,t.contentRows,r);return!s.more&&s.offset===0?!1:(s.offset===this.btwOverlayScroll||(this.btwOverlayScroll=s.offset,this.repaintNow()),!0)}isBtwOverlayCell(e){let t=this.btwOverlayRegion;return t!==null&&e>=t.top&&e<=t.bottom}btwOverlayScrollState(){let t=this.btwOverlayRegion?.contentRows??0;return{offset:this.btwOverlayScroll,more:this.wrapBtwWindow(this.term.width,t,this.btwOverlayScroll).more}}drawBtwOverlay(){if(!this.btwOverlayOpen){this.btwOverlayRegion=null;return}let e=this.btwOverlayRows();if(e===0){this.btwOverlayRegion=null;return}let t=this.term.width,s=this.term.height-this.promptRows()-Bt-Ht-$t,o=this.chipRows()+this.queuedRows()+this.completionRows(),i=s-1-o,a=i-e+1,d=e-1,c=a;this.btwOverlayRegion={top:c,bottom:i,contentRows:d},this.drawBar("btw",c);let l=this.wrapBtwWindow(t,d,this.btwOverlayScroll);this.btwOverlayScroll=l.offset;let u=l.rows;for(let f=0;f<d;f++){let p=c+1+f,m=u.length-d+f,h=m>=0?u[m]:void 0,g=Hv(`btw|c${f}`,t,h);this.paintRow(p,g,()=>{h?this.writeFormattedLine(h,t):this.term.noFormat(" ".repeat(t))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,t){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(t,d.length);return{rows:d.slice(d.length-c),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],s=0,o=0,i=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(i=!0);continue}let l=this.wrapOne(c,e);if(r.push(l),s+=l.length,o=d,s>=t)break}let a=[];for(let d=r.length-1;d>=0;d--)a.push(...r[d]);return{rows:a,exhausted:o===0||i}}wrapOne(e,t){let r=this.lineIds.get(e);if(r!==void 0){let g=this.wrapCache.get(r);if(g)return g}let s=e.prefix??"",o=Pt(s),i=Math.max(1,t-o-1),a=Math.max(0,Math.min(e.hangingIndent??0,i-1)),d=Math.max(1,i-a),c=df(e.bodyStyle),l=e.ansi?DK(e.body,a>0?d:i):jK(e.body,a>0?d:i,{escapeAware:c}),u=e.ansi?0:e.maxWrapRows??0,f=u>0&&l.length>u;f&&(l.length=u);let p=[],m=0,h=0;for(let g=0;g<l.length;g++){let w=l[g]??"",b=g===0||a===0?w:" ".repeat(a)+w;f&&g===l.length-1&&(b=mn(`${b}\u2026`,i,{escapeAware:c}));let k={prefix:g===0?e.prefix:" ".repeat(o),body:b};if(e.prefixStyle!==void 0&&(k.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(k.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(k.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(k.hoverSubKey=e.hoverSubKey),e.fillRow&&(k.fillRow=!0),e.ansi&&(k.ansi=!0),r!==void 0&&w.length>0)if(e.ansi){let S=m,I=0;for(let P=0;P<w.length;){let $=$r(w,P);if($){P+=$.text.length,$.width>0&&(I+=1);continue}I+=1,P+=1}let x=I;for(;x>0&&m<e.body.length;){let P=$r(e.body,m);if(P){m+=P.text.length,P.width>0&&(x-=1);continue}m+=1,x-=1}let A=m;if(g===l.length-1){for(;A<e.body.length;){let P=$r(e.body,A);if(!P)break;A+=P.text.length}m=A}let _={sourceLineId:r,sourceColOffset:S,sourceColEnd:A};if(g>0&&a>0&&(_.bodyDisplayShift=a),this.wrapOrigin.set(k,_),e.links!==void 0){let P=this.linkSpansForWindow(e.body,e.links,S,A,g===0||a===0?0:a);P!==null&&(k.linkSpans=P)}}else{let S=e.body.indexOf(w,h),I=S===-1?h:S,x={sourceLineId:r,sourceColOffset:I};if(g>0&&a>0&&(x.bodyDisplayShift=a),this.wrapOrigin.set(k,x),e.links!==void 0){let A=this.linkSpansForWindow(e.body,e.links,I,I+w.length,g===0||a===0?0:a);A!==null&&(k.linkSpans=A)}h=I+w.length}p.push(k)}return r!==void 0&&this.wrapCache.set(r,p),p}writeFormattedLine(e,t,r=null,s=0,o=null,i=!1,a=!1,d=null){e.prefix&&to(this.term,e.prefix,e.prefixStyle??e.bodyStyle,i);let c=Math.max(0,t-Pt(e.prefix??"")),l=df(e.bodyStyle),u=e.ansi?e.body:mn(e.body,c,{escapeAware:l}),f=d===null||d.length===0?null:d.map(h=>({start:Math.max(0,Math.min(u.length,h.start)),end:Math.max(0,Math.min(u.length,h.end)),url:h.url})).filter(h=>h.end>h.start).sort((h,g)=>h.start-g.start),p=(h,g,w)=>{if(f===null){w(h,g);return}let b=g+h.length,k=g;for(let S of f){if(S.end<=k||S.start>=b)continue;let I=Math.max(S.start,k),x=Math.min(S.end,b);I>k&&w(h.slice(k-g,I-g),k),process.stdout.write(`\x1B]8;;${S.url}\x1B\\`),w(h.slice(I-g,x-g),I),process.stdout.write("\x1B]8;;\x1B\\"),k=x}k<b&&w(h.slice(k-g),k)},m=(h,g)=>{h.length!==0&&p(h,g,(w,b)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let k=r!==null&&r>=b?r-b:null;NK(this.term,w,e.bodyStyle,this.scrollbackHighlight,k,s,i)}else to(this.term,w,e.bodyStyle,i)})};if(o!==null){let h=Math.max(0,Math.min(u.length,o.start)),g=Math.max(h,Math.min(u.length,o.end)),w=df(e.bodyStyle)||e.ansi===!0;if(m(u.slice(0,h),0),g>h){let k=u.slice(h,g);w&&(k=ug(k)),w?to(this.term,k,"selection-highlight",i):p(k,h,S=>{to(this.term,S,"selection-highlight",i)})}let b=u.slice(g);if(w&&g>h){let k=WK(u.slice(0,g));k.length>0&&(b=k+b)}m(b,g)}else m(u,0);if(e.fillRow||i||a){let h=e.ansi?r_(u):Pt(l?ug(u):u),g=c-h;if(g>0){let w=o!==null&&o.toEndOfLine?"selection-highlight":e.fillRow||i?e.bodyStyle:void 0;to(this.term," ".repeat(g),w,i)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset()}};o_=/[^\x20-\x7e]/,zv=new Intl.Segmenter(void 0,{granularity:"grapheme"}),i_=!1;VK=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]});function ZK(n,e,t=$o){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let r=t[n];return r?{kind:"resolve",action:r.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 r=e.ch.toLowerCase();if(r==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(r==="p")return{kind:"continue",selected:Math.max(0,n-1)};let s=t.findIndex(o=>o.hotkey.toLowerCase()===r);if(s>=0){let o=t[s];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:n}}async function u_(n,e){ls();let t=st(e.sessionId),r=e.importedFromMachine??"another machine",s=V(e.cwd),o=$o.findIndex(p=>p.key==="view");o<0&&(o=0);let i=null,a=null,d=()=>{let m=7+$o.length*2+2,h=pr(n,{contentHeight:m,title:"Imported session"}),g=h.contentW,w=[{label:"session: ",value:t},{label:"from: ",value:r},{label:"cwd: ",value:s}],b=0;for(let S of w)n.moveTo(h.contentX,h.contentY+b),B(n,"modal-label",` ${S.label}`),B(n,"content",_t(S.value,g-S.label.length-2)),b++;b++;let k=f_(n,h,b,{intro:"What do you want to do?",choices:$o,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"});return i=h,a=k.firstChoiceRow,h},c=()=>{let p=i,m=a;if(!(p===null||m===null))for(let h=0;h<$o.length;h++){let g=$o[h];g&&Jv(n,p,m+h*2,g.label,h===o)}},l=p=>{p<0||p>=$o.length||p===o||(o=p,c())},u=null,f=p_({choiceCount:$o.length,layout:()=>i,firstChoiceRow:()=>a,selected:()=>o,select:l,commit:p=>{let m=$o[p];m&&u?.(m.key)},back:()=>u?.("back")});return Qs({term:n,render:d,onKey:(p,m,h,g)=>{let w=eG(p,h);if(!w)return;let b=ZK(o,w);if(b.kind==="cancel"){g("cancel");return}if(b.kind==="back"){g("back");return}if(b.kind==="resolve"){g(b.action);return}l(b.selected)},onMouse:(p,m,h)=>{u=h,f(p,m)}})}function f_(n,e,t,r){let s=t;n.moveTo(e.contentX,e.contentY+s),B(n,"content",` ${r.intro}`),s+=2;let o=e.contentY+s;for(let i=0;i<r.choices.length;i++){let a=r.choices[i];a&&(Jv(n,e,e.contentY+s,a.label,i===r.selected),s++,n.moveTo(e.contentX,e.contentY+s),B(n,"list-description",` ${a.description}`),s++)}return s++,n.moveTo(e.contentX,e.contentY+s),B(n,"modal-hint",` ${r.footer}`),{firstChoiceRow:o}}function p_(n){let e=null,t=r=>{let s=n.firstChoiceRow();if(s===null)return null;let o=r-s;if(o<0)return null;let i=Math.floor(o/2);return i<n.choiceCount?i:null};return(r,s)=>{if(r==="MOUSE_WHEEL_UP"){n.select(n.selected()-1);return}if(r==="MOUSE_WHEEL_DOWN"){n.select(n.selected()+1);return}if(r==="MOUSE_LEFT_BUTTON_PRESSED"){e={x:s?.x??-1,y:s?.y??-1};return}let o=s?.y;if(typeof o!="number")return;if(r==="MOUSE_MOTION"){let l=t(o);l!==null&&n.select(l);return}if(r!=="MOUSE_LEFT_BUTTON_RELEASED")return;let i=s?.x,a=e!==null&&i===e.x&&o===e.y;if(e=null,!a)return;let d=n.layout();if(d!==null&&typeof i=="number"&&(i<d.x||i>=d.x+d.w||o<d.y||o>=d.y+d.h)){n.back();return}let c=t(o);c!==null&&n.commit(c)}}function Jv(n,e,t,r,s){let i=La(` ${s?"\u276F":" "} ${r}`,e.contentW);n.moveTo(e.contentX,t),B(n,s?"list-selected":"content",i)}function eG(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 h_(n,e,t){let r=st(e.sessionId),s=e.title??V(e.cwd),o=1,i=[{key:"launch",label:"Launch",hotkey:"l",description:"start a new agent session"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=null,d=null,c=()=>{let f=pr(n,{contentHeight:11,title:"Open session",overlay:!0}),p=f.contentW,m=0;n.moveTo(f.contentX,f.contentY+m),B(n,"modal-label"," session: "),B(n,"content",_t(r,p-10)),m++,n.moveTo(f.contentX,f.contentY+m),B(n,"content"," "+_t(s,p-2)),m++,m++;let h=f_(n,f,m,{intro:"What do you want to do?",choices:i,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"});a=f,d=h.firstChoiceRow},l=()=>{let f=a,p=d;if(!(f===null||p===null))for(let m=0;m<i.length;m++){let h=i[m];h&&Jv(n,f,p+m*2,h.label,m===o)}},u=f=>{f<0||f>=i.length||f===o||(o=f,l())};return c(),n.hideCursor(),await new Promise(f=>{let p=!1,m=()=>{p=!0},h=b=>{m(),t.pop(),f(b)},g=(b,k,S)=>{if(b==="CTRL_C"||b==="CTRL_D"){h("cancel");return}if(b==="ESCAPE"){h("back");return}if(b==="ENTER"||b==="KP_ENTER"){h(i[o]?.key??"view");return}if(b==="UP"||b==="SHIFT_TAB"){u(o-1);return}if(b==="DOWN"||b==="TAB"){u(o+1);return}if(S?.isCharacter){let I=b.toLowerCase();if(I==="l"){h("launch");return}if(I==="v"){h("view");return}if(I==="n"){u(o+1);return}if(I==="p"){u(o-1);return}}},w=p_({choiceCount:i.length,layout:()=>a,firstChoiceRow:()=>d,selected:()=>o,select:u,commit:b=>{let k=i[b];k&&h(k.key)},back:()=>h("back")});t.push({onKey:(b,k,S)=>{p||g(b,k,S)},onMouse:(b,k)=>{p||w(b,k)},onResize:()=>{p||c()}})})}var $o,Vv=q(()=>{"use strict";ke();ir();Na();Tn();$o=[{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 lf(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let r=n[t]??"",s=0;for(;s<e.length&&s<r.length&&e[s]===r[s];)s+=1;if(e=e.slice(0,s),e.length===0)break}return e}function m_(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let r=t.indexOf(" "),s=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r);if(e.length===1){let a=e[0]??"",d=o.startsWith(" ")?"":" ";return a+d+o}let i=lf(e);return i.length<=s.length?null:i+o}var hg=q(()=>{"use strict"});import*as g_ from"os";async function Ja(n,e,t={}){let r=t.defaultCwd??(e?await wP(e.cwd):void 0)??g_.homedir();ls();let s=t.title??"Fork locally \u2014 choose cwd",o=t.intro??"Pick a local cwd for this session:",i=e?[{label:"session: ",value:st(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:V(e.cwd)}]:[],a=new vi(r.endsWith("/")?r:r+"/"),d=()=>{let $=gP(a.text);$>0&&a.setText(a.text.slice($))},c=null,l=!1,u=null,f=null,p=null,m=null,h=" Enter accept \xB7 Esc back",g="Enter accept",w="Esc back",b=h.indexOf(g),k=h.indexOf(w),S=()=>{let $=i.length+6;u=pr(n,{contentHeight:$,title:s,overlay:t.overlay===!0});let F=u.contentW,J=0;for(let W of i)n.moveTo(u.contentX,u.contentY+J),B(n,"modal-label",` ${W.label}`),B(n,"content",_t(W.value,F-W.label.length-2)),J++;J++,n.moveTo(u.contentX,u.contentY+J),B(n,"content",` ${o}`),J+=2,A(J),J+=2;let Y=u.contentY+J;c!==null?(n.moveTo(u.contentX,Y),B(n,"input-error",` ${_t(c,F-2)}`),f=null,p=null,m=null):(n.moveTo(u.contentX,Y),B(n,"modal-hint",h),f=Y,p={start:u.contentX+b,end:u.contentX+b+g.length-1},m={start:u.contentX+k,end:u.contentX+k+w.length-1})},I=()=>i.length+3,x=0,A=$=>{if(!u)return;let F=$??I();n.moveTo(u.contentX,u.contentY+F).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+F),B(n,"box-border","\u2502"),n.moveTo(u.contentX,u.contentY+F),n.noFormat(" ");let Y=Math.max(1,u.contentW-1-2),W=a.text,Z=a.cursor;Z<x&&(x=Z),Z-x>=Y&&(x=Z-Y+1),x<0&&(x=0);let ne=W.slice(x,x+Y);x>0&&ne.length>0&&(ne="\u2026"+ne.slice(1));let ve=Wk(W),Ne=(Ge,Ae)=>{if(Ae.length===0)return;let de=Ge+Ae.length;if(ve<=Ge)B(n,"content",Ae);else if(ve>=de)B(n,"modal-hint",Ae);else{let De=ve-Ge;B(n,"modal-hint",Ae.slice(0,De)),B(n,"content",Ae.slice(De))}},Re=Z-x;if(l){Ne(x,ne);return}Re>=ne.length?(Ne(x,ne),B(n,"input-cursor"," ")):(Ne(x,ne.slice(0,Re)),B(n,"input-cursor",ne[Re]??" "),Ne(x+Re+1,ne.slice(Re+1)))},_=()=>{if(A(),!u)return;let $=I()+2;n.moveTo(u.contentX,u.contentY+$).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+$),B(n,"box-border","\u2502");let F=u.contentY+$;n.moveTo(u.contentX,F),c!==null?(B(n,"input-error",` ${_t(c,u.contentW-2)}`),f=null,p=null,m=null):(B(n,"modal-hint",h),f=F,p={start:u.contentX+b,end:u.contentX+b+g.length-1},m={start:u.contentX+k,end:u.contentX+k+w.length-1})},P=$=>{if(l)return;let F=a.text;l=!0,c=null,_(),Ju(F).then(J=>{if(l=!1,J.ok){$({kind:"ok",path:J.path});return}c=J.reason,_()})};return Qs({term:n,render:S,overlay:t.overlay===!0,onKey:($,F,J,Y)=>{if(!l){if($==="ENTER"||$==="KP_ENTER"){P(Y);return}if($==="ESCAPE"){Y({kind:"back"});return}if($==="CTRL_C"||$==="CTRL_D"){Y({kind:"cancel"});return}if($==="TAB"){l=!0,bP(a.text).then(W=>{if(l=!1,W.matches.length===0)return;let Z;if(W.matches.length===1)Z=W.prefix+W.matches[0];else{let ne=lf(W.matches);if(ne.length<=W.basePrefix.length)return;Z=W.prefix+ne}Z!==a.text&&(a.setText(Z,{recordUndo:!0}),d(),c=null,_())});return}if(a.handleKey($,J?.isCharacter===!0)){d(),c=null,_();return}}},onMouse:($,F,J)=>{if(l||$!=="MOUSE_LEFT_BUTTON_PRESSED")return;let Y=F?.x,W=F?.y;if(!(typeof Y!="number"||typeof W!="number")){if(u!==null&&(Y<u.x||Y>=u.x+u.w||W<u.y||W>=u.y+u.h)){J({kind:"back"});return}if(f!==null&&W===f){if(p!==null&&Y>=p.start&&Y<=p.end){P(J);return}if(m!==null&&Y>=m.start&&Y<=m.end){J({kind:"back"});return}}}}})}var Yv=q(()=>{"use strict";ke();ir();jk();hg();Na();Dm();Tn()});import*as w_ from"fs";import*as b_ from"os";import*as mg from"path";function gg(n,e){let t=e;for(;t>0;){let r=n[t-1]??"";if(/\s/.test(r)){if(r===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function tG(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function nG(n){return n.replace(/\\ /g," ")}function y_(n){return n.replace(/ /g,"\\ ")}function rG(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function sG(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=b_.homedir()+t.slice(1)),mg.isAbsolute(t)?t:mg.resolve(e,t)}function oG(n){let e;try{e=w_.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function yg(n,e,t=oG){let r=nG(n),{dirPrefix:s,base:o}=rG(r);if(s.length===0&&!tG(n)&&o.length===0)return null;let i=sG(s,e),a=t(i);if(a===null)return null;let d=o.startsWith("."),c=a.filter(f=>f.name.startsWith(o)&&(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:y_(s+p),candidates:l}}let u=lf(c.map(f=>f.name));return{replacement:y_(s+u),candidates:l}}var Qv=q(()=>{"use strict";hg()});import{spawn as iG}from"child_process";function aG(n,e){let t="";for(let r=0;r<n.length;r++){let s=n[r];if(s!=="%"||r===n.length-1){t+=s;continue}switch(n[r+1]){case"%":t+="%",r++;break;case"s":t+=e.sessionId,r++;break;case"c":t+=e.cwd,r++;break;case"a":t+=e.agentId,r++;break;case"u":t+=e.baseUrl,r++;break;case"t":t+=e.tokenFile,r++;break;default:t+=s;break}}return t}function dG(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function cG(n,e){let t=dG(n.command);if(t.length===0)return null;let r=t.map(a=>mt(aG(a,e))),[s,...o]=r;if(!s)return null;let i={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:s,args:o,env:i}}function lG(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(r,s)=>{if(e.truncated)return;let o=n-e.bytes;if(o<=0){e.truncated=!0;return}let i=r.length<=o?r.toString("utf8"):r.subarray(0,o).toString("utf8");r.length>o&&(e.truncated=!0),e[s]+=i,e.bytes+=Math.min(r.length,o)};return{onStdout:r=>t(r,"stdout"),onStderr:r=>t(r,"stderr"),onExit:(r,s)=>{let o=[],i=(a,d)=>{let c=a.split(/\r?\n/);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(let l of c)o.push({text:l,style:d})};return e.stdout&&i(e.stdout,"stdout"),e.stderr&&i(e.stderr,"stderr"),e.truncated&&o.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),s?o.push({text:`[killed by ${s}]`,style:"error"}):typeof r=="number"&&r!==0&&o.push({text:`[exit ${r}]`,style:"error"}),o}}}function wg(n,e,t){let r=cG(n,e);if(r===null){t.notify("hotkey: empty command");return}let s=lG(t.maxOutputBytes??uG),o=t.spawnFn??iG,i;try{i=o(r.program,r.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...r.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}i.stdout?.on("data",s.onStdout),i.stderr?.on("data",s.onStderr),i.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),i.on("close",(a,d)=>{t.emitLines(s.onExit(a,d))})}var uG,Xv=q(()=>{"use strict";rt();uG=16*1024});function fG(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function pG(n,e,t){let r=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${r} via npm\u2026`:t.phase==="installed"?`${n} ${r} installed`:`${n} installing ${r} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let s=t.receivedBytes??0,o=t.totalBytes??0,i=(s/1e6).toFixed(1);if(o>0){let a=(o/1e6).toFixed(1),d=Math.min(100,Math.floor(s/o*100));return`${n} downloading ${r} ${i}/${a} MB (${d}%)`}return`${n} downloading ${r} ${i} MB`}return t.phase==="download_done"?`${n} downloaded ${r}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${r}\u2026`:t.phase==="installed"?`${n} ${r} installed`:e||n}function bg(n,e){let t=!1,r="",s=!1,o=n,i=a=>{t||a===3&&s||a===0&&!s||(s=a===3,fG(a))};return{write(a){t||(o=a,r=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"?i(3):a.phase==="installed"&&i(0);let c=pG(o,r,a);r=c,e.write(c)},finalize(){t||(t=!0,i(0),e.finalize())}}}function k_(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),B(n,"status-active",t))},finalize(){e||(e=!0,process.stdout.write(`
|
|
265
|
+
`))}}}var Zv=q(()=>{"use strict";Tn()});function tS(n="local"){let e={filters:{cwdOnly:!1,hostFilter:n==="all"?"__all":"__local",includeNonInteractive:!1}};return n!=="local"&&n!=="all"&&(e.pendingDefaultHost=n),e}function Va(){return on()?.id??"terminal"}function gG(){if(!qu())return S_;let n=[];for(let e of S_)n.push(e),e?.[0]==="*"&&n.push(["^t",Lm()?"go to selected session's tab (opening one if needed), or send the composer to a new one":"new tab: selected session, or send the composer to a new one"]);return n}async function nS(n,e){let t=()=>{we(ns),we(_a),we(Po),we($a),we(Oa),we(jc),we(qc),we(zc),we(Ma),we("\x1B>")};t();let r=e.prefs??tS();if(e.prefs===void 0&&e.currentSessionId!==void 0){let E=e.sessions.find(M=>M.sessionId===e.currentSessionId);(E?.importedFromMachine||E?.remote)&&(r.filters.hostFilter="__all")}if(r.pendingDefaultHost!==void 0){let E=kG(r.pendingDefaultHost,e.sessions);r.filters.hostFilter=E,E!=="__local"&&(r.pendingDefaultHost=void 0)}let s=e.cwd,o=vg(e.sessions,s),i,a=E=>{let M=E;return r.filters.cwdOnly&&(M=M.filter(U=>U.cwd===s)),r.filters.includeNonInteractive||(M=M.filter(U=>U.interactive===!0)),M=bG(M,r.filters.hostFilter),M},d=a(o),c={columns:e.config.tui.sessionColumns??mi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},l=d.map(E=>ds(E,Date.now())),u=Vs(l,c),f=1+d.length,p=0,m=0;if(e.currentSessionId!==void 0){let E=d.findIndex(M=>M.sessionId===e.currentSessionId);E>=0&&(p=E+1)}let h=!1,g="",w=120,b=!1,k=0,S="normal",I=null,x=!1,A="input",_=new Mo({history:[],collapsePastes:!1}),P=[],$=!1,F=0,J=0,Y=null,W=!1,Z=new Map,ne=Vs([],c),ve="",Ne=E=>Z.get(E)??null,Re=()=>{let E=Date.now(),M=new Map(d.map(se=>[se.sessionId,se])),U=[];Z=new Map;for(let se of P){let oe=M.get(se.sessionId);if(!oe)continue;let pe=ds(oe,E);Z.set(se.sessionId,pe),U.push(pe)}ne=Vs(U,c);let K=Math.max(20,xn(n)-kg);ve=ur(Co,ne,K,c).padEnd(K)},Ge=null,Ae=null,de=null,De=null,it=()=>{if(De!==null){let E=De;return{plain:E,render:()=>{B(n,"status-active",` ${E}`)}}}if(h){let E=d.length===0?"no matches":`${d.length} match${d.length===1?"":"es"}`;return{plain:`/${g}\u2589 ${E} \xB7 ^c clears`,render:()=>{B(n,"prompt-text",` /${g}`),B(n,"prompt-cursor"," "),B(n,"modal-hint",` ${E} \xB7 ^c clears`)}}}return de!==null?{plain:de,render:()=>{B(n,"modal-hint",` ${de}`)}}:null},Rt=!1,Me=new Mo({history:[]});if(e.initialPrompt&&Me.setBuffer(e.initialPrompt),e.initialAttachments)for(let E of e.initialAttachments)Me.addAttachment(E);let Kt=e.config.tui.promptHistoryMaxEntries;du(D.globalTuiHistoryFile()).then(E=>{let M=E.length>Kt?E.slice(E.length-Kt):E;Me.setHistory(M)}).catch(()=>{});let Ve=new el(n),ys=El(e.config),Ti=e.config.tui.selectionClipboard,mr=null,ce=!1,Je=null,xe="char",an=null,Xa=null,Lr=!1,Nr=1,Oo=null,Mg=500,sl=1,ws=/[A-Za-z0-9_:\-]/,Fo=Ys(n),Ut=xn(n),at=0,Za="",er=0,Wn=[],gn=1,ro=0,Ei=0,ol=0,ed="",so=[],$n=1,kf=0,Ye=[],yn=1,Pi=0,Mi=0,oo=0,_i=()=>{Fo=Ys(n),Ut=xn(n);let E=Math.max(10,Ut-kg-1);er=Math.max(10,Ut-v_);let M=Math.max(10,Ut-8),U=Me.state().attachments.length,K=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",se=Math.max(10,M-K.length);Za=yG(s,se)+K;let oe=Me.state();Wn=ms(oe.buffer,er);let pe=no(Wn,oe,uf);gn=pe.rendered,ro=pe.windowStart,Ei=pe.cursorVisualRow,ol=pe.cursorVisualCol;let nt=6+gn,Dt=Math.max(3,Fo-nt);at=Math.min(d.length,Dt),ed=ur(Co,u,E,c).padEnd(E),so=l.map(tn=>ur(tn,u,E,c).padEnd(E))},td=()=>{l=d.map(E=>ds(E,Date.now())),u=Vs(l,c),f=1+d.length,_i()},In=()=>{let E=a(o);h&&g.length>0?d=E.filter(M=>SG(M,g)):d=E,td(),h?(m=0,p=d.length>0?1:0):p>f-1&&(p=Math.max(0,f-1)),m+at>d.length&&(m=Math.max(0,d.length-at)),Dr()},bs=E=>{if(E!==void 0){let M=d.findIndex(U=>U.sessionId===E);if(M>=0){p=M+1,Dr();return}}p=d.length>0?1:0,m=0,Dr()},Dr=()=>{if(p===0)return;let E=p-1;E<m?m=E:E>=m+at?m=E-at+1:m+at>d.length&&(m=Math.max(0,d.length-at))},me=()=>Math.max(2,Ut-3),It=!1,tt=!0,Qt=!1,vf=[],jn=e.composerAgentId,qn=e.composerModel,il=!1,$i=()=>{let E=jn;if(!E)return"";let M=qn;return M?`${E}\u2022${M}`:E},Oi=null,Br=null,Xt=null,Fi=()=>{let E=me(),M=`\u2500 ${Za} `,U=$i(),K="";if(U.length>0){let Et=`\u2500 ${U} `;Et.length+M.length+1<=E&&(K=Et)}let se=Math.max(1,E-M.length-K.length),oe="\u2500".repeat(se),pe=(p===0||It)&&tt;if(Oi=M.length>0?{start:2,end:1+M.length}:null,K.length>0){let Et=1+M.length+se+1;Br={start:Et,end:Et+K.length-1}}else Br=null;let nt=pe?"box-border-focused":"box-border",Dt=pe?"box-border-focused-hover":"box-border-hover",tn=(Et,xs)=>{B(n,xs?Dt:nt,Et)};B(n,nt,"\u256D"),tn(M,Xt==="cwd"),B(n,nt,oe),K&&tn(K,Xt==="agent"),B(n,nt,"\u256E")},Lo=()=>{let E=me(),M="\u2500".repeat(E);(p===0||It)&&tt?B(n,"box-border-focused",`\u2570${M}\u256F`):B(n,"box-border",`\u2570${M}\u256F`)},nd=()=>{let E=it();if(E===null)return;let M=Math.max(0,xn(n)-2);if(E.plain.length>M){let U=E.plain.slice(0,Math.max(0,M-1))+"\u2026";B(n,"modal-hint",` ${U}`);return}E.render()},rd=E=>{let M=Wn[E];return M?(Me.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},sd=E=>{if(Je===null)return null;let M=Wn[E];if(!M)return null;let U=Je;if(M.bufferIdx<U.startRow||M.bufferIdx>U.endRow)return null;let K=M.bufferIdx===U.startRow?U.startCol:M.startCol,se=M.bufferIdx===U.endRow?U.endCol:M.endCol,oe=Math.max(K,M.startCol),pe=Math.min(se,M.endCol);return pe<=oe?null:{start:oe-M.startCol,end:pe-M.startCol}},io=E=>{let M=me(),U=rd(E),K=Math.max(0,M-1-U.length),se=" ".repeat(K),oe=sd(E),pe=()=>{if(oe===null){B(n,"content",` ${U}${se}`);return}B(n,"content"," "),oe.start>0&&B(n,"content",U.slice(0,oe.start)),B(n,"selection-highlight",U.slice(oe.start,oe.end)),oe.end<U.length&&B(n,"content",U.slice(oe.end)),B(n,"content",se)};(p===0||It)&&tt?(B(n,"box-border-focused","\u2502"),pe(),B(n,"box-border-focused","\u2502")):(B(n,"box-border","\u2502"),pe(),B(n,"box-border","\u2502"))},No=E=>{let M=so[E]??"",U=d[E],K=U&&U.priority&&U.priority>0?"* ":" ";p===E+1&&!It&&tt?B(n,"list-selected",`${K}${M}`):B(n,"content",`${K}${M}`)},Hr=()=>{let E=m,M=Math.max(0,d.length-m-at),U=[];return r.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),r.filters.hostFilter!=="__all"&&U.push({kind:"host",text:vG(r.filters.hostFilter)}),r.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),E>0&&U.push({kind:"plain",text:`\u2191 ${E} above`}),M>0&&U.push({kind:"plain",text:`\u2193 ${M} below`}),U},od=()=>{let E=Hr();return E.length===0?"":` ${E.map(M=>M.text).join(" \xB7 ")}`},ao=E=>st(E),Sf=()=>{let E=I?`${I.sessionId}|${I.status}`:"";return["ind",S,E,Ge?`${Ge.text}${Ge.cursor}`:"",Ae??"",h?`1|${g}|${d.length}`:"0",od(),Wi?"h1":"h0",Uo?"ho1":"ho0"].join("")},Qe=()=>{pt(()=>{Ve.paintRow(Be(),Sf(),()=>{let E=()=>{bn=null,Ss=null};if(S==="confirm-kill"&&I)E(),B(n,"prompt-text",` kill ${ao(I.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&I)E(),I.status==="warm"?B(n,"prompt-destructive",` kill + delete ${ao(I.sessionId)}? [y/N]`):B(n,"prompt-destructive",` delete ${ao(I.sessionId)}? [y/N]`);else if(S==="busy"&&I)E(),B(n,"modal-status",` working on ${ao(I.sessionId)}\u2026`);else if(S==="rename"&&I&&Ge){E();let M=Ge.text,U=Ge.cursor;B(n,"prompt-text"," title: "),B(n,"prompt-text",M.slice(0,U)),U<M.length?(B(n,"prompt-cursor",M[U]??" "),B(n,"prompt-text",M.slice(U+1))):B(n,"prompt-cursor"," "),B(n,"modal-hint"," Enter saves \xB7 Esc cancels")}else if(Ae!==null)E(),B(n,"modal-status",` ${Ae}`);else{let M=Hr(),U=od(),K="Esc \xB7 Go Back",se=K.length,oe=5,pe=U.length,nt=Math.max(1,Ut-pe-se-oe);if(Ss=null,M.length>0){B(n,"modal-hint"," ");let Dt=3;for(let tn=0;tn<M.length;tn++){let Et=M[tn];tn>0&&(B(n,"modal-hint"," \xB7 "),Dt+=3),Et.kind==="host"?(Ss={start:Dt,end:Dt+Et.text.length-1},Uo?B(n,"content",Et.text):B(n,"modal-hint",Et.text)):B(n,"modal-hint",Et.text),Dt+=Et.text.length}}B(n,"modal-hint"," ".repeat(nt)),Wi?B(n,"content",K):B(n,"modal-hint",K),bn={start:Ut-oe-se+1,end:Ut-oe}}})})},Li=E=>$n+1+E,Zt=()=>$n+gn+1,en=()=>$n+gn+3,co=E=>en()+1+(E-m),Be=()=>en()+1+at,zn=()=>{let E=Ei-ro;if(E<0||E>=gn)return;let M=3+ol;n.moveTo(M,Li(E))},Ni=(E,M)=>{let U=M-($n+1);if(U<0||U>=gn)return null;let K=Wn[ro+U];if(!K)return null;let se=Math.max(0,Math.min(K.endCol-K.startCol,E-3));return{row:K.bufferIdx,col:K.startCol+se}},Ur=()=>{Je!==null&&(Je=null,Cn())},tr=(E,M)=>{let U=E.row<M.row||E.row===M.row&&E.col<=M.col,K=U?E:M,se=U?M:E;if(K.row===se.row&&K.col===se.col){Ur();return}let oe={startRow:K.row,startCol:K.col,endRow:se.row,endCol:se.col},pe=Je;pe&&pe.startRow===oe.startRow&&pe.startCol===oe.startCol&&pe.endRow===oe.endRow&&pe.endCol===oe.endCol||(Je=oe,Cn())},id=()=>{if(Je===null)return"";let{startRow:E,startCol:M,endRow:U,endCol:K}=Je,se=Me.state().buffer;if(E===U)return(se[E]??"").slice(M,K);let oe=[(se[E]??"").slice(M)];for(let pe=E+1;pe<U;pe++)oe.push(se[pe]??"");return oe.push((se[U]??"").slice(0,K)),oe.join(`
|
|
266
|
+
`)},ad=()=>{let E=id();E.length!==0&&Zc(E,{target:Ti}).then(M=>{let U=E.length;de=M.ok?`copied ${U} char${U===1?"":"s"} to clipboard`:`clipboard copy failed: ${M.reason}`,Gn()},M=>{de=`clipboard copy failed: ${M.message}`,Gn()})},R=E=>{let M=Me.state().buffer[E.row]??"";if(M.length===0)return null;let U=Math.max(0,Math.min(M.length-1,E.col));if(!ws.test(M[U]))return null;let K=U;for(;K>0&&ws.test(M[K-1]);)K--;let se=U+1;for(;se<M.length&&ws.test(M[se]);)se++;return{start:K,end:se}},xf=E=>{let M=Me.state().buffer[E]??"";tr({row:E,col:0},{row:E,col:M.length})},_g=E=>{let M=an;if(M===null)return;let U=E.row<M.row||E.row===M.row&&E.col<M.start,K=E.row>M.row||E.row===M.row&&E.col>M.end,se={row:M.row,col:M.start},oe={row:M.row,col:M.end};if(U){let pe=R(E);se=pe!==null?{row:E.row,col:pe.start}:E}else if(K){let pe=R(E);oe=pe!==null?{row:E.row,col:pe.end}:E}tr(se,oe)},If=E=>{let M=Xa;if(M===null)return;let U=Math.min(M,E.row),K=Math.max(M,E.row),se=Me.state().buffer[K]??"";tr({row:U,col:0},{row:K,col:se.length})},Cf=E=>{if(!ys)return;let M=Ni(E.x,E.y);if(M===null)return;mr=M,ce=!1,Lr=!1,Nr=1,xe="char",an=null,Xa=null,Ur();let U=Date.now(),K=Oo,se=K!==null&&U-K.t<=Mg&&Math.abs(E.x-K.x)<=sl&&Math.abs(E.y-K.y)<=sl&&K.row!==null&&K.row===M.row;if(se&&K.count===2&&E.x===K.x&&E.y===K.y){Nr=3,xf(M.row),xe="line",Xa=M.row,Lr=!0;return}if(se&&K.count===1){Nr=2;let nt=R(M);nt!==null&&(tr({row:M.row,col:nt.start},{row:M.row,col:nt.end}),Lr=!0,xe="word",an={row:M.row,start:nt.start,end:nt.end})}},dd=E=>{if(mr===null)return;let M=Math.max(1,Math.min(Ut,E.x)),U=Math.max($n+1,Math.min($n+gn,E.y)),K=Ni(M,U);K!==null&&(ce=!0,xe==="word"?_g(K):xe==="line"?If(K):tr(mr,K))},Do=E=>{let M=ce,U=Lr;if(mr=null,ce=!1,Lr=!1,E!==null){let K=Ni(E.x,E.y);Oo={x:E.x,y:E.y,t:Date.now(),count:Nr,row:K?.row??null}}if(Nr=1,M||U){ad();return}Ur()},gr=()=>tt?p===0?"f":It?"h":"u":"x",Rf=()=>`ct|${gr()}|${me()}|${Za}|${$i()}|${Xt??""}`,al=()=>`cb|${gr()}|${me()}`,lo=()=>De!==null?`cs|i|${De}`:h?`cs|s|${g}|${d.length}`:de!==null?`cs|h|${de}`:"blank",cd=E=>{let M=sd(E),U=M===null?"":`${M.start}:${M.end}`;return`cbb|${gr()}|${me()}|${rd(E)}|${U}`},Af=()=>`h|${ed}`,ld=E=>{let M=d[E],U=M&&M.priority&&M.priority>0?"* ":" ",K=so[E]??"";return`sr|${p===E+1&&!It&&tt?"1":"0"}|${U}${K}`},At=()=>{pt(()=>{n.hideCursor(),_i(),Dr(),$n=1,Ve.ensureSize(Ut,Fo),Ve.paintRow($n,Rf(),()=>{Fi()});for(let E=0;E<gn;E++){let M=ro+E;Ve.paintRow(Li(E),cd(M),()=>{io(M)})}Ve.paintRow(Zt(),al(),()=>{Lo()}),Ve.paintRow(Zt()+1,lo(),()=>nd()),Ve.paintRow(en(),Af(),()=>{B(n,"list-header",` ${ed}`)});for(let E=0;E<at;E++){let M=m+E,U=en()+1+E;M<d.length?Ve.paintRow(U,ld(M),()=>{No(M)}):Ve.paintRow(U,"blank",()=>{})}Qe();for(let E=Be()+1;E<=Fo;E++)Ve.paintRow(E,"blank",()=>{});p===0&&(zn(),n.hideCursor(!1))})},Tf=()=>{Ve.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),At()},Ef=()=>{pt(()=>{n.hideCursor(),Ve.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),B(n,"modal-title"," Picker hotkeys"),n.noFormat(`
|
|
267
267
|
|
|
268
268
|
`);for(let E of gG()){if(E===null){n(`
|
|
269
269
|
`);continue}let[M,U]=E;B(n,"modal-key",` ${M.padEnd(mG)}`),B(n,"content",U),n.noFormat(`
|
|
270
270
|
`)}n(`
|
|
271
271
|
`),B(n,"modal-hint"," press any key to dismiss"),n.noFormat(`
|
|
272
|
-
`)})},$g=()=>yn+4,Kn=()=>yn+5,ud=2,Ct=0,Ot=()=>{Fo=
|
|
273
|
-
`);pt(()=>{n.hideCursor(),Ve.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),dl(E);for(let K=0;K<yn;K++)n.moveTo(1,2+K),fd(Pi+K,E);n.moveTo(1,2+yn),pd(E);let U=P.length;if(U===0)n.moveTo(1,Kn()),W||(Y===null&&M.trim().length===0?(B(n,"modal-hint"," type a query in the box above, then press Enter"),n.eraseLineAfter()):Y===null&&(B(n,"modal-status"," no matches"),n.eraseLineAfter())),n.moveTo(1,Kn()+1),Wr();else{Bo(),n.moveTo(1,$g()),Og();let K=Ot(),se=A!=="input";for(let oe=0;oe<K;oe++){let pe=Ct+oe;n.moveTo(1,Kn()+oe*2),pe<U?ul(pe,se&&pe===F):n.eraseLineAfter(),n.moveTo(1,Kn()+oe*2+1),pe<U?Ho(pe,se&&pe===F):n.eraseLineAfter()}n.moveTo(1,Kn()+K*2),Wr()}E&&(n.moveTo(
|
|
274
|
-
`),gd=E=>{let M=yn;_.feed({type:"paste",text:E}),ks(),yn!==M?vs():cl()},jr=async()=>{let E=md().trim();if(E.length!==0){if(d.length===0){Y="no sessions in view to search",vs();return}W=!0,Y=null,vs();try{let M=await LT(e.target,E,{sessionIds:d.map(U=>U.sessionId),snippetWidth:Mf()});P=M.results,Re(),$=M.truncated,F=0,J=0,Ct=0,A=M.results.length>0?"results":"input",ks()}catch(M){Y=`search failed: ${M.message}`}finally{W=!1,vs()}}},qr=()=>{let E=md();if(E.trim().length===0&&P.length===0){delete r.lastFind;return}r.lastFind={query:E,results:P,truncated:$,selectedIdx:F,snippetIdx:J,scrollOffset:Ct}},zr=()=>{},wn=()=>{pt(()=>{let E=p===0;E&&n.hideCursor(),Ve.paintRow($n,Rf(),()=>{Fi()}),Ve.paintRow(Zt(),al(),()=>{Lo()});for(let M=0;M<gn;M++){let U=
|
|
275
|
-
`);Kr="";let oe=M.slice(K+Fu.length);if(x)A==="input"&&!W&&gd(se);else if(p===0&&!h){let pe=Me.feed({type:"paste",text:se});for(let Et of pe)Et.type==="attachment-request"&&Fn();let nt=Me.state(),Dt=ms(nt.buffer,er);
|
|
272
|
+
`)})},$g=()=>yn+4,Kn=()=>yn+5,ud=2,Ct=0,Ot=()=>{Fo=Ys(n);let E=Math.max(2,Fo-(yn+4)-ud);return Math.max(1,Math.floor(E/2))},Bo=()=>{let E=Ot();F<Ct?Ct=F:F>=Ct+E&&(Ct=F-E+1),Ct+E>P.length&&(Ct=Math.max(0,P.length-E)),Ct<0&&(Ct=0)},dl=E=>{Ut=xn(n);let M=Math.max(2,Ut-3),U="\u2500 Find sessions ",K="\u2500".repeat(Math.max(1,M-U.length));E?B(n,"box-border-focused",`\u256D${U}${K}\u256E`):B(n,"box-border",`\u256D${U}${K}\u256E`),n.styleReset()},ks=()=>{Ut=xn(n),kf=Math.max(10,Ut-v_);let E=_.state();Ye=ms(E.buffer,kf);let M=no(Ye,E,hG);yn=M.rendered,Pi=M.windowStart,Mi=M.cursorVisualRow,oo=M.cursorVisualCol},fd=(E,M)=>{Ut=xn(n);let U=Math.max(2,Ut-3),K=Ye[E],se="";K&&(se=(_.state().buffer[K.bufferIdx]??"").slice(K.startCol,K.endCol));let oe=Math.max(0,U-1-se.length),pe=" ".repeat(oe);M?(B(n,"box-border-focused","\u2502"),B(n,"content",` ${se}${pe}`),B(n,"box-border-focused","\u2502")):(B(n,"box-border","\u2502"),B(n,"content",` ${se}${pe}`),B(n,"box-border","\u2502")),n.styleReset()},pd=E=>{Ut=xn(n);let M=Math.max(2,Ut-3),U="\u2500".repeat(M);E?B(n,"box-border-focused",`\u2570${U}\u256F`):B(n,"box-border",`\u2570${U}\u256F`),n.styleReset()},uo=()=>3+oo,Wt=()=>2+(Mi-Pi),Di=()=>{let E=A==="input";pt(()=>{E&&n.hideCursor(),n.moveTo(1,1),dl(E);for(let M=0;M<yn;M++)n.moveTo(1,2+M),fd(Pi+M,E);n.moveTo(1,2+yn),pd(E),E&&(n.moveTo(uo(),Wt()),n.hideCursor(!1))})},cl=()=>{pt(()=>{n.hideCursor();for(let E=0;E<yn;E++)n.moveTo(1,2+E),fd(Pi+E,!0);n.moveTo(uo(),Wt()),n.hideCursor(!1)})},Pf=4,ll=16,Mf=()=>Math.max(24,xn(n)-1-Pf-ll),hd=(E,M)=>{let U=P[E];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let K=xn(n),se=Math.max(20,K-kg),oe=Ne(U.sessionId),pe=oe!==null?ur(oe,ne,se,c).padEnd(se):`${st(U.sessionId)} ${U.status==="warm"?"warm":"cold"} ${Eu(U.title??V(U.cwd),Math.max(5,se-20))}`.padEnd(se),nt=M?J:0,Dt=U.snippets[nt],tn=U.snippets.length>1?`[${nt+1}/${U.snippets.length}] `:U.totalMatches>U.snippets.length?`[${U.snippets.length} of ${U.totalMatches}] `:"",Et=Dt?.toolName?`${Dt.toolName} `:"",xs=`${tn}${Et}`,Sd=Math.max(10,K-1-Pf-xs.length),ji=Dt?Eu(Dt.text,Sd):"",qi=Dt?` ${xs}${ji}`:" (no snippet)";return{rowBudget:se,line1:pe,line2:qi.padEnd(se+kg),focusedRow:M}},Og=()=>{B(n,"list-header",` ${ve}`),n.styleReset()},ul=(E,M)=>{let{line1:U,focusedRow:K}=hd(E,M);K?B(n,"list-selected",`\u276F ${U}`):B(n,"content",` ${U}`),n.styleReset()},Ho=(E,M)=>{let{line2:U}=hd(E,M);B(n,"list-description",U),n.styleReset()},Wr=()=>{if(W)B(n,"modal-status"," searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(Y!==null)B(n,"modal-error",` ${Y}`),n.styleReset(),n.eraseLineAfter();else if(A==="input")P.length>0?B(n,"modal-hint"," Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):B(n,"modal-hint"," Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let E=P.length,M=$?" \xB7 truncated":"",U=E>0?` ${E} ${E===1?"session":"sessions"} match${M} \xB7 `:" ";B(n,"modal-hint",`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 i info \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},vs=()=>{ks();let E=A==="input",M=_.state().buffer.join(`
|
|
273
|
+
`);pt(()=>{n.hideCursor(),Ve.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),dl(E);for(let K=0;K<yn;K++)n.moveTo(1,2+K),fd(Pi+K,E);n.moveTo(1,2+yn),pd(E);let U=P.length;if(U===0)n.moveTo(1,Kn()),W||(Y===null&&M.trim().length===0?(B(n,"modal-hint"," type a query in the box above, then press Enter"),n.eraseLineAfter()):Y===null&&(B(n,"modal-status"," no matches"),n.eraseLineAfter())),n.moveTo(1,Kn()+1),Wr();else{Bo(),n.moveTo(1,$g()),Og();let K=Ot(),se=A!=="input";for(let oe=0;oe<K;oe++){let pe=Ct+oe;n.moveTo(1,Kn()+oe*2),pe<U?ul(pe,se&&pe===F):n.eraseLineAfter(),n.moveTo(1,Kn()+oe*2+1),pe<U?Ho(pe,se&&pe===F):n.eraseLineAfter()}n.moveTo(1,Kn()+K*2),Wr()}E&&(n.moveTo(uo(),Wt()),n.hideCursor(!1))})},Bi=(E,M)=>{let U=E-Ct;U<0||U>=Ot()||pt(()=>{n.moveTo(1,Kn()+U*2),ul(E,M),n.moveTo(1,Kn()+U*2+1),Ho(E,M)})},fo=()=>{pt(()=>{n.moveTo(1,Kn()+Ot()*2),Wr()})},Hi=()=>{pt(()=>{let E=Ot(),M=P.length,U=A!=="input";for(let K=0;K<E;K++){let se=Ct+K;n.moveTo(1,Kn()+K*2),se<M?ul(se,U&&se===F):n.eraseLineAfter(),n.moveTo(1,Kn()+K*2+1),se<M?Ho(se,U&&se===F):n.eraseLineAfter()}n.moveTo(1,Kn()+E*2),Wr()})},md=()=>_.state().buffer.join(`
|
|
274
|
+
`),gd=E=>{let M=yn;_.feed({type:"paste",text:E}),ks(),yn!==M?vs():cl()},jr=async()=>{let E=md().trim();if(E.length!==0){if(d.length===0){Y="no sessions in view to search",vs();return}W=!0,Y=null,vs();try{let M=await LT(e.target,E,{sessionIds:d.map(U=>U.sessionId),snippetWidth:Mf()});P=M.results,Re(),$=M.truncated,F=0,J=0,Ct=0,A=M.results.length>0?"results":"input",ks()}catch(M){Y=`search failed: ${M.message}`}finally{W=!1,vs()}}},qr=()=>{let E=md();if(E.trim().length===0&&P.length===0){delete r.lastFind;return}r.lastFind={query:E,results:P,truncated:$,selectedIdx:F,snippetIdx:J,scrollOffset:Ct}},zr=()=>{},wn=()=>{pt(()=>{let E=p===0;E&&n.hideCursor(),Ve.paintRow($n,Rf(),()=>{Fi()}),Ve.paintRow(Zt(),al(),()=>{Lo()});for(let M=0;M<gn;M++){let U=ro+M;Ve.paintRow(Li(M),cd(U),()=>{io(U)})}E&&(zn(),n.hideCursor(!1))})},Gn=()=>{pt(()=>{Ve.paintRow(Zt()+1,lo(),()=>nd())})},On=()=>{de!==null&&(de=null,Gn())},yd=E=>{let M=e.config.tui.hotkeys[E];return M?(wg(M,{sessionId:"",cwd:s,agentId:jn??"",baseUrl:e.target.baseUrl,tokenFile:D.authToken()},{notify:U=>{de=U,Gn()},cwd:s,emitLines:U=>{if(U.length===0)return;let K=U[0].text;de=U.length>1?`${K} (+${U.length-1} more)`:K,Gn()}}),!0):!1},Cn=()=>{pt(()=>{let E=Me.state();Wn=ms(E.buffer,er);let M=no(Wn,E,uf);ro=M.windowStart,Ei=M.cursorVisualRow,ol=M.cursorVisualCol;let U=p===0;U&&n.hideCursor();for(let K=0;K<gn;K++){let se=ro+K;Ve.paintRow(Li(K),cd(se),()=>{io(se)})}U&&(zn(),n.hideCursor(!1))})},Fn=async()=>{let E=await jm();if(!E.ok){Ae=E.reason,Qe();return}if(E.kind!=="image"){let M=Me.state(),U=[...M.buffer],K=M.row,se=M.col;Me.feed({type:"paste",text:E.text});let oe=Me.state();if(U.length!==oe.buffer.length||K!==oe.row||se!==oe.col||!U.every((nt,Dt)=>nt===oe.buffer[Dt])){let nt=ms(oe.buffer,er);no(nt,oe,uf).rendered!==gn?At():Cn()}return}Me.addAttachment(E.attachment),Ae=`attached ${E.attachment.name??"image"}`,At()},_f=async()=>{let E=await Gm(Me.expandedText(),{suspend:()=>fl?.(),resume:()=>kd?.(),notify:M=>{Ae=M,Qe()}});E!==null&&(Me.setBuffer(E,Me.state().attachments),At())},$f=E=>{E<m||E>=m+at||pt(()=>{Ve.paintRow(co(E),ld(E),()=>{No(E)})})},yr=()=>{pt(()=>{for(let E=0;E<at;E++){let M=en()+1+E,U=m+E;U<d.length?Ve.paintRow(M,ld(U),()=>{No(U)}):Ve.paintRow(M,"blank",()=>{})}Qe()})},Of=()=>{pt(()=>{Ve.paintRow(en(),Af(),()=>{B(n,"list-header",` ${ed}`)});for(let E=0;E<at;E++){let M=en()+1+E,U=m+E;U<d.length?Ve.paintRow(M,ld(U),()=>{No(U)}):Ve.paintRow(M,"blank",()=>{})}Qe(),p===0&&(zn(),n.hideCursor(!1))})},po=!1,Kr="",wd=0,Fg=200,ho=null,Ui=!1,bn=null,Wi=!1,Ss=null,Uo=!1,nr=null,bd=null,fl=null,kd=null,pl=!1,hl=null,vd=E=>{let M=E.toString("binary");if(M.includes("\x1B[I")||M.includes("\x1B[O")){for(;;){let K=M.indexOf("\x1B[I"),se=M.indexOf("\x1B[O"),oe=K===-1?se:se===-1?K:Math.min(K,se);if(oe===-1)break;let pe=tt;tt=oe===K,tt&&(wd=Date.now()),pe!==tt&&!Qt&&vf.length<=1&&pt(()=>{wn(),yr()}),M=M.slice(0,oe)+M.slice(oe+"\x1B[I".length)}if(M.length===0)return}if(!po&&M===""&&bd){bd();return}if(!po&&(M===""||M==="\x1B_"||M==="\x1B")){hl?.(M);return}if(po){let K=M.indexOf(Fu);if(K===-1){Kr+=M;return}Kr+=M.slice(0,K),po=!1;let se=Buffer.from(Kr,"binary").toString("utf-8").replace(/\r\n?/g,`
|
|
275
|
+
`);Kr="";let oe=M.slice(K+Fu.length);if(x)A==="input"&&!W&&gd(se);else if(p===0&&!h){let pe=Me.feed({type:"paste",text:se});for(let Et of pe)Et.type==="attachment-request"&&Fn();let nt=Me.state(),Dt=ms(nt.buffer,er);no(Dt,nt,uf).rendered!==gn?At():Cn()}oe.length>0&&nr&&nr(Buffer.from(oe,"binary"));return}let U=M.indexOf(Wc);if(U===-1){nr?.(E);return}U>0&&nr?.(Buffer.from(M.slice(0,U),"binary")),M=M.slice(U+Wc.length),po=!0,M.length>0&&vd(Buffer.from(M,"binary"))};return At(),await new Promise(E=>{let M=null,U=!1,K=null,se=!1,oe=vf,pe=L=>{oe.push(L)},nt=()=>{oe.pop(),Qt||oe[oe.length-1]?.onResize()},Dt={push:pe,pop:nt},tn=()=>{let L={kind:"new",cwd:s},ee=Me.state().attachments;return ee.length>0&&(L.attachments=[...ee]),jn&&(L.agentId=jn),qn&&(L.model=qn),il&&(L.agentExplicit=!0),L},Et=async()=>{if(!(il||!e.onCwdChange))try{let L=await e.onCwdChange(s);L.agentId!==void 0&&(jn=L.agentId,qn=L.model),L.notice!==void 0&&(Ae=L.notice)}catch{}},xs=async()=>{Cs(),Ve.clearCache(),pe({onKey:()=>{},onResize:()=>{}});let ee;try{ee=await Ja(n,void 0,{defaultCwd:s,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{nt(),wr()}if(ee.kind==="ok"&&ee.path!==s){s=ee.path;let fe=p>0?d[p-1]?.sessionId:void 0;o=vg(o,s),In(),bs(fe),await Et()}Qt||At()},Sd=async()=>{let L=e.availableAgents;if(!L||L.length===0)return;Cs(),Ve.clearCache(),pe({onKey:()=>{},onResize:()=>{}});let fe;try{fe=await Yu(n,L,jn,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{nt(),wr()}if(fe.kind==="select"){jn=fe.agentId,il=!0;let Q=L.find(Se=>Se.id===fe.agentId);if(qn=xr(e.config.sessionDefaults,{id:fe.agentId,extendsChain:Q?.extendsChain})?.value.model,e.onComposerAgentChange?.(jn,qn),fe.persist)try{await Jo(fe.agentId)}catch{}}Qt||At()};zr=()=>{qr(),_=new Mo({history:[],collapsePastes:!1}),P=[],$=!1,F=0,J=0,Ct=0,Y=null,W=!1,A="input",x=!1,nt()};let ji=new wi(vm),qi=(L,ee,fe)=>{if(yl(),Je!==null&&Ur(),fe?.isCharacter){ji.clear(),oe[oe.length-1]?.onKey(L,ee,fe);return}let Q=ji.feed(L);switch(Q.kind){case"pass":oe[oe.length-1]?.onKey(Q.token,ee,fe);return;case"armed":case"aborted":return}},ml=()=>{Qt||oe[oe.length-1]?.onResize()};hl=L=>{Qt||(ji.clear(),oe[oe.length-1]?.onKey(L,null,{}))};let gl=!1,Ff=()=>{if(gl)return;gl=!0,oe.length=0,M&&(clearInterval(M),M=null),K&&(K.abort(),K=null,U=!1),n.off("key",qi),n.off("mouse",Yr),n.off("resize",ml),we(Po),we(Nu);let L=n;L.stdin&&nr&&(L.stdin.removeListener("data",vd),L.stdin.on("data",nr),nr=null),po=!1,Kr="",n.grabInput(!1),ge({src:"grab",site:"picker.detachInput",on:!1})},rr=()=>{Qt||(Qt=!0,Ff(),n.hideCursor(!1),n.moveTo(1,Be()+1),n(`
|
|
276
276
|
`))},xd=()=>{if(Qt||oe.length>1||S!=="normal"||h||se||pl)return;U&&K&&(K.abort(),K=null,U=!1);let L=p>0?d[p-1]?.sessionId:void 0;U=!0;let ee=new AbortController;K=ee,Ki(L,{silent:!0,signal:ee.signal}).finally(()=>{K===ee&&(K=null),U=!1})},yl=()=>{Qt||(M&&clearInterval(M),M=setInterval(xd,3e3))},Gr=()=>(Ff(),bg("",{write(ee){De=ee,Gn()},finalize(){De=null,rr()}})),Wo=()=>(rr(),E({kind:Rt?"exit":"abort"}),!0),zi=()=>{let L=l.map(ee=>`${ee.session}|${ee.upstream}|${ee.host}|${ee.state}|${ee.agent}|${ee.model}|${ee.age}|${ee.title}|${ee.cwd}|${ee.cost}`).join(`
|
|
277
277
|
`);return`${p}:${m}:${Ae??""}
|
|
278
|
-
${L}`},Lg=(L,ee)=>{o=vg(_T(o,L,ee),s),i=L.cursor},Id=0,Ng=async()=>{if(!e.target.isLocal)return!1;try{let L=await rn(await He());return L.baseUrl===e.target.baseUrl&&L.wsUrl===e.target.wsUrl&&L.token===e.target.token?!1:(e.target.baseUrl=L.baseUrl,e.target.wsUrl=L.wsUrl,e.target.display=L.display,e.target.token=L.token,!0)}catch{return!1}},Ki=async(L,ee={})=>{let fe=async()=>{let Q=ee.silent?zi():"",Se=f,ze=i!==void 0,Ft=await Db(e.target,{includeNonInteractive:!0,since:i,signal:ee.signal}),Mt=L??(p>0?d[p-1]?.sessionId:void 0);if(Lg(Ft,ze),In(),Mt!==void 0){let dn=d.findIndex(ae=>ae.sessionId===Mt);dn>=0?p=dn+1:p=0}p>f-1&&(p=Math.max(0,f-1)),m+at>d.length&&(m=Math.max(0,d.length-at)),Dr(),!(ee.silent&&zi()===Q)&&(f===Se?Of():At())};try{await fe(),Id=0}catch(Q){let Se=Q;if(await Ng())try{await fe(),Id=0;return}catch(ze){Se=ze}if(ee.silent){Id+=1,Id>=3&&(Ae=`refresh failing: ${Se.message}`,At());return}Ae=`refresh failed: ${Se.message}`,At()}},Cd=async L=>{if(!I)return;let ee=I;S="busy",Qe();try{await Au(e.target,ee.sessionId,L),S="normal",I=null,Ge=null,await Ki(ee.sessionId)}catch(fe){S="normal",I=null,Ge=null,Ae=`rename failed: ${fe.message}`,Qe()}},Ln=async L=>{try{await FT(e.target,L.sessionId),Ae="title regen queued (press r to refresh)",Qe()}catch(ee){Ae=`regen failed: ${ee.message}`,Qe()}},Jn=async L=>{let fe=(L.priority&&L.priority>0?L.priority:0)>0?null:1,Q=fe??0;for(let ze of o)ze.sessionId===L.sessionId&&(ze.priority=Q>0?Q:void 0);let Se=L.sessionId;o=vg(o,s),In(),Se!==void 0&&bs(Se),At(),Ae=Q>0?"priority: high":"priority: normal",Qe();try{await OT(e.target,L.sessionId,fe)}catch(ze){Ae=`priority failed: ${ze.message}`,Qe()}},Is=async()=>{if(se)return;se=!0;let L=p>0?d[p-1]?.sessionId:void 0;Ae="syncing agents\u2026",Qe();try{let{synced:ee,skipped:fe,agents:Q}=await $T(e.target);await Ki(L),Ae=`synced ${ee} new (${fe} known) from ${Q} agent${Q===1?"":"s"}`,Qe()}catch(ee){Ae=`sync failed: ${ee.message}`,Qe()}finally{se=!1}},Jr=!1,Vr=async L=>{if(Jr)return;Jr=!0;let ee=L.title?.trim()||st(L.sessionId);Ae=Lm()?`showing ${ee} in ${Va()}\u2026`:`opening ${ee} in a new ${Va()} tab\u2026`,Qe();try{let fe=await zu({kind:"attach",sessionId:L.sessionId,title:L.title,cwd:qa(L)!==void 0?void 0:L.cwd});Ae=fe.outcome==="revealed"?`jumped to ${ee} \u2014 already open in ${Va()}`:fe.outcome==="opened"?`opened ${ee} in a new ${Va()} tab`:`new tab failed: ${fe.error??"unknown error"}`}catch(fe){Ae=`new tab failed: ${fe.message}`}finally{Jr=!1,Qe()}},
|
|
279
|
-
`)}catch(X){if(ae.signal.aborted)return;fe=`failed to load info: ${X.message}`}finally{Q=!1,!Qt&&oe[oe.length-1]===Te&&dn()}})()},wl=()=>{if(d.length===0){Ae="no sessions to search",Qe();return}_=new Mo({history:[],collapsePastes:!1});let L=r.lastFind,ee=new Set(d.map(ae=>ae.sessionId)),fe=L?L.results.filter(ae=>ee.has(ae.sessionId)):[];L&&L.query.length>0&&_.setBuffer(L.query),P=fe,Re(),$=L?.truncated??!1,F=Math.min(Math.max(0,L?.selectedIdx??0),Math.max(0,fe.length-1)),J=0,Ct=0,Y=null,W=!1,A=fe.length>0?"results":"input",x=!0,ks(),Bo(),vs();let Q=()=>{let ae=P[F];if(!ae)return;let lt=d.find(X=>X.sessionId===ae.sessionId),We=!!lt?.importedFromMachine&&!lt.remote&&!lt.upstreamSessionId,Te=ae.snippets[J]?.recordedAt??ae.snippets[0]?.recordedAt;if(We){qr(),rr();let X={kind:"attach",sessionId:ae.sessionId};lt.agentId!==void 0&&(X.agentId=lt.agentId),Te!==void 0&&(X.jumpToRecordedAt=Te),E(X);return}(async()=>{let X=await h_(n,{sessionId:ae.sessionId,title:ae.title,cwd:ae.cwd},Dt);if(X==="cancel"){qr(),rr(),E({kind:"abort"});return}if(X==="back")return;qr(),rr();let $e={kind:"attach",sessionId:ae.sessionId,readonly:X==="view"};lt?.agentId!==void 0&&($e.agentId=lt.agentId),Te!==void 0&&($e.jumpToRecordedAt=Te),E($e)})()},Se=ae=>{if(ae<0||ae>=P.length||ae===F)return;let lt=F,We=Ct;F=ae,J=0,Bo(),Ct!==We?Hi():pt(()=>{Bi(lt,!1),Bi(F,!0)}),uo()},ze=(ae,lt,We)=>{if(A==="input"){if(W)return;if(ae==="ESCAPE"||ae==="CTRL_C"){zr();return}if(ae==="ENTER"||ae==="KP_ENTER"){if(md().trim().length===0)return;jr();return}if((ae==="DOWN"||ae==="TAB"||ae==="CTRL_N")&&P.length>0){A="results",F=0,J=0,pt(()=>{Di(),Bi(0,!0),uo(),n.hideCursor()});return}let Te=_.state(),X=[...Te.buffer],$e=Te.row,_e=Te.col,vt=null;if(ae==="")vt={type:"key",name:"ctrl-underscore"};else if(ae==="\x1B_"||ae==="\x1B")vt={type:"key",name:"alt-underscore"};else if(We?.isCharacter)vt={type:"char",ch:ae};else{let cn=pg(ae);cn!==null&&(vt={type:"key",name:cn})}if(vt===null){n.moveTo(lo(),Wt());return}_.feed(vt);let St=_.state();if(X.length===St.buffer.length&&X.every((cn,Rs)=>cn===St.buffer[Rs])&&$e===St.row&&_e===St.col){n.moveTo(lo(),Wt());return}let Qr=yn;ks(),yn!==Qr?vs():cl();return}if(A==="results"){if(ae==="ESCAPE"||ae==="CTRL_C"){zr();return}if(ae==="CTRL_F"){A="input",Hi(),uo(),Di();return}if(ae==="ENTER"||ae==="KP_ENTER"){Q();return}if(We?.isCharacter&&ae==="i"){let $e=P[F];if(!$e)return;let _e=d.find(vt=>vt.sessionId===$e.sessionId);if(!_e)return;Rd(_e);return}let Te=$e=>{let _e=P[F];!_e||_e.snippets.length<=1||(J=(J+$e+_e.snippets.length)%_e.snippets.length,Bi(F,!0))};if(We?.isCharacter&&(ae==="n"||ae==="N")){Te(1);return}if(We?.isCharacter&&(ae==="p"||ae==="P")){Te(-1);return}if(ae==="LEFT"){Te(-1);return}if(ae==="RIGHT"){Te(1);return}let X=$e=>{if($e<0&&F===0){A="input",pt(()=>{Bi(0,!1),uo(),Di()});return}Se(Math.min(P.length-1,Math.max(0,F+$e)))};switch(ae){case"UP":case"SHIFT_TAB":case"CTRL_P":X(-1);return;case"DOWN":case"TAB":case"CTRL_N":X(1);return;case"PAGE_UP":X(-Ot());return;case"PAGE_DOWN":X(Ot());return;case"HOME":X(-F);return;case"END":X(P.length);return}return}},Ft=ae=>{let lt=Kn(),We=lt+Ot()*2-1;if(ae<lt||ae>We)return null;let Te=Ct+Math.floor((ae-lt)/2);return Te>=0&&Te<P.length?Te:null},Mt=null;pe({onKey:ze,onMouse:(ae,lt)=>{if(W)return;if(ae==="MOUSE_WHEEL_UP"||ae==="MOUSE_WHEEL_DOWN"){if(P.length===0)return;let _e=ae==="MOUSE_WHEEL_UP"?-3:3,vt=Math.max(0,P.length-Ot()),St=Math.min(vt,Math.max(0,Ct+_e));if(St===Ct)return;Ct=St,F<Ct?(F=Ct,J=0):F>=Ct+Ot()&&(F=Ct+Ot()-1,J=0),Hi(),uo();return}if(ae==="MOUSE_LEFT_BUTTON_PRESSED"){Mt={x:lt?.x??-1,y:lt?.y??-1};return}let We=lt?.y;if(typeof We!="number")return;if(ae==="MOUSE_MOTION"){if(A!=="results")return;let _e=Ft(We);_e!==null&&Se(_e);return}if(ae!=="MOUSE_LEFT_BUTTON_RELEASED")return;let Te=Mt!==null&<?.x===Mt.x&&We===Mt.y;if(Mt=null,!Te)return;if(We<=yn+2){A!=="input"&&(A="input",Hi(),uo(),Di(),n.moveTo(lo(),Wt()),n.hideCursor(!1));return}let X=Ft(We);if(X===null)return;if(A==="input"){A="results",F=X,J=0,Bo(),pt(()=>{Di(),Hi(),uo(),n.hideCursor()});return}if(X!==F){Se(X);return}Q()},onResize:()=>vs()})},Gt=(L,ee,fe)=>{if(S!=="busy"){if(L==="CTRL_O"){xs();return}if(L==="CTRL_L"){Tf();return}if(S==="rename"&&Ge){if(L==="ENTER"||L==="KP_ENTER"){let Q=Ge.text.trim();if(Q.length===0){S="normal",I=null,Ge=null,Qe();return}Cd(Q);return}if(L==="ESCAPE"||L==="CTRL_C"){S="normal",I=null,Ge=null,Qe();return}if(Ge.handleKey(L,fe?.isCharacter===!0)){Qe();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(fe?.isCharacter&&(L==="y"||L==="Y")){Lf(S==="confirm-kill"?"kill":"delete");return}if(L==="ESCAPE"||L==="CTRL_C"||L==="ENTER"||L==="KP_ENTER"||fe?.isCharacter&&(L==="n"||L==="N")){S="normal",I=null,Qe();return}return}if(Nf(),It&&(It=!1,p=0,pt(()=>{wn(),yr()})),L==="CTRL_F"&&p!==0){wl();return}if(p===0&&!h){if(L==="ESCAPE"){Wo();return}if(L==="ENTER"||L==="KP_ENTER"){let X=Me.expandedText(),$e=tn();X.trim().length>0&&($e.prompt=X),$e.installStatus=Gr(),E($e);return}if(L==="CTRL_T"){qu()&&ho();return}if(L==="UP"&&b){let X=Date.now(),$e=X-k;if(k=X,$e<w){zn();return}b=!1}if(L==="DOWN"){let X=Me.state(),$e=X.historyIndex!==-1||X.queueIndex!==-1,_e=Wn.length===0||Ei===Wn.length-1;if(!$e&&_e&&d.length>0){Vn(1);return}}if(L==="PAGE_DOWN"&&(Wn.length===0||Ei===Wn.length-1)&&d.length>0){Vn(1);return}if(L==="CTRL_P"||L==="CTRL_N"){d.length>0&&Vn(1);return}if(b=!1,L==="TAB"){let X=Me.state(),$e=X.buffer[X.row]??"",_e=gg($e,X.col);if(_e!==null){let vt=yg(_e.token,s);if(vt!==null){if(vt.replacement!==_e.token&&(Me.replaceRangeOnCurrentLine(_e.start,X.col,vt.replacement),Cn()),vt.candidates.length>1){let St=vt.candidates.join(" ");de=`${vt.candidates.length} matches: ${St}`,Gn()}else On();zn();return}}}On();let Q=Me.state(),Se=[...Q.buffer],ze=Q.row,Ft=Q.col,Mt=null;if(L==="")Mt={type:"key",name:"ctrl-underscore"};else if(L==="\x1B_"||L==="\x1B")Mt={type:"key",name:"alt-underscore"};else if(fe?.isCharacter)Mt={type:"char",ch:L};else{let X=pg(L);if(X!==null){if(yd(X)){zn();return}Mt={type:"key",name:X}}}if(Mt===null){zn();return}let dn=Me.feed(Mt),ae=Me.state(),lt=Se.length===ae.buffer.length&&Se.every((X,$e)=>X===ae.buffer[$e])&&ze===ae.row&&Ft===ae.col;if(dn.some(X=>X.type==="exit")){Wo();return}for(let X of dn)X.type==="attachment-request"?Fn():X.type==="edit-in-editor"&&_f();if(lt){zn();return}let We=ms(ae.buffer,er);if(to(We,ae,uf).rendered!==gn){At();return}Cn();return}if(!h&&fe?.isCharacter&&L==="?"){Df();return}if(h){if(fe?.isCharacter){g+=L,In(),At();return}if(L==="BACKSPACE"){g.length>0?(g=g.slice(0,-1),In(),At()):(h=!1,In(),At());return}if(L==="ESCAPE"||L==="CTRL_C"){h=!1,g="",In(),At();return}}if(fe?.isCharacter){if(L==="/"){let Q=p>0?d[p-1]?.sessionId:void 0;h=!0,g="",In(),bs(Q),At();return}if(L==="n"||L==="N"){Vn(1);return}if(L==="p"||L==="P"){Vn(-1);return}if(L==="c"||L==="C"){let Q=tn();Q.installStatus=Gr(),E(Q);return}if(L==="q"||L==="Q"){Wo();return}if(L==="o"||L==="O"){let Q=p>0?d[p-1]?.sessionId:void 0;r.filters.cwdOnly=!r.filters.cwdOnly,In(),bs(Q),At();return}if(L==="h"||L==="H"){let Q=p>0?d[p-1]?.sessionId:void 0;r.filters.hostFilter=x_(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,In(),bs(Q),At();return}if(L==="i"&&p>0){let Q=d[p-1];if(!Q)return;Rd(Q);return}if(L==="I"){let Q=p>0?d[p-1]?.sessionId:void 0;r.filters.includeNonInteractive=!r.filters.includeNonInteractive,In(),bs(Q),At();return}if(L==="r"||L==="R"){let Q=p>0?d[p-1]?.sessionId:void 0;Ki(Q);return}if(L==="s"||L==="S"){Is();return}if((L==="v"||L==="V")&&p>0){let Q=d[p-1];if(!Q)return;let Se={kind:"attach",sessionId:Q.sessionId,readonly:!0};Q.agentId!==void 0&&(Se.agentId=Q.agentId),Se.installStatus=Gr(),E(Se);return}if((L==="f"||L==="F")&&p>0){let Q=d[p-1];if(!Q)return;rr();let Se={kind:"fork",sourceSessionId:Q.sessionId,sourceCwd:Q.cwd};Q.agentId!==void 0&&(Se.sourceAgentId=Q.agentId),Q.importedFromMachine!==void 0&&(Se.sourceImportedFromMachine=Q.importedFromMachine),Q.upstreamSessionId!==void 0&&(Se.sourceUpstreamSessionId=Q.upstreamSessionId),E(Se);return}if((L==="k"||L==="K")&&p>0){let Q=d[p-1];if(!Q)return;I={sessionId:Q.sessionId,cwd:Q.cwd,status:Q.status},S="confirm-kill",Qe();return}if(L==="t"&&p>0){let Q=d[p-1];if(!Q)return;I={sessionId:Q.sessionId,cwd:Q.cwd,status:Q.status},Ge=new vi(Q.title??""),S="rename",Qe();return}if(L==="T"&&p>0){let Q=d[p-1];if(!Q)return;Ln({sessionId:Q.sessionId});return}if(L==="*"&&p>0){let Q=d[p-1];if(!Q)return;Jn(Q);return}if((L==="d"||L==="D")&&p>0){let Q=d[p-1];if(!Q)return;I={sessionId:Q.sessionId,cwd:Q.cwd,status:Q.status},S="confirm-delete",Qe();return}It=!1,p=0,Me.feed({type:"char",ch:L}),At();return}switch(L){case"CTRL_T":{if(!qu())return;if(It||p===0){ho();return}let Q=d[p-1];if(!Q)return;Vr(Q);return}case"UP":case"SHIFT_TAB":case"CTRL_P":L==="UP"&&(p===1&&(b=!0),k=Date.now()),Vn(-1);return;case"DOWN":case"TAB":case"CTRL_N":Vn(1);return;case"PAGE_UP":Vn(-at);return;case"PAGE_DOWN":Vn(at);return;case"HOME":Vn(1-p);return;case"END":Vn(f);return;case"RIGHT":if(It||p===0)break;case"ENTER":case"KP_ENTER":{if(It){let ze=Me.expandedText(),Ft=tn();ze.trim().length>0&&(Ft.prompt=ze),Ft.installStatus=Gr(),E(Ft);return}if(p===0){let ze=tn();ze.installStatus=Gr(),E(ze);return}let Q=d[p-1];if(!Q){rr(),E({kind:"abort"});return}let Se={kind:"attach",sessionId:Q.sessionId};Q.agentId!==void 0&&(Se.agentId=Q.agentId),Se.installStatus=Gr(),E(Se);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Wo();return}}};pe({onKey:(L,ee,fe)=>Gt(L,ee,fe),onResize:()=>{Qt||At()}});let Yr=(L,ee)=>{if(Qt)return;if(oe.length!==1){oe[oe.length-1]?.onMouse?.(L,ee);return}if(S!=="normal")return;let fe=L==="MOUSE_MOTION",Q=L==="MOUSE_DRAG",Se=L==="MOUSE_LEFT_BUTTON_PRESSED",ze=L==="MOUSE_LEFT_BUTTON_RELEASED",Ft=L==="MOUSE_WHEEL_UP",Mt=L==="MOUSE_WHEEL_DOWN",dn=tt&&Date.now()-wd<Fg,ae=!tt||dn;if(Se){po={x:ee?.x??-1,y:ee?.y??-1},Ui=ae;let Oe=ee?.x,Xe=ee?.y;!ae&&typeof Oe=="number"&&typeof Xe=="number"&&Xe>=$n&&Xe<=Zt()&&Cf({x:Oe,y:Xe});return}if(Q){if(mr!==null){let Oe=ee?.x,Xe=ee?.y;typeof Oe=="number"&&typeof Xe=="number"&&dd({x:Oe,y:Xe})}return}if(fe&&ae)return;let lt=ze&&po!==null&&ee?.x===po.x&&ee?.y===po.y,We=lt&&!Ui,Te=lt&&Ui;if(ze&&mr!==null){po=null,Ui=!1;let Oe=ee?.x,Xe=ee?.y;Do(typeof Oe=="number"&&typeof Xe=="number"?{x:Oe,y:Xe}:null);return}if(ze&&(po=null,Ui=!1,!lt))return;if(Ft||Mt){if(d.length===0)return;let Oe=Ft?-3:3,Xe=Math.max(0,d.length-at),kn=Math.min(Xe,Math.max(0,m+Oe));if(kn===m)return;if(m=kn,p>0){let bl=p-1;bl<m?p=m+1:bl>=m+at&&(p=m+at)}yr();return}if(!fe&&!We)return;let X=ee?.y;if(typeof X!="number")return;{let Oe=ee?.x,Xe=bn!==null&&X===Be()&&typeof Oe=="number"&&Oe>=bn.start&&Oe<=bn.end,kn=Ss!==null&&X===Be()&&typeof Oe=="number"&&Oe>=Ss.start&&Oe<=Ss.end;(Xe!==Wi||kn!==Uo)&&(Wi=Xe,Uo=kn,Qe(),p===0?(zn(),n.hideCursor(!1)):n.hideCursor(!0))}if(We&&bn!==null&&X===Be()){let Oe=ee?.x;if(typeof Oe=="number"&&Oe>=bn.start&&Oe<=bn.end){Wo();return}}if(We&&Ss!==null&&X===Be()){let Oe=ee?.x;if(typeof Oe=="number"&&Oe>=Ss.start&&Oe<=Ss.end){let Xe=p>0?d[p-1]?.sessionId:void 0;r.filters.hostFilter=x_(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,In(),bs(Xe),At();return}}if(X>=$n&&X<=Zt()){let Oe=null;if(X===$n){let Xe=ee?.x;typeof Xe=="number"&&(Br!==null&&Xe>=Br.start&&Xe<=Br.end?Oe="agent":Oi!==null&&Xe>=Oi.start&&Xe<=Oi.end&&(Oe="cwd"))}if(Oe!==Xt&&(Xt=Oe,wn()),We&&X===$n){if(Xt==="agent"){Sd();return}if(Xt==="cwd"){xs();return}}if((We||Te)&&p!==0){It=!1;let Xe=p;p=0,pt(()=>{yr(),jo(Xe,p)});return}fe&&!It&&p!==0&&(It=!0,pt(()=>{wn(),yr()}));return}Xt!==null&&(Xt=null,wn()),It&&(It=!1,pt(()=>{wn(),yr()}));let _e=en()+1,vt=_e+at-1;if(X<_e||X>vt)return;let St=m+(X-_e);if(St<0||St>=d.length)return;let Yn=d[St];if(!Yn)return;let Qr=St+1;if(fe&&p===0)return;let cn=p===0,Rs=p===Qr;if(Te&&p!==Qr){let Oe=p;p=Qr,Dr(),pt(()=>{yr(),jo(Oe,p)});return}if(Te)return;if(p!==Qr){let Oe=p;p=Qr,Dr(),pt(()=>{yr(),jo(Oe,p)})}if(!We||cn||!Rs)return;let qo={kind:"attach",sessionId:Yn.sessionId};Yn.agentId!==void 0&&(qo.agentId=Yn.agentId),qo.installStatus=Gr(),E(qo)},wr=()=>{n.grabInput({mouse:"motion"}),ge({src:"grab",site:"picker.installGrab",on:!0});let L=n;L.stdin&&typeof L.onStdin=="function"&&(nr=L.onStdin,L.stdin.removeListener("data",L.onStdin),L.stdin.on("data",vd),we(ym),we(km)),n.on("key",qi),n.on("mouse",Yr),n.on("resize",ml)},Cs=()=>{we(Po),we(Nu);let L=n;L.stdin&&nr&&(L.stdin.removeListener("data",vd),L.stdin.on("data",nr),nr=null),fo=!1,Kr="",n.off("key",qi),n.off("mouse",Yr),n.off("resize",ml),n.grabInput(!1),ge({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(wr(),fl=()=>{pl=!0,K&&(K.abort(),K=null,U=!1),Cs(),n.fullscreen(!1),we(`${Lu}${wm}`)},kd=()=>{pl=!1,n.fullscreen(!0),t(),n.hideCursor(),wr(),Qt||Tf()},process.platform!=="win32"){let L=!1,ee=()=>{L&&(L=!1,kd?.())};bd=()=>{L||Qt||(L=!0,fl?.(),we(`
|
|
280
|
-
`),process.once("SIGCONT",ee),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(xd,3e3)})}function yG(n,e){let t="Create new session in ",r=Math.max(1,e-t.length);return t+Eu(V(n),r)}function vg(n,e){let t=s=>s.priority&&s.priority>0?s.priority:0,r=s=>{let o=s.status==="warm",i=t(s)>0;return o&&s.busy&&s.awaitingInput?6:o&&s.busy?5:o&&s.awaitingInput?4:o&&i?3:o?2:i?1:0};return[...n].sort((s,o)=>{let i=r(o)-r(s);if(i!==0)return i;let a=t(o)-t(s);return a!==0?a:o.updatedAt.slice(0,16).localeCompare(s.updatedAt.slice(0,16))})}function wG(n,e){return n?e.has(n):!0}function eS(n){return!!n.importedFromMachine&&!n.upstreamSessionId}function bG(n,e,t=Sp()){if(e==="__all")return n;let r=o=>!o.remote&&(wG(o.importedFromMachine,t)||!!o.upstreamSessionId);if(e==="__local")return n.filter(r);if(e==="__remotes")return n.filter(o=>o.remote?!eS(o):r(o));if(e.startsWith(Ci)){let o=e.slice(Ci.length);return n.filter(i=>i.remote===o&&!eS(i))}let s=e.startsWith(Ya)?e.slice(Ya.length):e;return n.filter(o=>o.importedFromMachine===s&&!t.has(s)&&!o.upstreamSessionId)}function x_(n,e,t=Sp()){let r=I_(e,t),s=r.indexOf(n);return s===-1?"__local":r[(s+1)%r.length]??"__local"}function I_(n,e){let t=new Set,r=new Set;for(let s of n){if(s.remote){eS(s)||t.add(s.remote);continue}s.importedFromMachine&&!s.upstreamSessionId&&!e.has(s.importedFromMachine)&&r.add(s.importedFromMachine)}return["__local",...t.size>0?["__remotes"]:[],...[...t].sort().map(s=>`${Ci}${s}`),...[...r].sort().map(s=>`${Ya}${s}`),"__all"]}function kG(n,e,t=Sp()){if(n==="all")return"__all";let r=I_(e,t),s;return n===`${Ci}all`?s=["__remotes"]:n.startsWith(Ci)||n.startsWith(Ya)?s=[n]:s=[`${Ci}${n}`,`${Ya}${n}`],s.find(o=>r.includes(o))??"__local"}function vG(n){return n==="__local"?"host: local":n==="__remotes"?"host: local + remotes":n.startsWith(Ci)?`remote: ${n.slice(Ci.length)}`:n.startsWith(Ya)?`host: ${n.slice(Ya.length)}`:`host: ${n}`}function SG(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),r=[st(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,V(n.cwd)];for(let s of r)if(s.toLowerCase().includes(t))return!0;return!1}var kg,uf,hG,v_,mG,S_,Ci,Ya,C_=q(()=>{"use strict";Nc();zl();Os();ke();ir();rt();
|
|
281
|
-
`).map(c=>c.trimEnd()).filter(c=>c.length>0),a=s?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",d=()=>{let c=xn(n),l=
|
|
282
|
-
`)),m=Math.max(1,l-4-4),h=p.length>m,g=h?p.slice(0,m-1):p,w=g.length+(h?1:0)+4,b=pr(n,{contentHeight:w,contentWidth:u,title:"Agent failed to start"}),k=b.contentW,S=0;n.moveTo(b.contentX,b.contentY+S),B(n,"modal-title",_t(` ${o}`,k)),S+=2;for(let I of g)n.moveTo(b.contentX,b.contentY+S),B(n,"modal-error",_t(` ${I}`,k)),S++;return h&&(n.moveTo(b.contentX,b.contentY+S),B(n,"modal-hint",_t(" \u2026 (full details in ~/.hydra-acp/tui.log)",k)),S++),S++,n.moveTo(b.contentX,b.contentY+S),B(n,"modal-hint",_t(` ${a}`,k)),b};return Ys({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(s?"back":"cancel");return}c==="CTRL_C"&&f("cancel")}})}var CG,E_=q(()=>{"use strict";Na();Tn();CG=100});import{exec as RG}from"child_process";function Sg(n){let e=n.exec??AG,t=new Set,r=new Map,s=o=>{t.add(o);let i=n.envFor?.(o);e(o,{cwd:n.cwd()??void 0,timeout:TG,maxBuffer:EG,env:i?{...process.env,...i}:void 0},(a,d)=>{t.delete(o),n.onOutput(o,a?null:n.sanitize(d))})};return{poll(o,i){for(let[a,d]of o){if(t.has(a))continue;let c=r.get(a);c!==void 0&&i-c<d||(r.set(a,i),s(a))}}}}var AG,TG,EG,rS=q(()=>{"use strict";AG=(n,e,t)=>{RG(n,e,(r,s)=>t(r,s))},TG=3e3,EG=64*1024});function sS(n,e){let t=new Map,r=s=>{for(let o of s){if(typeof o=="string"||o.script===void 0)continue;let i=o.refreshMs??e,a=t.get(o.script);t.set(o.script,a===void 0?i:Math.min(a,i))}};return r(n.composer.top.left),r(n.composer.top.right),r(n.composer.bottom.left),r(n.composer.bottom.right),r(n.sessionbar.left),r(n.sessionbar.right),t}function PG(n){let e=n.trim().replace(/\s+/g," ");return e.length===0?null:e}function P_(n){return Sg({cwd:n.cwd,envFor:n.envFor,sanitize:PG,onOutput:n.onOutput,exec:n.exec})}var M_=q(()=>{"use strict";rS()});async function MG(n,e){try{let t=await fetch(`${n.baseUrl}/v1/process-tokens`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({sessionLabel:e}),signal:AbortSignal.timeout(3e3)});if(!t.ok)return;let r=await t.json();return typeof r.token=="string"?r.token:void 0}catch{return}}async function __(n,e,t){let r=new Map;return await Promise.all([...t.keys()].map(async s=>{let o=await MG(n,e);o&&r.set(s,o)})),r}async function $_(n,e){try{await fetch(`${n.baseUrl}/v1/process-tokens/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`},signal:AbortSignal.timeout(3e3)})}catch{}}var O_=q(()=>{"use strict"});function pf(n){if(typeof n!="string")return null;let e=n.trim();return e.length>0?e:null}function F_(n){if(!n||typeof n!="object")return{origin:"client",label:null};let e=n,t=pf(e.fromSession);return t?{origin:"peer",label:pf(e.fromSessionTitle)??pf(e.fromLabel)??t}:{origin:"client",label:pf(e.fromLabel)??pf(e.name)}}var L_=q(()=>{"use strict"});function N_(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 r=t._meta;if(r&&typeof r=="object"){let s=r["hydra-acp"];if(s&&typeof s=="object"){let o=s,i=o.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i),typeof o.armedSince=="number"&&o.armedSince>0&&(e.armedSince=o.armedSince),typeof o.armedTasks=="number"&&o.armedTasks>=0&&(e.armedTasks=o.armedTasks),Array.isArray(o.armedTaskList)&&(e.armedTaskList=o.armedTaskList)}}return e}function D_(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function B_(n){return!n.blockOpen&&n.isStart}function H_(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 U_=q(()=>{"use strict"});function xg(n){let e=Zo(n);if(e===null)throw new Error(`built-in theme has a malformed colour: ${n}`);return e}function _n(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=xg(s);return t.bg=xg(e.bg),t.fg=xg(e.fg),t}function Or(n){return{fg:xg(n)}}function hr(n){return{fg:gt(n)}}function oS(n){return W_.find(e=>e.name===n)}function iS(){return W_.map(n=>n.name)}function j_(n){return n===void 0?"terminal":Jd(n)?VG:YG}function q_(n,e,t){if(n.length===0)return;let r=n.indexOf(e);return r===-1?t===1?n[0]:n[n.length-1]:n[(r+t+n.length)%n.length]}var _G,$G,OG,FG,LG,NG,DG,BG,HG,UG,WG,jG,qG,Nt,zG,KG,GG,JG,W_,VG,YG,aS=q(()=>{"use strict";Yd();Tn();_G=_n({black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff5555",brightGreen:"#50fa7b",brightYellow:"#f1fa8c",brightBlue:"#bd93f9",brightMagenta:"#ff79c6",brightCyan:"#8be9fd",brightWhite:"#ffffff"},{bg:"#282a36",fg:"#f8f8f2"}),$G=_n({black:"#3b4252",red:"#bf616a",green:"#a3be8c",yellow:"#ebcb8b",blue:"#81a1c1",magenta:"#b48ead",cyan:"#88c0d0",white:"#e5e9f0",brightBlack:"#4c566a",brightRed:"#bf616a",brightGreen:"#a3be8c",brightYellow:"#ebcb8b",brightBlue:"#81a1c1",brightMagenta:"#b48ead",brightCyan:"#8fbcbb",brightWhite:"#eceff4"},{bg:"#2e3440",fg:"#d8dee9"}),OG=_n({black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},{bg:"#282828",fg:"#ebdbb2"}),FG=_n({black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#657b83",brightBlack:"#93a1a1",brightRed:"#cb4b16",brightGreen:"#859900",brightYellow:"#b58900",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#073642"},{bg:"#fdf6e3",fg:"#657b83"}),LG=(()=>{let n={};for(let e of Object.keys(ia))n[e]=gt(7);return n})(),NG=_n({black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#93a1a1",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#859900",brightYellow:"#b58900",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#fdf6e3"},{bg:"#002b36",fg:"#839496"}),DG=_n({black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#6c7086",brightRed:"#eba0ac",brightGreen:"#a6e3a1",brightYellow:"#fab387",brightBlue:"#b4befe",brightMagenta:"#cba6f7",brightCyan:"#89dceb",brightWhite:"#cdd6f4"},{bg:"#1e1e2e",fg:"#cdd6f4"}),BG=_n({black:"#51576d",red:"#e78284",green:"#a6d189",yellow:"#e5c890",blue:"#8caaee",magenta:"#f4b8e4",cyan:"#81c8be",white:"#b5bfe2",brightBlack:"#737994",brightRed:"#ea999c",brightGreen:"#a6d189",brightYellow:"#ef9f76",brightBlue:"#babbf1",brightMagenta:"#ca9ee6",brightCyan:"#99d1db",brightWhite:"#c6d0f5"},{bg:"#303446",fg:"#c6d0f5"}),HG=_n({black:"#494d64",red:"#ed8796",green:"#a6da95",yellow:"#eed49f",blue:"#8aadf4",magenta:"#f5bde6",cyan:"#8bd5ca",white:"#b8c0e0",brightBlack:"#6e738d",brightRed:"#ee99a0",brightGreen:"#a6da95",brightYellow:"#f5a97f",brightBlue:"#b7bdf8",brightMagenta:"#c6a0f6",brightCyan:"#91d7e3",brightWhite:"#cad3f5"},{bg:"#24273a",fg:"#cad3f5"}),UG=_n({black:"#ccd0da",red:"#d20f39",green:"#40a02b",yellow:"#df8e1d",blue:"#1e66f5",magenta:"#ea76cb",cyan:"#179299",white:"#5c5f77",brightBlack:"#8c8fa1",brightRed:"#e64553",brightGreen:"#40a02b",brightYellow:"#fe640b",brightBlue:"#7287fd",brightMagenta:"#8839ef",brightCyan:"#04a5e5",brightWhite:"#4c4f69"},{bg:"#eff1f5",fg:"#4c4f69"}),WG=_n({black:"#ebdbb2",red:"#9d0006",green:"#79740e",yellow:"#b57614",blue:"#076678",magenta:"#8f3f71",cyan:"#427b58",white:"#504945",brightBlack:"#7c6f64",brightRed:"#cc241d",brightGreen:"#98971a",brightYellow:"#af3a03",brightBlue:"#458588",brightMagenta:"#b16286",brightCyan:"#689d6a",brightWhite:"#3c3836"},{bg:"#fbf1c7",fg:"#3c3836"}),jG=_n({black:"#414868",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#565f89",brightRed:"#ff757f",brightGreen:"#73daca",brightYellow:"#ff9e64",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#2ac3de",brightWhite:"#c0caf5"},{bg:"#1a1b26",fg:"#c0caf5"}),qG=_n({black:"#3f4451",red:"#e05561",green:"#8cc265",yellow:"#d18f52",blue:"#4aa5f0",magenta:"#c162de",cyan:"#42b3c2",white:"#abb2bf",brightBlack:"#5c6370",brightRed:"#ff616e",brightGreen:"#a5e075",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#e6e6e6"},{bg:"#282c34",fg:"#abb2bf"}),Nt={orange:"#e69f00",skyBlue:"#56b4e9",bluishGreen:"#009e73",yellow:"#f0e442",blue:"#0072b2",vermillion:"#d55e00",reddishPurple:"#cc79a7"},zG=_n({black:"#3a3a3a",red:Nt.reddishPurple,green:Nt.bluishGreen,yellow:Nt.orange,blue:Nt.blue,magenta:Nt.reddishPurple,cyan:Nt.skyBlue,white:"#d0d0d0",brightBlack:"#8a8a8a",brightRed:Nt.vermillion,brightGreen:Nt.bluishGreen,brightYellow:Nt.yellow,brightBlue:Nt.skyBlue,brightMagenta:Nt.reddishPurple,brightCyan:Nt.skyBlue,brightWhite:"#f0f0f0"},{bg:"#1c1c1c",fg:"#d0d0d0"});KG=_n({black:"#090618",red:"#c34043",green:"#76946a",yellow:"#c0a36e",blue:"#7e9cd8",magenta:"#957fb8",cyan:"#6a9589",white:"#c8c093",brightBlack:"#727169",brightRed:"#e82424",brightGreen:"#98bb6c",brightYellow:"#e6c384",brightBlue:"#7fb4ca",brightMagenta:"#938aa9",brightCyan:"#7aa89f",brightWhite:"#dcd7ba"},{bg:"#1f1f28",fg:"#dcd7ba"}),GG=_n({black:"#343f44",red:"#e67e80",green:"#a7c080",yellow:"#e69875",blue:"#7fbbb3",magenta:"#d699b6",cyan:"#83c092",white:"#d3c6aa",brightBlack:"#859289",brightRed:"#e67e80",brightGreen:"#a7c080",brightYellow:"#dbbc7f",brightBlue:"#7fbbb3",brightMagenta:"#d699b6",brightCyan:"#83c092",brightWhite:"#d3c6aa"},{bg:"#2d353b",fg:"#d3c6aa"}),JG=_n({black:"#141c12",red:"#ff4b4b",green:"#1cc24b",yellow:"#e6ff57",blue:"#30b3ff",magenta:"#c770ff",cyan:"#24f6d9",white:"#2eff6a",brightBlack:"#8ca391",brightRed:"#ff4b4b",brightGreen:"#2eff6a",brightYellow:"#ffa83d",brightBlue:"#30b3ff",brightMagenta:"#c770ff",brightCyan:"#00efff",brightWhite:"#62ff94"},{bg:"#0a0e0a",fg:"#62ff94"}),W_=[{name:"terminal",description:"your terminal's own 16 colours (default)",palette:ia},{name:"dracula",description:"dark, high contrast, purple-leaning",palette:_G},{name:"nord",description:"dark, cool, low contrast",palette:$G},{name:"gruvbox-dark",description:"dark, warm, retro",counterpart:"gruvbox-light",palette:OG},{name:"catppuccin-mocha",description:"dark, soft pastel (the default on a dark terminal)",counterpart:"catppuccin-latte",palette:DG},{name:"catppuccin-macchiato",description:"dark, soft pastel, one step lighter than mocha",counterpart:"catppuccin-latte",palette:HG},{name:"catppuccin-frappe",description:"dark, soft pastel, the lightest of the dark flavours",counterpart:"catppuccin-latte",palette:BG},{name:"catppuccin-latte",description:"light, soft pastel (the default on a light terminal)",counterpart:"catppuccin-mocha",palette:UG},{name:"tokyo-night",description:"dark, deep blue",palette:jG},{name:"one-dark",description:"dark, the Atom default",palette:qG},{name:"kanagawa",description:"dark, muted ink tones",palette:KG},{name:"everforest",description:"dark, warm green, gentle contrast",palette:GG},{name:"matrix",description:"dark, green on black",palette:JG},{name:"gruvbox-light",description:"light, warm, retro",counterpart:"gruvbox-dark",palette:WG},{name:"colorblind",description:"dark, no meaning carried on the red/green axis",palette:zG,roles:{ok:Or(Nt.skyBlue),error:Or(Nt.vermillion),errorSoft:Or(Nt.vermillion),warn:Or(Nt.orange),active:Or(Nt.yellow),cold:Or(Nt.reddishPurple),diffAdded:Or(Nt.skyBlue),diffRemoved:Or(Nt.vermillion),gitStaged:Or(Nt.blue),gitDirty:Or(Nt.orange),syntaxRegexp:Or(Nt.reddishPurple),syntaxNumber:Or(Nt.skyBlue)}},{name:"solarized-dark",description:"dark, low contrast",counterpart:"solarized-light",palette:NG},{name:"solarized-light",description:"light",counterpart:"solarized-dark",palette:FG},{name:"mono",description:"no colour; weight and glyphs only",palette:LG,roles:{subtle:hr(8),muted:hr(8),fg:hr(7),fgStrong:hr(15),active:hr(15),error:hr(15),warn:hr(15),ok:hr(7),cold:hr(7),accent:hr(15),info:hr(7),reference:hr(15),focus:hr(15),selection:{bg:gt(8),fg:gt(15)},selectionBand:{bg:gt(8)},cursor:{bg:gt(15),fg:gt(0)},promptCursor:{bg:gt(15),fg:gt(0)},match:{bg:gt(15),fg:gt(0)},matchActive:{bg:gt(7),fg:gt(0)}}}];VG="catppuccin-mocha",YG="catppuccin-latte"});import{readdir as QG,readFile as XG}from"fs/promises";import{join as V_}from"path";function ZG(n,e,t,r){let s=(c,l)=>{if(c===void 0)return;if(typeof c!="string")return r.push(`${e}${l}: must be a colour string, got ${Ig(c)}`),null;let u=Zo(c);return u===null?(r.push(`${e}${l}: is not a colour ("${c}") \u2014 expected #rgb, #rrggbb, or rgb(r,g,b)`),null):u};if(typeof n=="string"){let c=s(n,"");return c==null?null:t?{fg:c}:{bg:c}}if(typeof n!="object"||n===null||Array.isArray(n))return r.push(`${e}: must be a colour string or { fg, bg }, got ${Ig(n)}`),null;let o=n;for(let c of Object.keys(o))c!=="fg"&&c!=="bg"&&r.push(`${e}: unknown key "${c}" \u2014 expected fg or bg`);let i=s(o.fg,".fg"),a=s(o.bg,".bg");if(i===null||a===null)return null;if(i===void 0&&a===void 0)return r.push(`${e}: needs at least one of fg or bg`),null;let d={};return i!==void 0&&(d.fg=i),a!==void 0&&(d.bg=a),d}function G_(n,e,t,r,s,o){let i={};if(n===void 0)return i;if(typeof n!="object"||n===null||Array.isArray(n))return o.push(`${t}: ${e} must be an object`),i;let a=new Set(r);for(let[d,c]of Object.entries(n)){if(!a.has(d)){let u=r.filter(f=>f.includes(d)||d.includes(f));o.push(`${t}: unknown ${e==="roles"?"role":"element"} "${d}"`+(u.length>0?` \u2014 did you mean ${u.slice(0,4).join(", ")}?`:"")+` (${r.length} available)`);continue}let l=ZG(c,`${t}: ${e}.${d}`,s(d),o);l!==null&&(i[d]=l)}return i}async function dS(n,e){let t=[],r=()=>({palette:ia,overrides:{roles:{},elements:{}},name:"terminal",problems:t});return n==null?r():typeof n=="string"?await Y_(n,e,t,new Set)??r():typeof n!="object"||Array.isArray(n)?(t.push(`tui.theme must be a theme name or an object, got ${Ig(n)}`),r()):{...await Q_(n,"tui.theme",e,t,new Set),name:"custom",problems:t}}function Ig(n){return Array.isArray(n)?"an array":typeof n}async function Y_(n,e,t,r){if(r.has(n))return t.push(`theme "${n}": extends forms a cycle`),null;r.add(n);let s=await e4(n,e,t);if(s!==null)return{...await Q_(s,`theme "${n}"`,e,t,r),name:n,problems:t};let o=oS(n);return o!==void 0?{palette:o.palette,overrides:{roles:{...o.roles??{}},elements:{}},name:n,problems:t}:(t.push(`unknown theme "${n}" \u2014 expected one of ${iS().join(", ")}, or a file at ${V_(e,`${n}.json`)}`),null)}async function e4(n,e,t){if(!/^[A-Za-z0-9._-]+$/.test(n)||n.startsWith("."))return null;let r=V_(e,`${n}.json`),s;try{s=await XG(r,"utf8")}catch{return null}try{let o=JSON.parse(s);return typeof o!="object"||o===null||Array.isArray(o)?(t.push(`theme file ${r}: expected a JSON object`),null):o}catch(o){return t.push(`theme file ${r}: ${o.message.split(`
|
|
278
|
+
${L}`},Lg=(L,ee)=>{o=vg(_T(o,L,ee),s),i=L.cursor},Id=0,Ng=async()=>{if(!e.target.isLocal)return!1;try{let L=await rn(await He());return L.baseUrl===e.target.baseUrl&&L.wsUrl===e.target.wsUrl&&L.token===e.target.token?!1:(e.target.baseUrl=L.baseUrl,e.target.wsUrl=L.wsUrl,e.target.display=L.display,e.target.token=L.token,!0)}catch{return!1}},Ki=async(L,ee={})=>{let fe=async()=>{let Q=ee.silent?zi():"",Se=f,ze=i!==void 0,Ft=await Db(e.target,{includeNonInteractive:!0,since:i,signal:ee.signal}),Mt=L??(p>0?d[p-1]?.sessionId:void 0);if(Lg(Ft,ze),In(),Mt!==void 0){let dn=d.findIndex(ae=>ae.sessionId===Mt);dn>=0?p=dn+1:p=0}p>f-1&&(p=Math.max(0,f-1)),m+at>d.length&&(m=Math.max(0,d.length-at)),Dr(),!(ee.silent&&zi()===Q)&&(f===Se?Of():At())};try{await fe(),Id=0}catch(Q){let Se=Q;if(await Ng())try{await fe(),Id=0;return}catch(ze){Se=ze}if(ee.silent){Id+=1,Id>=3&&(Ae=`refresh failing: ${Se.message}`,At());return}Ae=`refresh failed: ${Se.message}`,At()}},Cd=async L=>{if(!I)return;let ee=I;S="busy",Qe();try{await Au(e.target,ee.sessionId,L),S="normal",I=null,Ge=null,await Ki(ee.sessionId)}catch(fe){S="normal",I=null,Ge=null,Ae=`rename failed: ${fe.message}`,Qe()}},Ln=async L=>{try{await FT(e.target,L.sessionId),Ae="title regen queued (press r to refresh)",Qe()}catch(ee){Ae=`regen failed: ${ee.message}`,Qe()}},Jn=async L=>{let fe=(L.priority&&L.priority>0?L.priority:0)>0?null:1,Q=fe??0;for(let ze of o)ze.sessionId===L.sessionId&&(ze.priority=Q>0?Q:void 0);let Se=L.sessionId;o=vg(o,s),In(),Se!==void 0&&bs(Se),At(),Ae=Q>0?"priority: high":"priority: normal",Qe();try{await OT(e.target,L.sessionId,fe)}catch(ze){Ae=`priority failed: ${ze.message}`,Qe()}},Is=async()=>{if(se)return;se=!0;let L=p>0?d[p-1]?.sessionId:void 0;Ae="syncing agents\u2026",Qe();try{let{synced:ee,skipped:fe,agents:Q}=await $T(e.target);await Ki(L),Ae=`synced ${ee} new (${fe} known) from ${Q} agent${Q===1?"":"s"}`,Qe()}catch(ee){Ae=`sync failed: ${ee.message}`,Qe()}finally{se=!1}},Jr=!1,Vr=async L=>{if(Jr)return;Jr=!0;let ee=L.title?.trim()||st(L.sessionId);Ae=Lm()?`showing ${ee} in ${Va()}\u2026`:`opening ${ee} in a new ${Va()} tab\u2026`,Qe();try{let fe=await zu({kind:"attach",sessionId:L.sessionId,title:L.title,cwd:qa(L)!==void 0?void 0:L.cwd});Ae=fe.outcome==="revealed"?`jumped to ${ee} \u2014 already open in ${Va()}`:fe.outcome==="opened"?`opened ${ee} in a new ${Va()} tab`:`new tab failed: ${fe.error??"unknown error"}`}catch(fe){Ae=`new tab failed: ${fe.message}`}finally{Jr=!1,Qe()}},mo=async()=>{if(Jr)return;Jr=!0;let L=Me.expandedText(),ee=[...Me.state().attachments],fe=ee.length;Ae=`opening a new session in a new ${Va()} tab\u2026`,Qe();try{let Q=await Yc({kind:"new",cwd:s,agentId:jn,model:qn,prompt:L});Q.ok?(L.trim().length>0&&Me.setBuffer("",ee),Ae=fe>0?`opened a new ${Va()} tab \u2014 ${fe} attachment${fe===1?"":"s"} stayed here`:`opened a new session in a new ${Va()} tab`):Ae=`new tab failed: ${Q.error??"unknown error"}`}catch(Q){Ae=`new tab failed: ${Q.message}`}finally{Jr=!1,At()}},Lf=async L=>{if(!I)return;let ee=I;S="busy",Qe();try{L==="kill"?await Js(e.target,ee.sessionId):await NT(e.target,ee.sessionId),S="normal",I=null,ee.sessionId===e.currentSessionId&&(Rt=!0);let fe;if(L==="kill")fe=ee.sessionId;else{let Q=d.findIndex(Se=>Se.sessionId===ee.sessionId);Q>=0&&(fe=d[Q+1]?.sessionId??d[Q-1]?.sessionId)}await Ki(fe)}catch(fe){S="normal",I=null,Ae=`${L} failed: ${fe.message}`,Qe()}},jo=(L,ee)=>{L===0!=(ee===0)&&(wn(),ee===0?(n.hideCursor(!1),zn()):n.hideCursor())},Vn=L=>{let ee=Math.min(f-1,Math.max(0,p+L));if(ee===p)return;let fe=p;p=ee,Dr(),pt(()=>{yr(),jo(fe,p)})},Nf=()=>Ae===null?!1:(Ae=null,Qe(),!0),Df=()=>{Ef();let L=!1;pe({onKey:ee=>{if(ee==="CTRL_C"){rr(),E({kind:"abort"});return}nt()},onMouse:ee=>{if(ee==="MOUSE_LEFT_BUTTON_PRESSED"){L=!0;return}ee!=="MOUSE_LEFT_BUTTON_RELEASED"||!L||(L=!1,nt())},onResize:()=>Ef()})},Rd=L=>{let ee=null,fe=null,Q=!0,Se=0,ze=null,Ft=0,Mt=()=>Q?["loading\u2026"]:fe!==null?[fe]:ee??[],dn=()=>{pt(()=>{n.hideCursor(),Ve.clearCache();let X=Mt(),$e=Ys(n),_e=xn(n),vt=Math.max(3,$e-6),St=Math.min(X.length,vt),Yn=X.reduce((Oe,Xe)=>Math.max(Oe,Xe.length),0),Qr=Math.min(Math.max(40,Yn+2),Math.max(20,_e-6)),cn=pr(n,{contentHeight:St+2,contentWidth:Qr,title:`Session info \u2014 ${st(L.sessionId)}`,overlay:!0});ze={x:cn.x,y:cn.y,w:cn.w,h:cn.h},Ft=St,Se=Math.max(0,Math.min(Se,Math.max(0,X.length-St)));for(let Oe=0;Oe<St;Oe++){let Xe=X[Se+Oe]??"";n.moveTo(cn.contentX,cn.contentY+Oe);let kn=Xe.slice(0,cn.contentW-1);fe!==null?B(n,"modal-error",` ${kn}`):B(n,"content",` ${kn}`),n.styleReset()}let Rs=X.length-St-Se,qo=X.length>St?`\u2191/\u2193/wheel scroll${Rs>0?` (${Rs} more)`:""} \xB7 Esc or click outside to return`:"Esc or click outside to return";n.moveTo(cn.contentX,cn.contentY+St+1),B(n,"modal-hint",` ${qo}`),n.styleReset()})};dn();let ae=new AbortController,lt=()=>{ae.abort(),nt()},We=X=>{let $e=Math.max(0,Mt().length-Ft),_e=Math.max(0,Math.min($e,Se+X));_e!==Se&&(Se=_e,dn())},Te={onKey:X=>{if(X==="ESCAPE"||X==="CTRL_C"){lt();return}if(X==="UP"){We(-1);return}if(X==="DOWN"){We(1);return}if(X==="PAGE_UP"){We(-Math.max(1,Ft-1));return}if(X==="PAGE_DOWN"){We(Math.max(1,Ft-1));return}if(X==="HOME"){We(-Number.MAX_SAFE_INTEGER);return}if(X==="END"){We(Number.MAX_SAFE_INTEGER);return}},onMouse:(X,$e)=>{if(X==="MOUSE_WHEEL_UP"){We(-3);return}if(X==="MOUSE_WHEEL_DOWN"){We(3);return}if(X!=="MOUSE_LEFT_BUTTON_RELEASED"||ze===null)return;let _e=$e?.x??-1,vt=$e?.y??-1;_e>=ze.x&&_e<ze.x+ze.w&&vt>=ze.y&&vt<ze.y+ze.h||lt()},onResize:()=>dn()};pe(Te),(async()=>{try{let X=await lr(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(L.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ae.signal});if(!X.ok)throw new Error(`daemon returned HTTP ${X.status}`);let $e=await X.json(),_e=as($e),vt=ok(_e,L.status);ee=dm(vt,!1).replace(/\n$/,"").split(`
|
|
279
|
+
`)}catch(X){if(ae.signal.aborted)return;fe=`failed to load info: ${X.message}`}finally{Q=!1,!Qt&&oe[oe.length-1]===Te&&dn()}})()},wl=()=>{if(d.length===0){Ae="no sessions to search",Qe();return}_=new Mo({history:[],collapsePastes:!1});let L=r.lastFind,ee=new Set(d.map(ae=>ae.sessionId)),fe=L?L.results.filter(ae=>ee.has(ae.sessionId)):[];L&&L.query.length>0&&_.setBuffer(L.query),P=fe,Re(),$=L?.truncated??!1,F=Math.min(Math.max(0,L?.selectedIdx??0),Math.max(0,fe.length-1)),J=0,Ct=0,Y=null,W=!1,A=fe.length>0?"results":"input",x=!0,ks(),Bo(),vs();let Q=()=>{let ae=P[F];if(!ae)return;let lt=d.find(X=>X.sessionId===ae.sessionId),We=!!lt?.importedFromMachine&&!lt.remote&&!lt.upstreamSessionId,Te=ae.snippets[J]?.recordedAt??ae.snippets[0]?.recordedAt;if(We){qr(),rr();let X={kind:"attach",sessionId:ae.sessionId};lt.agentId!==void 0&&(X.agentId=lt.agentId),Te!==void 0&&(X.jumpToRecordedAt=Te),E(X);return}(async()=>{let X=await h_(n,{sessionId:ae.sessionId,title:ae.title,cwd:ae.cwd},Dt);if(X==="cancel"){qr(),rr(),E({kind:"abort"});return}if(X==="back")return;qr(),rr();let $e={kind:"attach",sessionId:ae.sessionId,readonly:X==="view"};lt?.agentId!==void 0&&($e.agentId=lt.agentId),Te!==void 0&&($e.jumpToRecordedAt=Te),E($e)})()},Se=ae=>{if(ae<0||ae>=P.length||ae===F)return;let lt=F,We=Ct;F=ae,J=0,Bo(),Ct!==We?Hi():pt(()=>{Bi(lt,!1),Bi(F,!0)}),fo()},ze=(ae,lt,We)=>{if(A==="input"){if(W)return;if(ae==="ESCAPE"||ae==="CTRL_C"){zr();return}if(ae==="ENTER"||ae==="KP_ENTER"){if(md().trim().length===0)return;jr();return}if((ae==="DOWN"||ae==="TAB"||ae==="CTRL_N")&&P.length>0){A="results",F=0,J=0,pt(()=>{Di(),Bi(0,!0),fo(),n.hideCursor()});return}let Te=_.state(),X=[...Te.buffer],$e=Te.row,_e=Te.col,vt=null;if(ae==="")vt={type:"key",name:"ctrl-underscore"};else if(ae==="\x1B_"||ae==="\x1B")vt={type:"key",name:"alt-underscore"};else if(We?.isCharacter)vt={type:"char",ch:ae};else{let cn=pg(ae);cn!==null&&(vt={type:"key",name:cn})}if(vt===null){n.moveTo(uo(),Wt());return}_.feed(vt);let St=_.state();if(X.length===St.buffer.length&&X.every((cn,Rs)=>cn===St.buffer[Rs])&&$e===St.row&&_e===St.col){n.moveTo(uo(),Wt());return}let Qr=yn;ks(),yn!==Qr?vs():cl();return}if(A==="results"){if(ae==="ESCAPE"||ae==="CTRL_C"){zr();return}if(ae==="CTRL_F"){A="input",Hi(),fo(),Di();return}if(ae==="ENTER"||ae==="KP_ENTER"){Q();return}if(We?.isCharacter&&ae==="i"){let $e=P[F];if(!$e)return;let _e=d.find(vt=>vt.sessionId===$e.sessionId);if(!_e)return;Rd(_e);return}let Te=$e=>{let _e=P[F];!_e||_e.snippets.length<=1||(J=(J+$e+_e.snippets.length)%_e.snippets.length,Bi(F,!0))};if(We?.isCharacter&&(ae==="n"||ae==="N")){Te(1);return}if(We?.isCharacter&&(ae==="p"||ae==="P")){Te(-1);return}if(ae==="LEFT"){Te(-1);return}if(ae==="RIGHT"){Te(1);return}let X=$e=>{if($e<0&&F===0){A="input",pt(()=>{Bi(0,!1),fo(),Di()});return}Se(Math.min(P.length-1,Math.max(0,F+$e)))};switch(ae){case"UP":case"SHIFT_TAB":case"CTRL_P":X(-1);return;case"DOWN":case"TAB":case"CTRL_N":X(1);return;case"PAGE_UP":X(-Ot());return;case"PAGE_DOWN":X(Ot());return;case"HOME":X(-F);return;case"END":X(P.length);return}return}},Ft=ae=>{let lt=Kn(),We=lt+Ot()*2-1;if(ae<lt||ae>We)return null;let Te=Ct+Math.floor((ae-lt)/2);return Te>=0&&Te<P.length?Te:null},Mt=null;pe({onKey:ze,onMouse:(ae,lt)=>{if(W)return;if(ae==="MOUSE_WHEEL_UP"||ae==="MOUSE_WHEEL_DOWN"){if(P.length===0)return;let _e=ae==="MOUSE_WHEEL_UP"?-3:3,vt=Math.max(0,P.length-Ot()),St=Math.min(vt,Math.max(0,Ct+_e));if(St===Ct)return;Ct=St,F<Ct?(F=Ct,J=0):F>=Ct+Ot()&&(F=Ct+Ot()-1,J=0),Hi(),fo();return}if(ae==="MOUSE_LEFT_BUTTON_PRESSED"){Mt={x:lt?.x??-1,y:lt?.y??-1};return}let We=lt?.y;if(typeof We!="number")return;if(ae==="MOUSE_MOTION"){if(A!=="results")return;let _e=Ft(We);_e!==null&&Se(_e);return}if(ae!=="MOUSE_LEFT_BUTTON_RELEASED")return;let Te=Mt!==null&<?.x===Mt.x&&We===Mt.y;if(Mt=null,!Te)return;if(We<=yn+2){A!=="input"&&(A="input",Hi(),fo(),Di(),n.moveTo(uo(),Wt()),n.hideCursor(!1));return}let X=Ft(We);if(X===null)return;if(A==="input"){A="results",F=X,J=0,Bo(),pt(()=>{Di(),Hi(),fo(),n.hideCursor()});return}if(X!==F){Se(X);return}Q()},onResize:()=>vs()})},Gt=(L,ee,fe)=>{if(S!=="busy"){if(L==="CTRL_O"){xs();return}if(L==="CTRL_L"){Tf();return}if(S==="rename"&&Ge){if(L==="ENTER"||L==="KP_ENTER"){let Q=Ge.text.trim();if(Q.length===0){S="normal",I=null,Ge=null,Qe();return}Cd(Q);return}if(L==="ESCAPE"||L==="CTRL_C"){S="normal",I=null,Ge=null,Qe();return}if(Ge.handleKey(L,fe?.isCharacter===!0)){Qe();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(fe?.isCharacter&&(L==="y"||L==="Y")){Lf(S==="confirm-kill"?"kill":"delete");return}if(L==="ESCAPE"||L==="CTRL_C"||L==="ENTER"||L==="KP_ENTER"||fe?.isCharacter&&(L==="n"||L==="N")){S="normal",I=null,Qe();return}return}if(Nf(),It&&(It=!1,p=0,pt(()=>{wn(),yr()})),L==="CTRL_F"&&p!==0){wl();return}if(p===0&&!h){if(L==="ESCAPE"){Wo();return}if(L==="ENTER"||L==="KP_ENTER"){let X=Me.expandedText(),$e=tn();X.trim().length>0&&($e.prompt=X),$e.installStatus=Gr(),E($e);return}if(L==="CTRL_T"){qu()&&mo();return}if(L==="UP"&&b){let X=Date.now(),$e=X-k;if(k=X,$e<w){zn();return}b=!1}if(L==="DOWN"){let X=Me.state(),$e=X.historyIndex!==-1||X.queueIndex!==-1,_e=Wn.length===0||Ei===Wn.length-1;if(!$e&&_e&&d.length>0){Vn(1);return}}if(L==="PAGE_DOWN"&&(Wn.length===0||Ei===Wn.length-1)&&d.length>0){Vn(1);return}if(L==="CTRL_P"||L==="CTRL_N"){d.length>0&&Vn(1);return}if(b=!1,L==="TAB"){let X=Me.state(),$e=X.buffer[X.row]??"",_e=gg($e,X.col);if(_e!==null){let vt=yg(_e.token,s);if(vt!==null){if(vt.replacement!==_e.token&&(Me.replaceRangeOnCurrentLine(_e.start,X.col,vt.replacement),Cn()),vt.candidates.length>1){let St=vt.candidates.join(" ");de=`${vt.candidates.length} matches: ${St}`,Gn()}else On();zn();return}}}On();let Q=Me.state(),Se=[...Q.buffer],ze=Q.row,Ft=Q.col,Mt=null;if(L==="")Mt={type:"key",name:"ctrl-underscore"};else if(L==="\x1B_"||L==="\x1B")Mt={type:"key",name:"alt-underscore"};else if(fe?.isCharacter)Mt={type:"char",ch:L};else{let X=pg(L);if(X!==null){if(yd(X)){zn();return}Mt={type:"key",name:X}}}if(Mt===null){zn();return}let dn=Me.feed(Mt),ae=Me.state(),lt=Se.length===ae.buffer.length&&Se.every((X,$e)=>X===ae.buffer[$e])&&ze===ae.row&&Ft===ae.col;if(dn.some(X=>X.type==="exit")){Wo();return}for(let X of dn)X.type==="attachment-request"?Fn():X.type==="edit-in-editor"&&_f();if(lt){zn();return}let We=ms(ae.buffer,er);if(no(We,ae,uf).rendered!==gn){At();return}Cn();return}if(!h&&fe?.isCharacter&&L==="?"){Df();return}if(h){if(fe?.isCharacter){g+=L,In(),At();return}if(L==="BACKSPACE"){g.length>0?(g=g.slice(0,-1),In(),At()):(h=!1,In(),At());return}if(L==="ESCAPE"||L==="CTRL_C"){h=!1,g="",In(),At();return}}if(fe?.isCharacter){if(L==="/"){let Q=p>0?d[p-1]?.sessionId:void 0;h=!0,g="",In(),bs(Q),At();return}if(L==="n"||L==="N"){Vn(1);return}if(L==="p"||L==="P"){Vn(-1);return}if(L==="c"||L==="C"){let Q=tn();Q.installStatus=Gr(),E(Q);return}if(L==="q"||L==="Q"){Wo();return}if(L==="o"||L==="O"){let Q=p>0?d[p-1]?.sessionId:void 0;r.filters.cwdOnly=!r.filters.cwdOnly,In(),bs(Q),At();return}if(L==="h"||L==="H"){let Q=p>0?d[p-1]?.sessionId:void 0;r.filters.hostFilter=x_(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,In(),bs(Q),At();return}if(L==="i"&&p>0){let Q=d[p-1];if(!Q)return;Rd(Q);return}if(L==="I"){let Q=p>0?d[p-1]?.sessionId:void 0;r.filters.includeNonInteractive=!r.filters.includeNonInteractive,In(),bs(Q),At();return}if(L==="r"||L==="R"){let Q=p>0?d[p-1]?.sessionId:void 0;Ki(Q);return}if(L==="s"||L==="S"){Is();return}if((L==="v"||L==="V")&&p>0){let Q=d[p-1];if(!Q)return;let Se={kind:"attach",sessionId:Q.sessionId,readonly:!0};Q.agentId!==void 0&&(Se.agentId=Q.agentId),Se.installStatus=Gr(),E(Se);return}if((L==="f"||L==="F")&&p>0){let Q=d[p-1];if(!Q)return;rr();let Se={kind:"fork",sourceSessionId:Q.sessionId,sourceCwd:Q.cwd};Q.agentId!==void 0&&(Se.sourceAgentId=Q.agentId),Q.importedFromMachine!==void 0&&(Se.sourceImportedFromMachine=Q.importedFromMachine),Q.upstreamSessionId!==void 0&&(Se.sourceUpstreamSessionId=Q.upstreamSessionId),E(Se);return}if((L==="k"||L==="K")&&p>0){let Q=d[p-1];if(!Q)return;I={sessionId:Q.sessionId,cwd:Q.cwd,status:Q.status},S="confirm-kill",Qe();return}if(L==="t"&&p>0){let Q=d[p-1];if(!Q)return;I={sessionId:Q.sessionId,cwd:Q.cwd,status:Q.status},Ge=new vi(Q.title??""),S="rename",Qe();return}if(L==="T"&&p>0){let Q=d[p-1];if(!Q)return;Ln({sessionId:Q.sessionId});return}if(L==="*"&&p>0){let Q=d[p-1];if(!Q)return;Jn(Q);return}if((L==="d"||L==="D")&&p>0){let Q=d[p-1];if(!Q)return;I={sessionId:Q.sessionId,cwd:Q.cwd,status:Q.status},S="confirm-delete",Qe();return}It=!1,p=0,Me.feed({type:"char",ch:L}),At();return}switch(L){case"CTRL_T":{if(!qu())return;if(It||p===0){mo();return}let Q=d[p-1];if(!Q)return;Vr(Q);return}case"UP":case"SHIFT_TAB":case"CTRL_P":L==="UP"&&(p===1&&(b=!0),k=Date.now()),Vn(-1);return;case"DOWN":case"TAB":case"CTRL_N":Vn(1);return;case"PAGE_UP":Vn(-at);return;case"PAGE_DOWN":Vn(at);return;case"HOME":Vn(1-p);return;case"END":Vn(f);return;case"RIGHT":if(It||p===0)break;case"ENTER":case"KP_ENTER":{if(It){let ze=Me.expandedText(),Ft=tn();ze.trim().length>0&&(Ft.prompt=ze),Ft.installStatus=Gr(),E(Ft);return}if(p===0){let ze=tn();ze.installStatus=Gr(),E(ze);return}let Q=d[p-1];if(!Q){rr(),E({kind:"abort"});return}let Se={kind:"attach",sessionId:Q.sessionId};Q.agentId!==void 0&&(Se.agentId=Q.agentId),Se.installStatus=Gr(),E(Se);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Wo();return}}};pe({onKey:(L,ee,fe)=>Gt(L,ee,fe),onResize:()=>{Qt||At()}});let Yr=(L,ee)=>{if(Qt)return;if(oe.length!==1){oe[oe.length-1]?.onMouse?.(L,ee);return}if(S!=="normal")return;let fe=L==="MOUSE_MOTION",Q=L==="MOUSE_DRAG",Se=L==="MOUSE_LEFT_BUTTON_PRESSED",ze=L==="MOUSE_LEFT_BUTTON_RELEASED",Ft=L==="MOUSE_WHEEL_UP",Mt=L==="MOUSE_WHEEL_DOWN",dn=tt&&Date.now()-wd<Fg,ae=!tt||dn;if(Se){ho={x:ee?.x??-1,y:ee?.y??-1},Ui=ae;let Oe=ee?.x,Xe=ee?.y;!ae&&typeof Oe=="number"&&typeof Xe=="number"&&Xe>=$n&&Xe<=Zt()&&Cf({x:Oe,y:Xe});return}if(Q){if(mr!==null){let Oe=ee?.x,Xe=ee?.y;typeof Oe=="number"&&typeof Xe=="number"&&dd({x:Oe,y:Xe})}return}if(fe&&ae)return;let lt=ze&&ho!==null&&ee?.x===ho.x&&ee?.y===ho.y,We=lt&&!Ui,Te=lt&&Ui;if(ze&&mr!==null){ho=null,Ui=!1;let Oe=ee?.x,Xe=ee?.y;Do(typeof Oe=="number"&&typeof Xe=="number"?{x:Oe,y:Xe}:null);return}if(ze&&(ho=null,Ui=!1,!lt))return;if(Ft||Mt){if(d.length===0)return;let Oe=Ft?-3:3,Xe=Math.max(0,d.length-at),kn=Math.min(Xe,Math.max(0,m+Oe));if(kn===m)return;if(m=kn,p>0){let bl=p-1;bl<m?p=m+1:bl>=m+at&&(p=m+at)}yr();return}if(!fe&&!We)return;let X=ee?.y;if(typeof X!="number")return;{let Oe=ee?.x,Xe=bn!==null&&X===Be()&&typeof Oe=="number"&&Oe>=bn.start&&Oe<=bn.end,kn=Ss!==null&&X===Be()&&typeof Oe=="number"&&Oe>=Ss.start&&Oe<=Ss.end;(Xe!==Wi||kn!==Uo)&&(Wi=Xe,Uo=kn,Qe(),p===0?(zn(),n.hideCursor(!1)):n.hideCursor(!0))}if(We&&bn!==null&&X===Be()){let Oe=ee?.x;if(typeof Oe=="number"&&Oe>=bn.start&&Oe<=bn.end){Wo();return}}if(We&&Ss!==null&&X===Be()){let Oe=ee?.x;if(typeof Oe=="number"&&Oe>=Ss.start&&Oe<=Ss.end){let Xe=p>0?d[p-1]?.sessionId:void 0;r.filters.hostFilter=x_(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,In(),bs(Xe),At();return}}if(X>=$n&&X<=Zt()){let Oe=null;if(X===$n){let Xe=ee?.x;typeof Xe=="number"&&(Br!==null&&Xe>=Br.start&&Xe<=Br.end?Oe="agent":Oi!==null&&Xe>=Oi.start&&Xe<=Oi.end&&(Oe="cwd"))}if(Oe!==Xt&&(Xt=Oe,wn()),We&&X===$n){if(Xt==="agent"){Sd();return}if(Xt==="cwd"){xs();return}}if((We||Te)&&p!==0){It=!1;let Xe=p;p=0,pt(()=>{yr(),jo(Xe,p)});return}fe&&!It&&p!==0&&(It=!0,pt(()=>{wn(),yr()}));return}Xt!==null&&(Xt=null,wn()),It&&(It=!1,pt(()=>{wn(),yr()}));let _e=en()+1,vt=_e+at-1;if(X<_e||X>vt)return;let St=m+(X-_e);if(St<0||St>=d.length)return;let Yn=d[St];if(!Yn)return;let Qr=St+1;if(fe&&p===0)return;let cn=p===0,Rs=p===Qr;if(Te&&p!==Qr){let Oe=p;p=Qr,Dr(),pt(()=>{yr(),jo(Oe,p)});return}if(Te)return;if(p!==Qr){let Oe=p;p=Qr,Dr(),pt(()=>{yr(),jo(Oe,p)})}if(!We||cn||!Rs)return;let qo={kind:"attach",sessionId:Yn.sessionId};Yn.agentId!==void 0&&(qo.agentId=Yn.agentId),qo.installStatus=Gr(),E(qo)},wr=()=>{n.grabInput({mouse:"motion"}),ge({src:"grab",site:"picker.installGrab",on:!0});let L=n;L.stdin&&typeof L.onStdin=="function"&&(nr=L.onStdin,L.stdin.removeListener("data",L.onStdin),L.stdin.on("data",vd),we(ym),we(km)),n.on("key",qi),n.on("mouse",Yr),n.on("resize",ml)},Cs=()=>{we(Po),we(Nu);let L=n;L.stdin&&nr&&(L.stdin.removeListener("data",vd),L.stdin.on("data",nr),nr=null),po=!1,Kr="",n.off("key",qi),n.off("mouse",Yr),n.off("resize",ml),n.grabInput(!1),ge({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(wr(),fl=()=>{pl=!0,K&&(K.abort(),K=null,U=!1),Cs(),n.fullscreen(!1),we(`${Lu}${wm}`)},kd=()=>{pl=!1,n.fullscreen(!0),t(),n.hideCursor(),wr(),Qt||Tf()},process.platform!=="win32"){let L=!1,ee=()=>{L&&(L=!1,kd?.())};bd=()=>{L||Qt||(L=!0,fl?.(),we(`
|
|
280
|
+
`),process.once("SIGCONT",ee),process.kill(process.pid,"SIGTSTP"))}}M=setInterval(xd,3e3)})}function yG(n,e){let t="Create new session in ",r=Math.max(1,e-t.length);return t+Eu(V(n),r)}function vg(n,e){let t=s=>s.priority&&s.priority>0?s.priority:0,r=s=>{let o=s.status==="warm",i=t(s)>0;return o&&s.busy&&s.awaitingInput?6:o&&s.busy?5:o&&s.awaitingInput?4:o&&i?3:o?2:i?1:0};return[...n].sort((s,o)=>{let i=r(o)-r(s);if(i!==0)return i;let a=t(o)-t(s);return a!==0?a:o.updatedAt.slice(0,16).localeCompare(s.updatedAt.slice(0,16))})}function wG(n,e){return n?e.has(n):!0}function eS(n){return!!n.importedFromMachine&&!n.upstreamSessionId}function bG(n,e,t=Sp()){if(e==="__all")return n;let r=o=>!o.remote&&(wG(o.importedFromMachine,t)||!!o.upstreamSessionId);if(e==="__local")return n.filter(r);if(e==="__remotes")return n.filter(o=>o.remote?!eS(o):r(o));if(e.startsWith(Ci)){let o=e.slice(Ci.length);return n.filter(i=>i.remote===o&&!eS(i))}let s=e.startsWith(Ya)?e.slice(Ya.length):e;return n.filter(o=>o.importedFromMachine===s&&!t.has(s)&&!o.upstreamSessionId)}function x_(n,e,t=Sp()){let r=I_(e,t),s=r.indexOf(n);return s===-1?"__local":r[(s+1)%r.length]??"__local"}function I_(n,e){let t=new Set,r=new Set;for(let s of n){if(s.remote){eS(s)||t.add(s.remote);continue}s.importedFromMachine&&!s.upstreamSessionId&&!e.has(s.importedFromMachine)&&r.add(s.importedFromMachine)}return["__local",...t.size>0?["__remotes"]:[],...[...t].sort().map(s=>`${Ci}${s}`),...[...r].sort().map(s=>`${Ya}${s}`),"__all"]}function kG(n,e,t=Sp()){if(n==="all")return"__all";let r=I_(e,t),s;return n===`${Ci}all`?s=["__remotes"]:n.startsWith(Ci)||n.startsWith(Ya)?s=[n]:s=[`${Ci}${n}`,`${Ya}${n}`],s.find(o=>r.includes(o))??"__local"}function vG(n){return n==="__local"?"host: local":n==="__remotes"?"host: local + remotes":n.startsWith(Ci)?`remote: ${n.slice(Ci.length)}`:n.startsWith(Ya)?`host: ${n.slice(Ya.length)}`:`host: ${n}`}function SG(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),r=[st(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,V(n.cwd)];for(let s of r)if(s.toLowerCase().includes(t))return!0;return!1}var kg,uf,hG,v_,mG,S_,Ci,Ya,C_=q(()=>{"use strict";Nc();zl();Os();ke();ir();rt();wo();Hm();Wa();Ku();Tu();Vk();rh();qm();zm();nv();Gv();Vv();Yv();Dm();Qv();Na();Du();Xv();rv();Tv();Fa();Tn();ma();ik();na();Zv();kg=2,uf=4,hG=4,v_=4,mG=20,S_=[["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)"],[" in results","n/p cycle snippets \xB7 i info \xB7 Enter open"],[" ","the query and results survive opening a hit"],["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)"]];Ci="remote:",Ya="host:"});function xG(n){let e=n.explicitAgentId??n.directoryDefaultAgent??n.prefs.lastChosenAgent??n.fallbackAgentId??n.configDefaultAgent;if(e===void 0||e.length===0)return{};let t=n.availableAgents.find(i=>i.id===e)?.extendsChain,r={id:e,...t?{extendsChain:t}:{}},s=e===n.prefs.lastChosenAgent?n.prefs.lastChosenModel:void 0,o=xr(n.directoryDefaultModels,r)?.value??s??xr(n.configDefaultModels,r)?.value;return{agentId:e,...o!==void 0?{model:o}:{}}}function R_(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n))typeof r.model=="string"&&(e[t]=r.model);return Object.keys(e).length>0?e:void 0}async function ff(n){let e={},t;try{let i=await Tl(n.cwd);e=i.merged,t=i.homeRequest}catch{}let r=Jf(e,"defaultAgent"),s=R_(Vf(e,"sessionDefaults")),o=xG({...n.explicitAgentId!==void 0?{explicitAgentId:n.explicitAgentId}:{},...r!==void 0?{directoryDefaultAgent:r}:{},...s!==void 0?{directoryDefaultModels:s}:{},prefs:n.prefs,...n.fallbackAgentId!==void 0?{fallbackAgentId:n.fallbackAgentId}:{},configDefaultAgent:n.config.defaultAgent,configDefaultModels:R_(n.config.sessionDefaults),availableAgents:n.availableAgents});return t!==void 0&&t!==Le()?{...o,notice:`that directory sets home: ${t} \u2014 run hydra there for a separate daemon`}:o}var A_=q(()=>{"use strict";ke();Od();Os()});import IG from"wrap-ansi";async function T_(n,e,t,r){ls();let s=r?.canGoBack!==!1,o=e?`Couldn't start ${e}`:"Couldn't start session",i=t.split(`
|
|
281
|
+
`).map(c=>c.trimEnd()).filter(c=>c.length>0),a=s?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",d=()=>{let c=xn(n),l=Ys(n),u=Math.min(CG,Math.max(20,c-4)),f=Math.max(1,u-1),p=i.flatMap(I=>IG(I,f,{hard:!0,trim:!1}).split(`
|
|
282
|
+
`)),m=Math.max(1,l-4-4),h=p.length>m,g=h?p.slice(0,m-1):p,w=g.length+(h?1:0)+4,b=pr(n,{contentHeight:w,contentWidth:u,title:"Agent failed to start"}),k=b.contentW,S=0;n.moveTo(b.contentX,b.contentY+S),B(n,"modal-title",_t(` ${o}`,k)),S+=2;for(let I of g)n.moveTo(b.contentX,b.contentY+S),B(n,"modal-error",_t(` ${I}`,k)),S++;return h&&(n.moveTo(b.contentX,b.contentY+S),B(n,"modal-hint",_t(" \u2026 (full details in ~/.hydra-acp/tui.log)",k)),S++),S++,n.moveTo(b.contentX,b.contentY+S),B(n,"modal-hint",_t(` ${a}`,k)),b};return Qs({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(s?"back":"cancel");return}c==="CTRL_C"&&f("cancel")}})}var CG,E_=q(()=>{"use strict";Na();Tn();CG=100});import{exec as RG}from"child_process";function Sg(n){let e=n.exec??AG,t=new Set,r=new Map,s=o=>{t.add(o);let i=n.envFor?.(o);e(o,{cwd:n.cwd()??void 0,timeout:TG,maxBuffer:EG,env:i?{...process.env,...i}:void 0},(a,d)=>{t.delete(o),n.onOutput(o,a?null:n.sanitize(d))})};return{poll(o,i){for(let[a,d]of o){if(t.has(a))continue;let c=r.get(a);c!==void 0&&i-c<d||(r.set(a,i),s(a))}}}}var AG,TG,EG,rS=q(()=>{"use strict";AG=(n,e,t)=>{RG(n,e,(r,s)=>t(r,s))},TG=3e3,EG=64*1024});function sS(n,e){let t=new Map,r=s=>{for(let o of s){if(typeof o=="string"||o.script===void 0)continue;let i=o.refreshMs??e,a=t.get(o.script);t.set(o.script,a===void 0?i:Math.min(a,i))}};return r(n.composer.top.left),r(n.composer.top.right),r(n.composer.bottom.left),r(n.composer.bottom.right),r(n.sessionbar.left),r(n.sessionbar.right),t}function PG(n){let e=n.trim().replace(/\s+/g," ");return e.length===0?null:e}function P_(n){return Sg({cwd:n.cwd,envFor:n.envFor,sanitize:PG,onOutput:n.onOutput,exec:n.exec})}var M_=q(()=>{"use strict";rS()});async function MG(n,e){try{let t=await fetch(`${n.baseUrl}/v1/process-tokens`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({sessionLabel:e}),signal:AbortSignal.timeout(3e3)});if(!t.ok)return;let r=await t.json();return typeof r.token=="string"?r.token:void 0}catch{return}}async function __(n,e,t){let r=new Map;return await Promise.all([...t.keys()].map(async s=>{let o=await MG(n,e);o&&r.set(s,o)})),r}async function $_(n,e){try{await fetch(`${n.baseUrl}/v1/process-tokens/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`},signal:AbortSignal.timeout(3e3)})}catch{}}var O_=q(()=>{"use strict"});function pf(n){if(typeof n!="string")return null;let e=n.trim();return e.length>0?e:null}function F_(n){if(!n||typeof n!="object")return{origin:"client",label:null};let e=n,t=pf(e.fromSession);return t?{origin:"peer",label:pf(e.fromSessionTitle)??pf(e.fromLabel)??t}:{origin:"client",label:pf(e.fromLabel)??pf(e.name)}}var L_=q(()=>{"use strict"});function N_(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 r=t._meta;if(r&&typeof r=="object"){let s=r["hydra-acp"];if(s&&typeof s=="object"){let o=s,i=o.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i),typeof o.armedSince=="number"&&o.armedSince>0&&(e.armedSince=o.armedSince),typeof o.armedTasks=="number"&&o.armedTasks>=0&&(e.armedTasks=o.armedTasks),Array.isArray(o.armedTaskList)&&(e.armedTaskList=o.armedTaskList)}}return e}function D_(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function B_(n){return!n.blockOpen&&n.isStart}function H_(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 U_=q(()=>{"use strict"});function xg(n){let e=Zo(n);if(e===null)throw new Error(`built-in theme has a malformed colour: ${n}`);return e}function _n(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=xg(s);return t.bg=xg(e.bg),t.fg=xg(e.fg),t}function Or(n){return{fg:xg(n)}}function hr(n){return{fg:gt(n)}}function oS(n){return W_.find(e=>e.name===n)}function iS(){return W_.map(n=>n.name)}function j_(n){return n===void 0?"terminal":Jd(n)?VG:YG}function q_(n,e,t){if(n.length===0)return;let r=n.indexOf(e);return r===-1?t===1?n[0]:n[n.length-1]:n[(r+t+n.length)%n.length]}var _G,$G,OG,FG,LG,NG,DG,BG,HG,UG,WG,jG,qG,Nt,zG,KG,GG,JG,W_,VG,YG,aS=q(()=>{"use strict";Yd();Tn();_G=_n({black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff5555",brightGreen:"#50fa7b",brightYellow:"#f1fa8c",brightBlue:"#bd93f9",brightMagenta:"#ff79c6",brightCyan:"#8be9fd",brightWhite:"#ffffff"},{bg:"#282a36",fg:"#f8f8f2"}),$G=_n({black:"#3b4252",red:"#bf616a",green:"#a3be8c",yellow:"#ebcb8b",blue:"#81a1c1",magenta:"#b48ead",cyan:"#88c0d0",white:"#e5e9f0",brightBlack:"#4c566a",brightRed:"#bf616a",brightGreen:"#a3be8c",brightYellow:"#ebcb8b",brightBlue:"#81a1c1",brightMagenta:"#b48ead",brightCyan:"#8fbcbb",brightWhite:"#eceff4"},{bg:"#2e3440",fg:"#d8dee9"}),OG=_n({black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},{bg:"#282828",fg:"#ebdbb2"}),FG=_n({black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#657b83",brightBlack:"#93a1a1",brightRed:"#cb4b16",brightGreen:"#859900",brightYellow:"#b58900",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#073642"},{bg:"#fdf6e3",fg:"#657b83"}),LG=(()=>{let n={};for(let e of Object.keys(ia))n[e]=gt(7);return n})(),NG=_n({black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#93a1a1",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#859900",brightYellow:"#b58900",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#fdf6e3"},{bg:"#002b36",fg:"#839496"}),DG=_n({black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#6c7086",brightRed:"#eba0ac",brightGreen:"#a6e3a1",brightYellow:"#fab387",brightBlue:"#b4befe",brightMagenta:"#cba6f7",brightCyan:"#89dceb",brightWhite:"#cdd6f4"},{bg:"#1e1e2e",fg:"#cdd6f4"}),BG=_n({black:"#51576d",red:"#e78284",green:"#a6d189",yellow:"#e5c890",blue:"#8caaee",magenta:"#f4b8e4",cyan:"#81c8be",white:"#b5bfe2",brightBlack:"#737994",brightRed:"#ea999c",brightGreen:"#a6d189",brightYellow:"#ef9f76",brightBlue:"#babbf1",brightMagenta:"#ca9ee6",brightCyan:"#99d1db",brightWhite:"#c6d0f5"},{bg:"#303446",fg:"#c6d0f5"}),HG=_n({black:"#494d64",red:"#ed8796",green:"#a6da95",yellow:"#eed49f",blue:"#8aadf4",magenta:"#f5bde6",cyan:"#8bd5ca",white:"#b8c0e0",brightBlack:"#6e738d",brightRed:"#ee99a0",brightGreen:"#a6da95",brightYellow:"#f5a97f",brightBlue:"#b7bdf8",brightMagenta:"#c6a0f6",brightCyan:"#91d7e3",brightWhite:"#cad3f5"},{bg:"#24273a",fg:"#cad3f5"}),UG=_n({black:"#ccd0da",red:"#d20f39",green:"#40a02b",yellow:"#df8e1d",blue:"#1e66f5",magenta:"#ea76cb",cyan:"#179299",white:"#5c5f77",brightBlack:"#8c8fa1",brightRed:"#e64553",brightGreen:"#40a02b",brightYellow:"#fe640b",brightBlue:"#7287fd",brightMagenta:"#8839ef",brightCyan:"#04a5e5",brightWhite:"#4c4f69"},{bg:"#eff1f5",fg:"#4c4f69"}),WG=_n({black:"#ebdbb2",red:"#9d0006",green:"#79740e",yellow:"#b57614",blue:"#076678",magenta:"#8f3f71",cyan:"#427b58",white:"#504945",brightBlack:"#7c6f64",brightRed:"#cc241d",brightGreen:"#98971a",brightYellow:"#af3a03",brightBlue:"#458588",brightMagenta:"#b16286",brightCyan:"#689d6a",brightWhite:"#3c3836"},{bg:"#fbf1c7",fg:"#3c3836"}),jG=_n({black:"#414868",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#565f89",brightRed:"#ff757f",brightGreen:"#73daca",brightYellow:"#ff9e64",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#2ac3de",brightWhite:"#c0caf5"},{bg:"#1a1b26",fg:"#c0caf5"}),qG=_n({black:"#3f4451",red:"#e05561",green:"#8cc265",yellow:"#d18f52",blue:"#4aa5f0",magenta:"#c162de",cyan:"#42b3c2",white:"#abb2bf",brightBlack:"#5c6370",brightRed:"#ff616e",brightGreen:"#a5e075",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#e6e6e6"},{bg:"#282c34",fg:"#abb2bf"}),Nt={orange:"#e69f00",skyBlue:"#56b4e9",bluishGreen:"#009e73",yellow:"#f0e442",blue:"#0072b2",vermillion:"#d55e00",reddishPurple:"#cc79a7"},zG=_n({black:"#3a3a3a",red:Nt.reddishPurple,green:Nt.bluishGreen,yellow:Nt.orange,blue:Nt.blue,magenta:Nt.reddishPurple,cyan:Nt.skyBlue,white:"#d0d0d0",brightBlack:"#8a8a8a",brightRed:Nt.vermillion,brightGreen:Nt.bluishGreen,brightYellow:Nt.yellow,brightBlue:Nt.skyBlue,brightMagenta:Nt.reddishPurple,brightCyan:Nt.skyBlue,brightWhite:"#f0f0f0"},{bg:"#1c1c1c",fg:"#d0d0d0"});KG=_n({black:"#090618",red:"#c34043",green:"#76946a",yellow:"#c0a36e",blue:"#7e9cd8",magenta:"#957fb8",cyan:"#6a9589",white:"#c8c093",brightBlack:"#727169",brightRed:"#e82424",brightGreen:"#98bb6c",brightYellow:"#e6c384",brightBlue:"#7fb4ca",brightMagenta:"#938aa9",brightCyan:"#7aa89f",brightWhite:"#dcd7ba"},{bg:"#1f1f28",fg:"#dcd7ba"}),GG=_n({black:"#343f44",red:"#e67e80",green:"#a7c080",yellow:"#e69875",blue:"#7fbbb3",magenta:"#d699b6",cyan:"#83c092",white:"#d3c6aa",brightBlack:"#859289",brightRed:"#e67e80",brightGreen:"#a7c080",brightYellow:"#dbbc7f",brightBlue:"#7fbbb3",brightMagenta:"#d699b6",brightCyan:"#83c092",brightWhite:"#d3c6aa"},{bg:"#2d353b",fg:"#d3c6aa"}),JG=_n({black:"#141c12",red:"#ff4b4b",green:"#1cc24b",yellow:"#e6ff57",blue:"#30b3ff",magenta:"#c770ff",cyan:"#24f6d9",white:"#2eff6a",brightBlack:"#8ca391",brightRed:"#ff4b4b",brightGreen:"#2eff6a",brightYellow:"#ffa83d",brightBlue:"#30b3ff",brightMagenta:"#c770ff",brightCyan:"#00efff",brightWhite:"#62ff94"},{bg:"#0a0e0a",fg:"#62ff94"}),W_=[{name:"terminal",description:"your terminal's own 16 colours (default)",palette:ia},{name:"dracula",description:"dark, high contrast, purple-leaning",palette:_G},{name:"nord",description:"dark, cool, low contrast",palette:$G},{name:"gruvbox-dark",description:"dark, warm, retro",counterpart:"gruvbox-light",palette:OG},{name:"catppuccin-mocha",description:"dark, soft pastel (the default on a dark terminal)",counterpart:"catppuccin-latte",palette:DG},{name:"catppuccin-macchiato",description:"dark, soft pastel, one step lighter than mocha",counterpart:"catppuccin-latte",palette:HG},{name:"catppuccin-frappe",description:"dark, soft pastel, the lightest of the dark flavours",counterpart:"catppuccin-latte",palette:BG},{name:"catppuccin-latte",description:"light, soft pastel (the default on a light terminal)",counterpart:"catppuccin-mocha",palette:UG},{name:"tokyo-night",description:"dark, deep blue",palette:jG},{name:"one-dark",description:"dark, the Atom default",palette:qG},{name:"kanagawa",description:"dark, muted ink tones",palette:KG},{name:"everforest",description:"dark, warm green, gentle contrast",palette:GG},{name:"matrix",description:"dark, green on black",palette:JG},{name:"gruvbox-light",description:"light, warm, retro",counterpart:"gruvbox-dark",palette:WG},{name:"colorblind",description:"dark, no meaning carried on the red/green axis",palette:zG,roles:{ok:Or(Nt.skyBlue),error:Or(Nt.vermillion),errorSoft:Or(Nt.vermillion),warn:Or(Nt.orange),active:Or(Nt.yellow),cold:Or(Nt.reddishPurple),diffAdded:Or(Nt.skyBlue),diffRemoved:Or(Nt.vermillion),gitStaged:Or(Nt.blue),gitDirty:Or(Nt.orange),syntaxRegexp:Or(Nt.reddishPurple),syntaxNumber:Or(Nt.skyBlue)}},{name:"solarized-dark",description:"dark, low contrast",counterpart:"solarized-light",palette:NG},{name:"solarized-light",description:"light",counterpart:"solarized-dark",palette:FG},{name:"mono",description:"no colour; weight and glyphs only",palette:LG,roles:{subtle:hr(8),muted:hr(8),fg:hr(7),fgStrong:hr(15),active:hr(15),error:hr(15),warn:hr(15),ok:hr(7),cold:hr(7),accent:hr(15),info:hr(7),reference:hr(15),focus:hr(15),selection:{bg:gt(8),fg:gt(15)},selectionBand:{bg:gt(8)},cursor:{bg:gt(15),fg:gt(0)},promptCursor:{bg:gt(15),fg:gt(0)},match:{bg:gt(15),fg:gt(0)},matchActive:{bg:gt(7),fg:gt(0)}}}];VG="catppuccin-mocha",YG="catppuccin-latte"});import{readdir as QG,readFile as XG}from"fs/promises";import{join as V_}from"path";function ZG(n,e,t,r){let s=(c,l)=>{if(c===void 0)return;if(typeof c!="string")return r.push(`${e}${l}: must be a colour string, got ${Ig(c)}`),null;let u=Zo(c);return u===null?(r.push(`${e}${l}: is not a colour ("${c}") \u2014 expected #rgb, #rrggbb, or rgb(r,g,b)`),null):u};if(typeof n=="string"){let c=s(n,"");return c==null?null:t?{fg:c}:{bg:c}}if(typeof n!="object"||n===null||Array.isArray(n))return r.push(`${e}: must be a colour string or { fg, bg }, got ${Ig(n)}`),null;let o=n;for(let c of Object.keys(o))c!=="fg"&&c!=="bg"&&r.push(`${e}: unknown key "${c}" \u2014 expected fg or bg`);let i=s(o.fg,".fg"),a=s(o.bg,".bg");if(i===null||a===null)return null;if(i===void 0&&a===void 0)return r.push(`${e}: needs at least one of fg or bg`),null;let d={};return i!==void 0&&(d.fg=i),a!==void 0&&(d.bg=a),d}function G_(n,e,t,r,s,o){let i={};if(n===void 0)return i;if(typeof n!="object"||n===null||Array.isArray(n))return o.push(`${t}: ${e} must be an object`),i;let a=new Set(r);for(let[d,c]of Object.entries(n)){if(!a.has(d)){let u=r.filter(f=>f.includes(d)||d.includes(f));o.push(`${t}: unknown ${e==="roles"?"role":"element"} "${d}"`+(u.length>0?` \u2014 did you mean ${u.slice(0,4).join(", ")}?`:"")+` (${r.length} available)`);continue}let l=ZG(c,`${t}: ${e}.${d}`,s(d),o);l!==null&&(i[d]=l)}return i}async function dS(n,e){let t=[],r=()=>({palette:ia,overrides:{roles:{},elements:{}},name:"terminal",problems:t});return n==null?r():typeof n=="string"?await Y_(n,e,t,new Set)??r():typeof n!="object"||Array.isArray(n)?(t.push(`tui.theme must be a theme name or an object, got ${Ig(n)}`),r()):{...await Q_(n,"tui.theme",e,t,new Set),name:"custom",problems:t}}function Ig(n){return Array.isArray(n)?"an array":typeof n}async function Y_(n,e,t,r){if(r.has(n))return t.push(`theme "${n}": extends forms a cycle`),null;r.add(n);let s=await e4(n,e,t);if(s!==null)return{...await Q_(s,`theme "${n}"`,e,t,r),name:n,problems:t};let o=oS(n);return o!==void 0?{palette:o.palette,overrides:{roles:{...o.roles??{}},elements:{}},name:n,problems:t}:(t.push(`unknown theme "${n}" \u2014 expected one of ${iS().join(", ")}, or a file at ${V_(e,`${n}.json`)}`),null)}async function e4(n,e,t){if(!/^[A-Za-z0-9._-]+$/.test(n)||n.startsWith("."))return null;let r=V_(e,`${n}.json`),s;try{s=await XG(r,"utf8")}catch{return null}try{let o=JSON.parse(s);return typeof o!="object"||o===null||Array.isArray(o)?(t.push(`theme file ${r}: expected a JSON object`),null):o}catch(o){return t.push(`theme file ${r}: ${o.message.split(`
|
|
283
283
|
`)[0]}`),null}}async function Q_(n,e,t,r,s){let o=ia,i={roles:{},elements:{}};if(n.extends!==void 0)if(typeof n.extends!="string")r.push(`${e}: extends must be a theme name`);else{let d=await Y_(n.extends,t,r,s);d!==null&&(o=d.palette,Object.assign(i.roles,d.overrides.roles),Object.assign(i.elements,d.overrides.elements))}let a={...o};if(n.palette!==void 0)if(typeof n.palette!="object"||n.palette===null||Array.isArray(n.palette))r.push(`${e}: palette must be an object`);else{let d=new Set([...z_,...K_]);for(let[c,l]of Object.entries(n.palette)){if(!d.has(c)){r.push(`${e}: unknown palette slot "${c}" \u2014 expected one of ${[...z_,...K_].join(", ")}`);continue}if(typeof l!="string"){r.push(`${e}: palette.${c} must be a colour string, got ${Ig(l)}`);continue}let u=Zo(l);if(u===null){r.push(`${e}: palette.${c} is not a colour ("${l}") \u2014 expected #rgb, #rrggbb, or rgb(r,g,b)`);continue}a[c]=u}}return Object.assign(i.roles,G_(n.roles,"roles",e,Qx(),Zx,r)),Object.assign(i.elements,G_(n.elements,"elements",e,Xx(),eI,r)),{palette:a,overrides:i}}async function X_(n){let e=[...iS()];try{for(let r of await QG(n)){if(!r.endsWith(".json"))continue;let s=r.slice(0,-5);e.includes(s)||e.push(s)}}catch{}let t=[];for(let r of e){let s=await dS(r,n);t.push({name:r,palette:s.palette,overrides:s.overrides})}return t}function Z_(n,e,t=process.env,r){if(n!=null)if(typeof n!="string")e.push(`tui.themeBackground must be "dark", "light", or a colour, got ${typeof n}`);else{let o=J_(n.trim().toLowerCase());if(o!==void 0)return o;let i=Zo(n);if(i!==null)return i;e.push(`tui.themeBackground is not "dark", "light", or a colour ("${n}")`)}if(r!==void 0)return r;let s=Fx(t);return s===void 0?void 0:J_(s)}function cS(n,e,t){if(t===void 0||n.bg===void 0)return;let r=Jd(t),s=Jd(n.bg);if(r===s)return;let o=oS(e)?.counterpart,i=o===void 0?"":` \u2014 try "${o}" instead`;return r?`"${e}" is a light theme and this terminal is dark${i}`:`"${e}" is a dark theme and this terminal is light${i}`}function J_(n){if(n==="dark")return Dn(0,0,0);if(n==="light")return Dn(255,255,255)}var z_,K_,e$=q(()=>{"use strict";sa();aS();Yd();Tn();z_=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"],K_=["bg","fg"]});import{resolve as t4}from"path";function r4(n,e){let t=0;for(let r=0;r<e;r++){let s=n.indexOf(" ",t);if(s===-1)return"";t=s+1}return n.slice(t)}function s4(){return{branch:null,staged:0,unstaged:0,untracked:0,ahead:0,behind:0,files:[]}}function t$(n,e){let t=s4(),r=(s,o)=>{e===null||s===""||t.files.push({path:t4(e,s),state:o})};for(let s of n.split(`
|
|
284
284
|
`)){if(s.startsWith("# branch.head ")){let u=s.slice(14).trim();t.branch=u==="(detached)"?null:u;continue}if(s.startsWith("# branch.ab ")){let u=/\+(\d+) -(\d+)/.exec(s);u!==null&&(t.ahead=Number(u[1]),t.behind=Number(u[2]));continue}if(s.startsWith("? ")){t.untracked++,r(s.slice(2),"new");continue}let o=s.slice(0,1),i=n4[o];if(i===void 0||s[1]!==" ")continue;let a=s.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=r4(s,i).split(" ")[0]??"";r(l,c?"dirty":"staged")}return t}var n4,n$=q(()=>{"use strict";n4={1:8,2:9,u:10}});import{resolve as o4}from"path";function i4(n,e){return e!==void 0||oC(n.rawKind)}function r$(n,e,t){if(n.status!=="completed"||!i4(n,e))return null;let r=e?.path??Ip(n.locations);if(r===void 0||r==="")return null;let s=e===void 0?void 0:Xb(e);return{path:t===null?r:o4(t,r),added:s?.added,removed:s?.removed}}function s$(n){let e=new Map;for(let t of n){let r=e.get(t.path);if(r===void 0){e.set(t.path,{...t});continue}t.added!==void 0&&(r.added=(r.added??0)+t.added),t.removed!==void 0&&(r.removed=(r.removed??0)+t.removed),e.delete(t.path),e.set(t.path,r)}return[...e.values()]}var o$=q(()=>{"use strict";Jl();To()});function i$(n){if(n===null||typeof n!="object")return null;let t=n.rawInput;if(t===null||typeof t!="object")return null;let r=t.todos;if(!Array.isArray(r))return null;let s=[];for(let o of r){if(o===null||typeof o!="object")continue;let{content:i,status:a,priority:d}=o;if(typeof i!="string"||i.length===0)continue;let c={content:i,status:typeof a=="string"&&a4.has(a)?a:"pending"};typeof d=="string"&&d.length>0&&(c.priority=d),s.push(c)}return s}var a4,a$=q(()=>{"use strict";a4=new Set(["pending","in_progress","completed"])});import{readdirSync as d4,readFileSync as c4}from"fs";function lS(n){let e=n.lastIndexOf(")");if(e===-1)return null;let t=Number(n.slice(0,n.indexOf(" "))),r=n.slice(e+2).split(" "),s=Number(r[1]),o=Number(r[11]),i=Number(r[12]),a=Number(r[13]),d=Number(r[14]);if(!Number.isInteger(t)||!Number.isInteger(s)||!Number.isFinite(o)||!Number.isFinite(i))return null;let c=Number.isFinite(a)&&Number.isFinite(d)?(a+d)/d$:void 0;return{pid:t,ppid:s,rssBytes:0,cpuSeconds:(o+i)/d$,...c===void 0?{}:{childCpuSeconds:c}}}function l4(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 c$(n,e,t){if(e===null||t<=0)return;let r=n.user-e.user+(n.system-e.system);return Math.max(0,r/1e3/t)}function u4(n){let e=new Map;for(let t of n.split(`
|
|
285
|
-
`)){let r=t.trim().split(/\s+/);if(r.length<4)continue;let s=Number(r[0]),o=Number(r[1]),i=Number(r[2]),a=f4(r[3]);!Number.isInteger(s)||!Number.isInteger(o)||!Number.isFinite(i)||a===null||e.set(s,{pid:s,ppid:o,rssBytes:i*1024,cpuSeconds:a})}return e}function f4(n){let e=n,t=0,r=e.indexOf("-");if(r!==-1){let i=e.slice(0,r);if(i.length===0||(t=Number(i),e=e.slice(r+1),!Number.isInteger(t)||t<0))return null}let s=e.split(":");if(s.length<2||s.length>3)return null;let o=0;for(let i of s){let a=Number(i);if(!Number.isFinite(a)||a<0)return null;o=o*60+a}return t*86400+o}function uS(n,e){let t=new Map;for(let o of n.values()){let i=t.get(o.ppid);i===void 0?t.set(o.ppid,[o.pid]):i.push(o.pid)}let r=new Set;if(!n.has(e))return r;let s=[e];for(;s.length>0;){let o=s.pop();if(!r.has(o)){r.add(o);for(let i of t.get(o)??[])r.has(i)||s.push(i)}}return r}function l$(n,e,t){let r=uS(n.rows,t);if(r.size===0)return null;let s=0,o=0,i=!1;for(let c of r){if(n.rssKnown!==void 0&&!n.rssKnown.has(c))return null;let l=n.rows.get(c);s+=l.rssBytes;let u=e?.rows.get(c);u!==void 0&&(i=!0,o+=Math.max(0,l.cpuSeconds-u.cpuSeconds))}i&&e!==null&&(o+=p4(n,e,r,t));let a={processes:r.size,rssBytes:s},d=e===null?0:n.at-e.at;return i&&d>0&&(a.cpuFraction=Math.max(0,o)/(d/1e3)),a}function p4(n,e,t,r){let s=0,o=!1;for(let i of t){let a=n.rows.get(i).childCpuSeconds,d=e.rows.get(i)?.childCpuSeconds;a===void 0||d===void 0||(o=!0,s+=Math.max(0,a-d))}if(!o)return 0;for(let i of uS(e.rows,r)){if(t.has(i))continue;let a=e.rows.get(i);a!==void 0&&a.childCpuSeconds!==void 0&&(s-=a.cpuSeconds+a.childCpuSeconds)}return s}async function h4(n,e,t){let r=[],s;try{s=await e(`/proc/${n}/task`)}catch{return r}for(let o of s){if(!/^\d+$/.test(o))continue;let i;try{i=await t(`/proc/${n}/task/${o}/children`)}catch{continue}for(let a of i.split(/\s+/)){if(a.length===0)continue;let d=Number(a);Number.isInteger(d)&&d>0&&r.push(d)}}return r}async function m4(n,e,t){let r=new Map,s=new Set;for(let o of n){if(s.has(o))continue;let i;try{i=await t(`/proc/${o}/stat`)}catch{continue}try{await t(`/proc/${o}/task/${o}/children`)}catch{return null}let a=lS(i);if(a===null)continue;r.set(o,a),s.add(o);let d=[o];for(;d.length>0;){let c=d.pop();for(let l of await h4(c,e,t)){if(s.has(l))continue;s.add(l);let u;try{u=lS(await t(`/proc/${l}/stat`))}catch{continue}u!==null&&(r.set(l,u),d.push(l))}}}return r}async function g4(n,e){let t=new Map,r;try{r=await n("/proc")}catch{return t}return await Promise.all(r.map(async s=>{if(/^\d+$/.test(s))try{let o=lS(await e(`/proc/${s}/stat`));o!==null&&t.set(o.pid,o)}catch{}})),t}async function y4(n,e,t){for(let r of e){let s=n.get(r);if(s!==void 0)try{let o=l4(await t(`/proc/${r}/status`));o!==null&&(s.rssBytes=o)}catch{}}}async function u$(n,e={}){let t=e.platform??process.platform,r=Date.now();if(t==="linux"){let o=e.readDir??(l=>d4(l)),i=e.readFile??(l=>c4(l,"utf8")),a=await m4(n,o,i),d=a??await g4(o,i),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 uS(d,l))c.add(u);return await y4(d,c,i),{at:r,rows:d,rssKnown:c}}let s=e.runPs??(async()=>{let{execFile:o}=await import("child_process"),{promisify:i}=await import("util"),{stdout:a}=await i(o)("ps",["-A","-o","pid=,ppid=,rss=,time="],{timeout:5e3,maxBuffer:8*1024*1024});return a});try{return{at:r,rows:u4(await s())}}catch{return{at:r,rows:new Map}}}var d$,f$=q(()=>{"use strict";d$=100});import{mkdtempSync as w4,readFileSync as b4,rmSync as k4}from"fs";import{tmpdir as v4}from"os";import{performance as S4}from"perf_hooks";import{writeHeapSnapshot as x4}from"v8";import{nanoid as gS}from"nanoid";import I4 from"terminal-kit";import fS from"fs/promises";import Ri from"path";import{execFile as p$}from"child_process";function C4(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function R4(n){let e=Ag(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function A4(n){let e=new Map,t=[];for(let r of n){let s=r.question,o=e.get(s);o?o.ids.push(r.id):(e.set(s,{representative:r,ids:[r.id]}),t.push(s))}return t.map(r=>e.get(r))}function Ag(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 pS(n){let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t;typeof r.label!="string"||typeof r.since!="number"||e.push({label:r.label,since:r.since,...typeof r.taskId=="string"?{taskId:r.taskId}:{},...typeof r.taskType=="string"?{taskType:r.taskType}:{}})}return e}function T4(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function I$(n,e,t,r,s=60){let o=n.map((i,a)=>{let d=Ag(i.representative),c=e[a]??0,l=t[a]?yS:d[c]??d[0]??"",u=T4(i.representative.question,s);return{id:i.representative.id,kind:"select",label:u,value:l}});return{title:`Open questions (${n.length})`,rows:o,cursor:Math.max(0,Math.min(n.length-1,r)),hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 cycle"},{label:"d dismiss",action:"dismiss"},{label:"1-9 jump"},{label:"\u23CE/Esc save",action:"commit"},{label:"^C discard",action:"cancel"}]}}function E4(n,e,t){return n===yS?{type:"dismiss",method:SP,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:vP,params:{sessionId:t,questionId:e.id,answer:n}}}function C$(n,e,t,r,s){let o=[];for(let i=0;i<n.length;i++){let a=n[i];if(!a||!t[i])continue;let d=r[i]?yS:Ag(a.representative)[e[i]??0]??"";if(d)for(let c of a.ids){let l={...a.representative,id:c},u=E4(d,l,s);u!==null&&o.push(u)}}return o}function P4(n,e,t,r,s,o,i,a){if(!e||t===null||t.length===0)return{type:"noop"};let d=()=>({type:"save",dispatches:C$(t,r,s,o,a)});if(n.type==="key"&&n.name==="ctrl-q")return d();let c=I$(t,r,o,i);return R$(Vu(c,n),t,r,s,o,a)}function R$(n,e,t,r,s,o){let i=()=>({type:"save",dispatches:C$(e,t,r,s,o)});switch(n.type){case"row":return{type:"row",selectedRow:n.row};case"cycle":{let a=e[n.row];if(!a)return{type:"noop"};let d=Ag(a.representative);if(d.length===0)return{type:"noop"};let c=t[n.row]??0;return{type:"cycle",selectedRow:n.row,newValueIndex:(c+n.delta+d.length)%d.length}}case"dismiss":return{type:"dismiss-toggle",selectedRow:n.row};case"advance":case"commit":case"close":return i();case"cancel":return{type:"discard"};default:return{type:"noop"}}}function h$(n){if(!Array.isArray(n))return;let e=
|
|
285
|
+
`)){let r=t.trim().split(/\s+/);if(r.length<4)continue;let s=Number(r[0]),o=Number(r[1]),i=Number(r[2]),a=f4(r[3]);!Number.isInteger(s)||!Number.isInteger(o)||!Number.isFinite(i)||a===null||e.set(s,{pid:s,ppid:o,rssBytes:i*1024,cpuSeconds:a})}return e}function f4(n){let e=n,t=0,r=e.indexOf("-");if(r!==-1){let i=e.slice(0,r);if(i.length===0||(t=Number(i),e=e.slice(r+1),!Number.isInteger(t)||t<0))return null}let s=e.split(":");if(s.length<2||s.length>3)return null;let o=0;for(let i of s){let a=Number(i);if(!Number.isFinite(a)||a<0)return null;o=o*60+a}return t*86400+o}function uS(n,e){let t=new Map;for(let o of n.values()){let i=t.get(o.ppid);i===void 0?t.set(o.ppid,[o.pid]):i.push(o.pid)}let r=new Set;if(!n.has(e))return r;let s=[e];for(;s.length>0;){let o=s.pop();if(!r.has(o)){r.add(o);for(let i of t.get(o)??[])r.has(i)||s.push(i)}}return r}function l$(n,e,t){let r=uS(n.rows,t);if(r.size===0)return null;let s=0,o=0,i=!1;for(let c of r){if(n.rssKnown!==void 0&&!n.rssKnown.has(c))return null;let l=n.rows.get(c);s+=l.rssBytes;let u=e?.rows.get(c);u!==void 0&&(i=!0,o+=Math.max(0,l.cpuSeconds-u.cpuSeconds))}i&&e!==null&&(o+=p4(n,e,r,t));let a={processes:r.size,rssBytes:s},d=e===null?0:n.at-e.at;return i&&d>0&&(a.cpuFraction=Math.max(0,o)/(d/1e3)),a}function p4(n,e,t,r){let s=0,o=!1;for(let i of t){let a=n.rows.get(i).childCpuSeconds,d=e.rows.get(i)?.childCpuSeconds;a===void 0||d===void 0||(o=!0,s+=Math.max(0,a-d))}if(!o)return 0;for(let i of uS(e.rows,r)){if(t.has(i))continue;let a=e.rows.get(i);a!==void 0&&a.childCpuSeconds!==void 0&&(s-=a.cpuSeconds+a.childCpuSeconds)}return s}async function h4(n,e,t){let r=[],s;try{s=await e(`/proc/${n}/task`)}catch{return r}for(let o of s){if(!/^\d+$/.test(o))continue;let i;try{i=await t(`/proc/${n}/task/${o}/children`)}catch{continue}for(let a of i.split(/\s+/)){if(a.length===0)continue;let d=Number(a);Number.isInteger(d)&&d>0&&r.push(d)}}return r}async function m4(n,e,t){let r=new Map,s=new Set;for(let o of n){if(s.has(o))continue;let i;try{i=await t(`/proc/${o}/stat`)}catch{continue}try{await t(`/proc/${o}/task/${o}/children`)}catch{return null}let a=lS(i);if(a===null)continue;r.set(o,a),s.add(o);let d=[o];for(;d.length>0;){let c=d.pop();for(let l of await h4(c,e,t)){if(s.has(l))continue;s.add(l);let u;try{u=lS(await t(`/proc/${l}/stat`))}catch{continue}u!==null&&(r.set(l,u),d.push(l))}}}return r}async function g4(n,e){let t=new Map,r;try{r=await n("/proc")}catch{return t}return await Promise.all(r.map(async s=>{if(/^\d+$/.test(s))try{let o=lS(await e(`/proc/${s}/stat`));o!==null&&t.set(o.pid,o)}catch{}})),t}async function y4(n,e,t){for(let r of e){let s=n.get(r);if(s!==void 0)try{let o=l4(await t(`/proc/${r}/status`));o!==null&&(s.rssBytes=o)}catch{}}}async function u$(n,e={}){let t=e.platform??process.platform,r=Date.now();if(t==="linux"){let o=e.readDir??(l=>d4(l)),i=e.readFile??(l=>c4(l,"utf8")),a=await m4(n,o,i),d=a??await g4(o,i),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 uS(d,l))c.add(u);return await y4(d,c,i),{at:r,rows:d,rssKnown:c}}let s=e.runPs??(async()=>{let{execFile:o}=await import("child_process"),{promisify:i}=await import("util"),{stdout:a}=await i(o)("ps",["-A","-o","pid=,ppid=,rss=,time="],{timeout:5e3,maxBuffer:8*1024*1024});return a});try{return{at:r,rows:u4(await s())}}catch{return{at:r,rows:new Map}}}var d$,f$=q(()=>{"use strict";d$=100});import{mkdtempSync as w4,readFileSync as b4,rmSync as k4}from"fs";import{tmpdir as v4}from"os";import{performance as S4}from"perf_hooks";import{writeHeapSnapshot as x4}from"v8";import{nanoid as gS}from"nanoid";import I4 from"terminal-kit";import fS from"fs/promises";import Ri from"path";import{execFile as p$}from"child_process";function C4(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function R4(n){let e=Ag(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function A4(n){let e=new Map,t=[];for(let r of n){let s=r.question,o=e.get(s);o?o.ids.push(r.id):(e.set(s,{representative:r,ids:[r.id]}),t.push(s))}return t.map(r=>e.get(r))}function Ag(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 pS(n){let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t;typeof r.label!="string"||typeof r.since!="number"||e.push({label:r.label,since:r.since,...typeof r.taskId=="string"?{taskId:r.taskId}:{},...typeof r.taskType=="string"?{taskType:r.taskType}:{}})}return e}function T4(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function I$(n,e,t,r,s=60){let o=n.map((i,a)=>{let d=Ag(i.representative),c=e[a]??0,l=t[a]?yS:d[c]??d[0]??"",u=T4(i.representative.question,s);return{id:i.representative.id,kind:"select",label:u,value:l}});return{title:`Open questions (${n.length})`,rows:o,cursor:Math.max(0,Math.min(n.length-1,r)),hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 cycle"},{label:"d dismiss",action:"dismiss"},{label:"1-9 jump"},{label:"\u23CE/Esc save",action:"commit"},{label:"^C discard",action:"cancel"}]}}function E4(n,e,t){return n===yS?{type:"dismiss",method:SP,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:vP,params:{sessionId:t,questionId:e.id,answer:n}}}function C$(n,e,t,r,s){let o=[];for(let i=0;i<n.length;i++){let a=n[i];if(!a||!t[i])continue;let d=r[i]?yS:Ag(a.representative)[e[i]??0]??"";if(d)for(let c of a.ids){let l={...a.representative,id:c},u=E4(d,l,s);u!==null&&o.push(u)}}return o}function P4(n,e,t,r,s,o,i,a){if(!e||t===null||t.length===0)return{type:"noop"};let d=()=>({type:"save",dispatches:C$(t,r,s,o,a)});if(n.type==="key"&&n.name==="ctrl-q")return d();let c=I$(t,r,o,i);return R$(Vu(c,n),t,r,s,o,a)}function R$(n,e,t,r,s,o){let i=()=>({type:"save",dispatches:C$(e,t,r,s,o)});switch(n.type){case"row":return{type:"row",selectedRow:n.row};case"cycle":{let a=e[n.row];if(!a)return{type:"noop"};let d=Ag(a.representative);if(d.length===0)return{type:"noop"};let c=t[n.row]??0;return{type:"cycle",selectedRow:n.row,newValueIndex:(c+n.delta+d.length)%d.length}}case"dismiss":return{type:"dismiss-toggle",selectedRow:n.row};case"advance":case"commit":case"close":return i();case"cancel":return{type:"discard"};default:return{type:"noop"}}}function h$(n){if(!Array.isArray(n))return;let e=js({sessionUpdate:"config_option_update",configOptions:n});return e&&e.kind==="config-options"?e.options:void 0}function hS(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 _4(n,e=process.env){if(n!==void 0)return{argv:n,source:"config"};let t=[e.HYDRA_EDITOR,e.VISUAL,e.EDITOR].find(r=>r!==void 0&&r.trim()!=="");if(t!==void 0)return{argv:t,source:"env"}}function O4(n,e){e.has(n)?e.delete(n):e.add(n)}function F4(n){return n.map(e=>`${e.status??"pending"}\0${e.content}`).join("")}function L4(n){let{stale:e,hasKey:t,prevFingerprint:r,fingerprint:s}=n;return e&&(!t||r!==s)?"fresh":"splice"}function N4(){if(g$)return;g$=!0;let n=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{ge({src:"uncaughtException",stack:n(e)}),Ii(),process.stderr.write(`
|
|
286
286
|
uncaught: ${n(e)}
|
|
287
287
|
`),process.exit(1)}),process.on("unhandledRejection",e=>{ge({src:"unhandledRejection",stack:n(e)}),Ii(),process.stderr.write(`
|
|
288
288
|
unhandled rejection: ${n(e)}
|
|
@@ -293,18 +293,18 @@ unhandled rejection: ${n(e)}
|
|
|
293
293
|
`),process.stdout.isTTY){let x=await Ca(e);if(x?.version!==void 0){let A=x.version!==Ue,_=ci(e),P=x.configDigest!==void 0&&x.configDigest!==_;if(A||P){let $=A?`daemon ${x.version} \u2260 cli ${Ue}`:"config changed since daemon started";process.stderr.write(aa("cli-warn",`! ${$} \u2014 run \`${Nn()} daemon restart\` to apply.`,Fl(process.stderr))+`
|
|
294
294
|
`)}}}if(l.sessionId&&process.stdout.isTTY){let x=st(l.sessionId),A=l.readonly?" --readonly":"";process.stdout.write(`Continue: ${Nn()} --session ${x}${A}
|
|
295
295
|
`)}}function B4(n){let{order:e,states:t,startedAt:r,endedAt:s,stopReason:o,perToolExpanded:i,collapsedLimit:a=20}=n,d=e.filter(F=>!vc(F,t.get(F)?.latestTitle)),c=d.length,l=a>0,u;if(!l||n.expanded)u=d;else{let F=Math.max(0,c-a),J=d.slice(F),Y=[];for(let W=0;W<F;W++){let Z=d[W];if(Z===void 0)continue;let ne=t.get(Z);ne&&!ek(ne.status)&&Y.push(Z)}u=[...Y,...J]}let f=c-u.length,p=s===null,m=s??Date.now(),h=m-r,g=!p&&o!==null&&o!=="end_turn"?o:null,w=g==="amended",b=w?`amended \xB7 ${Pr(h)}`:`stopped (${g}) \xB7 ${Pr(h)}`,k=p?"":` \xB7 ${am(m)}`,S;if(c===0)g!==null?S=b+k:S=p?`thinking \xB7 ${Pr(h)}`:`thought \xB7 ${Pr(h)}${k}`;else{let F=c===1?"tool":"tools",J=g!==null?b:p?Pr(h):`took ${Pr(h)}`,Y=[`${c} ${F}`,J];p&&Y.push(`started ${am(r)}`),p&&l&&f>0&&Y.push(`${f} hidden`),S=Y.join(" \xB7 ")+k}let I=c===0&&p;if(I)return{lines:[{body:""}],rowOwners:[null]};let x=w?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:I?"tool-status-running":g!==null?x:"tool",body:S,bodyStyle:I?"tool-status-running":g!==null?x:"status-idle"}],$=[null];for(let F of u){let J=t.get(F);if(J){let Y=$u(J,m),W=i?.has(F)??!1;for(let Z of Y)Z.hoverSubKey=F,W||(Z.maxWrapRows=D4);if(P.push(...Y),$.push(...Y.map(()=>F)),W){let Z=v0(J);for(let ne of Z)ne.hoverSubKey=F;P.push(...Z),$.push(...Z.map(()=>F))}}}return{lines:P,rowOwners:$}}async function H4(n,e,t,r,s,o,i,a){if(r.terminalHostLauncher&&r.sessionId===void 0&&r.forceNew!==!0&&r.resume!==!0)for(;;){let y=await y$(n,e,t,r,i,o);if(!y)return n.grabInput(!1),null;y.installStatus?.finalize();let v=await mS(y.sessionId==="__new__"?{kind:"new",...r.cwd!==void 0?{cwd:r.cwd}:{},...y.agentId?{agentId:y.agentId}:{},...r.model!==void 0?{model:r.model}:{},...r.initialPrompt!==void 0?{prompt:r.initialPrompt}:{}}:{kind:"attach",sessionId:y.sessionId},[],y.cwd);B(n,"content",`${v}
|
|
296
|
-
`),y.sessionId!=="__new__"&&(r.pickerSelect=y.sessionId),delete r.initialPrompt,delete r.initialAttachments}let d=await y$(n,e,t,r,i,o);if(!d)return n.grabInput(!1),ge({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=d.resolved?.status==="warm"&&t.isLocal,l=d.sessionId==="__new__"?"Starting new session\u2026":d.isFreshFork?"Forking session\u2026":d.resolved?.status==="warm"?"Attaching to session\u2026":"Resuming session\u2026",u=r.installStatus;r.installStatus&&delete r.installStatus;let f=d.installStatus??u??bg(c?"":l,k_(n));c||f.write(l);let p=t.isLocal?async()=>(await rn(await He())).wsUrl:t.wsUrl,m=t.isLocal?async()=>["acp.v1",`hydra-acp-token.${(await rn(await He())).token}`]:["acp.v1",`hydra-acp-token.${t.token}`],h=null,g=null,w=new Gc({url:p,subprotocols:m,onConnect:async y=>{y||h&&await h()},onDisconnect:y=>{g&&g(y)},log:y=>ge({src:"resilient-ws",line:y})}),b=new pn(w);await w.start(),b.onNotification(bp,y=>{let v=JI.safeParse(y);v.success&&f.applyProgress(v.data)});let k=[],S=null,I=!1,x=!1,A=(y,v,C)=>{y&&(S?S(y,v,C):k.push({event:y,rawUpdate:v,recordedAt:C}))},_,P=y=>{y!==_&&(_=y,y!==void 0&&R.appendLines([{prefix:" ",body:`\u2500\u2500 T${y} \u2500\u2500`,bodyStyle:"muted"}]))},$=null,F=null,J=!1,Y=0,W=0,Z=!1,ne=!1,ve,Ne=null,Re=null,Ge=!1,Ae=!1,de=null,De=!1,it=null,Rt=null,Me=null,Kt=null,Ve=null,ys=null,Ti=!1,mr=()=>setInterval(()=>{if(xe===null)return;if(Ne===null){it!==null&&xe.setBanner({});return}let y=ys===null?0:Date.now()-ys;y<m$&&(Ti=!1);let C=it===null&&!Xa()&&y>=m$;xe.setBanner({elapsedMs:Date.now()-Ne,stalled:C}),C&&!Ti&&(Ti=!0,xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`no output for ${Math.round(y/6e4)}m and nothing running. ^C to cancel`,bodyStyle:"tool-status-fail"}])),sr()},1e3),ce=!1,Je=(y,v,C)=>{let O=W;W=Math.max(0,W+y),ge({src:"pending-turns",delta:y,before:O,after:W,origin:v??null,label:C??null}),y>0&&xM({origin:v??null,label:C});let T=typeof xe<"u"&&xe!==null;O===0&&W>0?(ne=!1,Ne=Date.now(),ys=Date.now(),xe?.setSidebarSnapshot({busySince:Ne}),an?.setTurnRunning(!0),T&&xe.setBanner({status:"busy",elapsedMs:0,stalled:!1}),de===null&&T&&(de=mr())):O>0&&W===0?(ne=!1,er!==null&&(clearTimeout(er),er=null),at=!1,Ne=null,Ge?Re=Date.now():Ae=!0,xe?.setSidebarSnapshot({busySince:null,lastTurnEndedAt:Re}),ys=null,an?.setTurnRunning(!1),de!==null&&it===null&&(clearInterval(de),de=null),T&&xe.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):W>0&&ne&&(ne=!1,T&&xe.setBanner({status:"busy",stalled:!1}))},xe=null,an=null,Xa=()=>!1,Lr,Nr,Oo=null,Mg=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction","_hydra_workspace","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),sl=y=>{let{update:v}=y??{},C=HI(y),O=Ws(v,{cwd:tt});U4(v,O),ys=Date.now();let T=v?.sessionUpdate;if(typeof T=="string"&&!Mg.has(T)){let N=v??{};typeof N.messageId=="string"&&(Lr=N.messageId);let H=yp(y);H!==void 0&&(Nr=H)}if(T==="prompt_received"){let N=F_(v?.sentBy);Je(1,N.origin,N.label)}else O?.kind==="turn-complete"&&(Je(-1),J=!0);if(T==="permission_resolved"){kf(v);return}if(T==="_hydra_compaction"){no(v);return}if(T==="_hydra_workspace"){Ei(v);return}if(T==="clarifier_question_asked"){let N=v,H=typeof N.question?.question=="string"?N.question.question:"",te=H.length>50?H.slice(0,49)+"\u2026":H;R.notify(te?`new question: ${te} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}T==="clarifier_question_answered"||T==="clarifier_question_dismissed"||(A(O,v,C),Pi(v))};b.onNotification("session/update",y=>{if(!I){if(Oo!==null){Oo.push(y);return}sl(y)}}),b.onNotification("hydra-acp/session/closed",()=>{if(I)return;W>0&&Je(-W),typeof xe<"u"&&xe!==null&&xe.setBanner({status:"cold",elapsedMs:void 0}),$n()});let ws=new Map,Fo=200,Ut=0,at=!1,Za=4e3,er=null;b.onNotification("hydra-acp/prompt_queue/added",y=>{if(I)return;let v=y??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let O=v.messageId,T=v.prompt,N=setTimeout(()=>{I||(ws.delete(O),Ln.set(O,Cd(O,T)),xe&&an&&ho())},Fo);ws.set(O,N)}else Ln.set(v.messageId,Cd(v.messageId,v.prompt)),xe&&an&&ho();if(Br!==void 0&&v.originator?.clientId===Br){let O=Jn.shift();O&&(O.messageId=v.messageId,Is.set(v.messageId,O))}});let Wn=(y,v)=>{let C=Ln.get(y);C!==void 0&&(v?C.held=!0:delete C.held,xe&&an&&ho())},gn=(y,v)=>{v!==void 0&&xe?.setSidebarSnapshot({armedTasks:v}),it!==y&&(it=y,xe?.setBanner({armedSince:y??void 0}),xe?.setSidebarSnapshot({armedSince:y}),y!==null&&de===null&&xe!==null&&(de=mr()),y===null&&Ne===null&&de!==null&&(clearInterval(de),de=null))};b.onNotification("hydra-acp/session/armed_tasks_updated",y=>{if(I)return;let v=y??{},C=typeof v.count=="number"?v.count:0;gn(C>0&&typeof v.since=="number"?v.since:null,Array.isArray(v.tasks)?pS(v.tasks):void 0)}),b.onNotification("hydra-acp/prompt_queue/held",y=>{if(I)return;let v=y??{};typeof v.messageId=="string"&&Wn(v.messageId,!0)}),b.onNotification("hydra-acp/prompt_queue/released",y=>{if(I)return;let v=y??{};typeof v.messageId=="string"&&Wn(v.messageId,!1)}),b.onNotification("hydra-acp/prompt_queue/updated",y=>{if(I)return;let v=y??{};if(typeof v.messageId!="string")return;let C=Ln.get(v.messageId);if(C===void 0)return;let O=Cd(v.messageId,v.prompt);C.held&&(O.held=!0),Ln.set(v.messageId,O);let T=Is.get(v.messageId);if(T){let N=Array.isArray(v.prompt)?v.prompt:[],H="",te=[];for(let le of N){if(!le||typeof le!="object")continue;let ie=le;ie.type==="text"&&typeof ie.text=="string"?H+=ie.text:ie.type==="image"&&typeof ie.data=="string"&&typeof ie.mimeType=="string"&&te.push({data:ie.data,mimeType:ie.mimeType,sizeBytes:Math.floor(ie.data.length*3/4)})}T.text=H,T.attachments=te}xe&&an&&ho()}),b.onNotification("hydra-acp/prompt_queue/removed",y=>{if(I)return;let v=y??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(ve=v.messageId);let C=ws.get(v.messageId);C!==void 0&&(clearTimeout(C),ws.delete(v.messageId)),Ln.delete(v.messageId)&&xe&&an&&ho();let T=Is.get(v.messageId);T&&(Is.delete(v.messageId),v.reason==="started"&&(T.flushed=!0,A({kind:"user-text",text:T.displayText,attachments:T.attachments}),Vr=T))}),b.onNotification("hydra-acp/cancel_failed",y=>{if(I)return;let v=y??{};if(!(typeof xe<"u"&&xe!==null))return;Ut=Date.now();let O=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";if(v.reason==="unresponsive"){xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`agent kept resuming after repeated cancels${O} \u2014 hydra restarted it automatically.`,bodyStyle:"tool-status-fail"}]);return}at=!0;let T=typeof v.code=="number"?` (${v.code})`:"";xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${T}${O} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),b.onNotification("hydra-acp/prompt/amended",y=>{if(I)return;let v=y??{};if(typeof v.cancelledMessageId!="string")return;let C=v.cancelledMessageId;Jr.add(C),Vr!==null&&Vr.messageId!==void 0&&Vr.messageId===C&&(A({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Vr=null,Jr.delete(C))}),b.onNotification("hydra-acp/context_self_compacted",()=>{I||R.notify("agent compacted its own context \u2014 recall armed",4e3)});let no=y=>{let v=y??{},C=typeof v.phase=="string"?v.phase:void 0;if(C==="started")R.setCompactionIndicator("compacting...");else if(C==="iteration")R.setCompactionIndicator("compacting...");else if(C==="deferred")R.setCompactionIndicator("compaction queued (waiting for idle)");else if(C==="swapped")R.setCompactionIndicator(null),R.notify("compacted",2e3);else if(C==="rolled_back")R.setCompactionIndicator(null),R.notify("rolled back",2e3);else if(C==="failed"){R.setCompactionIndicator(null);let O=typeof v.error=="string"?v.error:"unknown error",T=O.length>40?O.slice(0,40)+"...":O;R.notify(`compaction failed: ${T}`,5e3)}},Ei=y=>{let v=y??{},C=typeof v.phase=="string"?v.phase:void 0;if(C==="drift"){let N=typeof v.behind=="number"?v.behind:0;R.notify(N>0?`source moved on, ${N} commit(s) ahead \u2014 /hydra workspace sync`:"source moved on \u2014 /hydra workspace sync",6e3);return}if(C==="provisioning"){R.setWorkspaceIndicator("creating workspace...");return}if(C==="setup"){R.setWorkspaceIndicator("running workspace setup...");return}if(C==="swapping"){R.setWorkspaceIndicator("moving session into workspace...");return}if(C==="landing"){R.setWorkspaceIndicator("merging workspace back...");return}if(C==="applying"){R.setWorkspaceIndicator("staging workspace changes...");return}if(C==="returning"){R.setWorkspaceIndicator("returning to source tree...");return}if(C==="failed"){R.setWorkspaceIndicator(null);let N=typeof v.error=="string"?v.error:"unknown error";R.notify(`workspace failed: ${N.length>40?N.slice(0,40)+"...":N}`,5e3);return}if(C!=="entered"&&C!=="left"||(R.setWorkspaceIndicator(null),typeof v.cwd!="string"||v.cwd.length===0))return;tt=v.cwd,jf=null;let O=typeof v.sourceCwd=="string"?v.sourceCwd:v.cwd,T=typeof v.label=="string"?v.label:void 0;R.setSessionbar({cwd:v.cwd,...C==="entered"&&T!==void 0?{workspace:{label:T,path:v.cwd,sourceCwd:O}}:{workspace:void 0}}),kl(),R.setSidebarSnapshot({workspace:C==="entered"&&T!==void 0?{label:T,path:v.cwd}:null}),R.notify(C==="entered"?`isolated in ${T??"a workspace"}`:"returned to source tree",2e3)},ol=()=>{Rt===null&&(Rt=setInterval(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!y.ok)return;let v=await y.json();v.forkSynthesisState===void 0?(R.setSynthesisIndicator(null),R.notify("synthesis complete",2e3),Rt!==null&&(clearInterval(Rt),Rt=null)):v.forkSynthesisState==="failed"&&(R.setSynthesisIndicator("\u26A0 synthesis failed"),R.notify("synthesis failed \u2014 fork still usable via recall",8e3),Rt!==null&&(clearInterval(Rt),Rt=null))}catch{}},5e3))},ed=()=>{Rt!==null&&(clearInterval(Rt),Rt=null)},ro=()=>{Me!==null&&(clearInterval(Me),Me=null)},$n=()=>{if(Me!==null)return;let y=!1;Me=setInterval(async()=>{if(!(y||I)){y=!0;try{let v=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!v.ok){v.status===404&&ro();return}if((await v.json()).status!=="warm")return;ro(),ge({src:"cold-watch",step:"warm-detected",sessionId:me}),h&&await h({skipInitialize:!0,beforeReplay:()=>{xe?.appendLines([{prefix:" ",body:"-- session resumed by another client, catching up --",bodyStyle:"muted"}])}})}catch{}finally{y=!1}}},M4)},kf=y=>{let v=y??{},C=typeof v.toolCallId=="string"?v.toolCallId:void 0,O;v.outcome&&typeof v.outcome=="object"?O=v.outcome:typeof v.chosenOptionId=="string"&&(O={kind:"selected",optionId:v.chosenOptionId}),yn(C,O?{outcome:O}:void 0)},Ye=null,yn=(y,v)=>{if(!Ye||Ye.toolCallId&&y&&Ye.toolCallId!==y)return;let C=Ye.resolve;Ye=null,R.setPermissionPrompt(null),C(v??{outcome:{outcome:"cancelled"}})},Pi=y=>{if(!Ye?.toolCallId)return;let v=y??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===Ye.toolCallId&&(!v.status||v.status==="pending"||yn(v.toolCallId,void 0))},Mi=()=>{if(!Ye){R.setPermissionPrompt(null);return}R.setPermissionPrompt({title:Ye.title,detail:Ye.detail,options:Ye.options.map(y=>({label:y.name})),selectedIndex:Ye.selectedIndex})},so=y=>{if(!Ye)return;let{options:v,resolve:C}=Ye;if(Ye=null,R.setPermissionPrompt(null),y===null){C({outcome:{outcome:"cancelled"}});return}C({outcome:{outcome:"selected",optionId:y}})};b.onRequest("session/request_permission",async y=>{if(I)return{outcome:{outcome:"cancelled"}};if(r.dangerouslySkipPermissions)return Da(y);let v=y??{},O=(Array.isArray(v.options)?v.options:[]).map(le=>({optionId:le.optionId,name:ot(le.name??""),...le.kind!==void 0?{kind:le.kind}:{}})),T=v.toolCall?.title??v.toolCall?.name??"tool",N=ot(T),H=ot(EE(TE(y))),te=v.toolCall?.toolCallId;return O.length===0?(R.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${N} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(le=>{Ye={title:N,detail:H,options:O,selectedIndex:0,resolve:le,toolCallId:te},Mi()})}),b.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let _i,td,In=!0,bs=!1,Dr=!1;try{let y=await b.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Ue}});td=y?.agentInfo?.name,y?.agentCapabilities?.promptCapabilities?.image===!1&&(In=!1),bs=Pn(y?._meta??void 0).prompt?.amending===!0,Dr=y?._meta?.steering?.supported===!0}catch{}let me=d.sessionId,It=d.agentId,tt=d.cwd,Qt;t.isLocal||(d.remote=t.display);let vf=d.remote,jn=Qc(d),qn=null,il=()=>(qn===null&&(qn=w4(Ri.join(v4(),"hydra-remote-exec-"))),qn),$i=()=>jn?il():tt,Oi=d.jumpToRecordedAt,Br,Xt,Fi,Lo,nd,rd,sd,oo,No,Hr,od,io,Sf=!1;if(d.sessionId==="__new__"){let y={};r.agentId&&(y.agentId=r.agentId),r.name&&(y.title=r.name),r.model&&(y.model=r.model),r.workspace===!0&&(y.workspace={});let v={cwd:d.cwd,...Object.keys(y).length>0?{_meta:{[ut]:y}}:{}},C;try{C=await gE({request:()=>b.request("session/new",v),showBanner:(N,H,te)=>yE(n,N,H,te,{authenticate:le=>b.request("authenticate",{methodId:le,_meta:{[ut]:{agentId:N}}})}),resolveOnboarding:async N=>{if(N)try{return(await Aa(t)).find(le=>le.id===N)?.onboarding}catch{return}},fallbackAgentId:r.agentId})}catch(N){n.grabInput(!1),ge({src:"grab",site:"runSession.session-new-failed",on:!1}),w.close().catch(()=>{});let H=N instanceof Error?N.message:String(N);ge({src:"session-new-failed",agentId:r.agentId??null,message:H});let te=await T_(n,r.agentId,H,{canGoBack:!r.forceNew});if(te==="cancel")return null;let le={...r};return delete le.sessionId,delete le.resume,te==="retry"?le.forceNew=!0:(delete le.forceNew,delete le.agentId),le}if(C.kind==="cancel")return n.grabInput(!1),ge({src:"grab",site:"runSession.auth-cancel",on:!1}),w.close().catch(()=>{}),null;if(C.kind==="back"){n.grabInput(!1),ge({src:"grab",site:"runSession.auth-back",on:!1}),w.close().catch(()=>{});let N={...r};return delete N.sessionId,delete N.forceNew,delete N.resume,delete N.agentId,N}let O=C.result;f.write(l),me=O.sessionId,Rv(me),s.sessionId=me,s.readonly=!1;let T=Pn(O._meta??void 0);T.clientId&&(Br=T.clientId),_i=T.upstreamSessionId,T.agentId&&(It=T.agentId),T.cwd&&(tt=T.cwd),Xt=T.workspaceInfo,T.title&&(Qt=T.title),Fi=T.currentModel,Lo=T.currentMode,No=T.currentUsage,Hr=T.turnStartedAt,od=T.armedSince,io=T.armedTaskList,T.availableCommands&&(nd=xh(T.availableCommands)),T.availableModes&&(rd=T.availableModes),sd=h$(O.configOptions),oo=T.queue}else{let y={};r.readonly===!0&&(y.readonly=!0),e.tui.toolContent==="references"&&(y.toolContent="references"),r.drip===!0&&(y.replayMode="drip",r.dripSpeed!==void 0&&(y.dripSpeed=r.dripSpeed)),d.resumeHint!==void 0&&(y.resume={upstreamSessionId:d.resumeHint.upstreamSessionId,agentId:d.resumeHint.agentId,cwd:d.resumeHint.cwd});let v=await b.request("session/attach",{sessionId:d.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:Ue},...Object.keys(y).length>0?{_meta:{[ut]:y}}:{}});me=v.sessionId,Rv(me),v.clientId&&(Br=v.clientId),s.sessionId=me,s.readonly=r.readonly===!0;let C=Pn(v._meta??void 0);Sf=C.resurrected===!0,_i=C.upstreamSessionId,C.agentId&&(It=C.agentId),C.cwd&&(tt=C.cwd),Xt=C.workspaceInfo,C.title&&(Qt=C.title),Fi=C.currentModel,Lo=C.currentMode,No=C.currentUsage,Hr=C.turnStartedAt,od=C.armedSince,io=C.armedTaskList,C.availableCommands&&(nd=xh(C.availableCommands)),C.availableModes&&(rd=C.availableModes),sd=h$(v.configOptions),oo=C.queue}let Qe=D.tuiHistoryFile(me),Li=D.globalTuiHistoryFile(),Zt=await du(Qe).catch(()=>[]),en=await du(Li).catch(()=>[]);en.length>e.tui.promptHistoryMaxEntries&&(en=en.slice(en.length-e.tui.promptHistoryMaxEntries));let ao=[...Zt],Be=new Mo({history:nh(en,ao)});an=Be;let zn=!1,Ni=()=>{xe?.setBanner({hintsExhausted:ER(Zt.length,e.tui.composer.hintTurns)})},Ur=(y,v)=>{let C=y.replace(/\n+$/,"");if(C.length===0)return;let O=(v??y).replace(/\n+$/,""),T=cu(Zt,C),N=T!==Zt;Zt=T,ao=cu(ao,O);let H=cu(en,C,e.tui.promptHistoryMaxEntries),te=H!==en;en=H,Be.setHistory(nh(en,ao)),N&&ha(Qe,Zt).catch(()=>{}),te&&PR(Li,C).catch(()=>{}),Ni(),xe?.clearHintReveal()};W>0&&Be.setTurnRunning(!0);let tr=[],id=null;a_(d_(e.tui.ambiguousWidth,process.env,k$)),x0(e.tui.diffContextLines);let ad=!1,R,xf=()=>{ad&&(ad=!1,R.start())},_g=()=>{ad||(ad=!0,R.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",xf);let If=_4(e.tui.openFileCommand);R=new fg({term:n,dispatcher:Be,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:o.mouseEnabled,inAppSelection:o.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:If?.argv,openFileSource:If?.source,openFileInTerminal:e.tui.openFileInTerminal,progressIndicator:e.tui.progressIndicator,readonly:r.readonly===!0,onSidebarCollapseChange:(y,v)=>{o.sidebarCollapsed=xe?.sidebarCollapsedIds()??[],!v&&(y==="git"?kl():y==="sessions"?Gg():y==="resources"&&BS(),Sl())},onSuspend:process.platform!=="win32"?_g:void 0,onLayoutChange:()=>{OS()},onBlockClick:(y,v,C)=>{dO(y,v,C)},onHydraLinkClick:y=>(Wo(y),!0),onBlockVisible:y=>{Y$(y)},onHoverRun:y=>{if(!y.startsWith("thought:"))return null;let v=We.get(y);if(v!==void 0&&v.length>0)return new Set(v);let C=R.contiguousRun(y,new Set(ae.keys()));return C.length>0?new Set(C):null},onBarAction:(y,v)=>{if(y==="toggle-mode"){Df(!0);return}if(y==="rename-session"){hl(v);return}if(y==="choose-model"){pe("model");return}if(y==="choose-agent"){pe("agent");return}if(y==="choose-mode"){pe("mode");return}let C=y==="switch-session"?{type:"switch-session"}:y==="detach"?{type:"exit"}:y==="toggle-options"?{type:"toggle-options"}:{type:"show-help"};r.readonly===!0&&hS(C)||zi(C)},onFormClick:y=>ml(y),onPermissionClick:y=>Ef(y),onCompactionClick:y=>Bi(y),onHelpClick:()=>R.setHelpPrompt(null),onMouse:y=>{if(y.kind!=="press"||y.button!=="middle")return;let v={type:"attachment-request",source:"primary"};r.readonly===!0&&hS(v)||zi(v)},onKey:y=>{for(let v of y){if(Z&&uo(v)){v.type==="key"&&ge({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(Ye&&$g(v)){v.type==="key"&&ge({src:"key-swallowed",site:"permission",name:v.name});continue}if(Hi(v)){v.type==="key"&&ge({src:"key-swallowed",site:"help",name:v.name});continue}if(qi(v)){v.type==="key"&&ge({src:"key-swallowed",site:`form:${On??"none"}`,name:v.name});continue}if(Tf(v)){v.type==="key"&&ge({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(Af(v)){v.type==="key"&&ge({src:"key-swallowed",site:"completion",name:v.name});continue}if(At(v)){v.type==="key"&&ge({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&R.isScrolledBack()){R.scrollToBottom();continue}if(v.type==="attachment-paths"){Id(v.paths);continue}if(v.type==="key"&&Kn(v.name)){ge({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let C=Be.feed(v);for(let O of C)r.readonly===!0&&hS(O)||zi(O)}cd(),R.setBannerSearchIndicator(Be.state().historySearchQuery),R.setAttachments(Be.state().attachments),R.refreshPrompt()}}),xe=R,R.setStickyBottomKey("plan");let Cf=[{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:"/title",description:"Rename this session: /title [title] (no arg opens the field)"},{name:"/model",description:"Switch model: /model [model-id] (no arg opens the picker)"},{name:"/mode",description:"Switch mode: /mode [mode-id] (no arg opens the picker)"},{name:"/agent",description:"Switch agent: /agent [agent-id] (no arg opens the picker)"},{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]"}],dd=nd??[],Do=rd??[],gr=sd??[],Rf=()=>{let y=new Set,v=[];for(let C of[...Cf,...dd])y.has(C.name)||(y.add(C.name),v.push(C));return v},al=()=>{let y=Be.state().buffer,v=y[0]??"";if(!v.startsWith("/"))return[];if(y.length>1)return[];let C=v.indexOf(" "),O=C===-1?v:v.slice(0,C);if(O.lastIndexOf("/")>0)return[];let T=Rf().filter(N=>N.name.startsWith(O));return T.length===1&&T[0]?.name===O?[]:T},co=[],cd=()=>{let y=al();if(y.length>0){co=[],R.setCompletions(y);return}R.setCompletions(co)},Af=y=>{if(y.type!=="key"||y.name!=="tab")return co.length>0&&(co=[]),!1;let v=al();if(R.isOverlayOpen()&&v.length===0)return R.toggleFocusedPane(),!0;if(v.length>0){co=[];let C=Be.state().buffer[0]??"",O=m_({matches:v.map(T=>T.name),firstLine:C});return O===null||Be.replaceFirstLine(O),!0}return ld()},ld=()=>{if(jn)return!1;let y=Be.state(),v=y.buffer[y.row]??"",C=gg(v,y.col);if(C===null)return!1;let O=yg(C.token,tt);return O===null?!1:(O.replacement!==C.token&&Be.replaceRangeOnCurrentLine(C.start,y.col,O.replacement),co=O.candidates.length>1?O.candidates.map(T=>({name:T})):[],!0)},At=y=>!R.isOverlayOpen()||y.type!=="key"||y.name!=="escape"&&y.name!=="ctrl-c"?!1:($&&($.cancel(),$=null,F=null),R.closeBtwOverlay(),!0),Tf=y=>{if(!R.isScrollbackSearchActive())return y.type==="key"&&y.name==="ctrl-r"&&R.isScrolledBack()?(R.enterScrollbackSearch(),R.updateScrollbackSearchTerm(""),!0):!1;if(y.type==="char"){let v=R.scrollbackSearchTerm()+y.ch;return R.updateScrollbackSearchTerm(v),!0}if(y.type==="paste"){let v=R.scrollbackSearchTerm()+y.text.replace(/\n/g," ");return R.updateScrollbackSearchTerm(v),!0}if(y.type==="key")switch(y.name){case"ctrl-r":return R.advanceScrollbackSearch(),!0;case"ctrl-s":return R.retreatScrollbackSearch(),!0;case"backspace":{let v=R.scrollbackSearchTerm();return v.length===0?R.cancelScrollbackSearch():R.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return R.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return R.cancelScrollbackSearch(),!0;default:return!0}return!0},Ef=y=>{if(!Ye)return;let v=Ye.options;if(y.kind==="hint"){if(y.action==="cancel"){so(null);return}so(v[Ye.selectedIndex]?.optionId??null);return}let C=v[y.index];if(C){if(y.select===!0){Ye.selectedIndex=y.index,Mi();return}so(C.optionId)}},$g=y=>{if(!Ye)return!1;let v=Ye.options;if(y.type==="key")switch(y.name){case"up":return Ye.selectedIndex=Math.max(0,Ye.selectedIndex-1),Mi(),!0;case"down":return Ye.selectedIndex=Math.min(v.length-1,Ye.selectedIndex+1),Mi(),!0;case"enter":{let C=v[Ye.selectedIndex];return C&&so(C.optionId),!0}case"escape":case"ctrl-c":return so(null),!0;default:return!0}if(y.type==="char"&&/^[1-9]$/.test(y.ch)){let C=parseInt(y.ch,10)-1,O=v[C];return O&&so(O.optionId),!0}return!0},Kn=y=>{let v=e.tui.hotkeys[y];return v?(wg(v,{sessionId:me,cwd:$i(),agentId:It||td||"",baseUrl:t.baseUrl,tokenFile:D.authToken()},{notify:C=>R.notify(C),cwd:$i(),emitLines:C=>{R.appendLines(C.map(O=>{let T;switch(O.style){case"meta":T="muted";break;case"stderr":case"error":T="tool-status-fail";break;default:T="notice"}return{prefix:" ",body:O.text,bodyStyle:T}}))}}),!0):!1},ud=()=>It||td||"?",Ct=ud(),Ot={...No??{}};f.finalize(),R.start({skipFullscreen:!0}),R.setHideThoughts(!o.showThoughts),R.setBarConfig({composer:e.tui.composer,sessionbar:e.tui.sessionbar});let Bo=sS(tf({composer:e.tui.composer,sessionbar:e.tui.sessionbar}),e.tui.scriptRefreshMs),dl=y=>{let v=a.get(y);if(v===void 0)return;let C={HYDRA_ACP_TOKEN:v,HYDRA_ACP_DAEMON_URL:t.baseUrl};return me!==null&&(C.HYDRA_ACP_SESSION_ID=me),C};if(Bo.size>0){let y=P_({cwd:$i,envFor:dl,onOutput:(v,C)=>R.setScriptOutput(v,C)});Kt=setInterval(()=>{y.poll(Bo,Date.now())},1e3),Kt.unref?.(),y.poll(Bo,Date.now())}let ks=kv(e.tui.sidebar.gadgets);R.setSidebarProcessGadgets(tg(ks)),R.setSidebarGadgets(ks.map(eg));let fd=hv(ks,e.tui.scriptRefreshMs),pd=new Map;for(let y of tg(ks)){let v=pd.get(y.script)??[];v.push(y.id),pd.set(y.script,v)}let lo=()=>{let y=new Map;for(let[v,C]of fd)(pd.get(v)??[]).some(T=>R.isSidebarGadgetActive(T))&&y.set(v,C);return y};if(fd.size>0){let y=Sg({cwd:$i,envFor:dl,sanitize:uM,onOutput:(v,C)=>R.setProcessOutput(v,C)});Ve=setInterval(()=>{y.poll(lo(),Date.now())},1e3),Ve.unref?.(),y.poll(lo(),Date.now())}Ni(),R.setSidebarWidth(e.tui.sidebar.width??null),R.setSidebarBorder(e.tui.sidebar.border),R.setSidebarSnapshot({usage:{...Ot},model:Fi??null,mode:Lo??null,sessionId:me===null?null:st(me),host:me===null?null:Ds(me)?.name??null,agent:Ct,workspace:Xt===void 0?null:{label:Xt.label,path:Xt.path}}),R.setSessionbar({agent:Ct,cwd:tt,remote:vf,...Xt===void 0?{}:{workspace:{label:Xt.label,path:Xt.path,sourceCwd:Xt.sourceCwd}},sessionId:me,title:Qt,model:Fi,usage:{...Ot}}),Lo&&R.setBanner({currentMode:Lo}),Uu().then(y=>{y&&R.notify(`\u2728 ${Wu(y)}`,3e4)}).catch(()=>{});let Wt=null,Di=new Promise(y=>{Wt=y}),cl=()=>{if(b.notify("session/cancel",{sessionId:me}).catch(()=>{}),er===null){let y=Date.now();er=setTimeout(()=>{er=null,W!==0&&(Ut>=y||at||(at=!0,xe?.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"cancel not acknowledged by agent; the turn is still running. Cancel again to force-stop (restarts the agent).",bodyStyle:"tool-status-fail"}])))},Za)}},Pf=()=>{at=!1,xe!==null&&xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"force-stopping agent \u2014 turn aborted; resumes on your next message\u2026",bodyStyle:"tool-status-fail"}]),b.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(()=>{})},ll=()=>{xe!==null&&W===1&&(ne=!0,xe.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Mf=()=>{let y=tr[0];if(y){y.cancel(),ll();return}if(W>0){at?Pf():cl(),ll();return}hd()},hd=()=>{xd(0)},Og=()=>{let y="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...o.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",y]]:[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",v]],...$4]},ul=()=>{if(R.isHelpPromptActive()){R.setHelpPrompt(null);return}R.setHelpPrompt({title:`Hotkeys \xB7 hydra-acp v${Ue}`,entries:Og(),hint:"any key dismisses \xB7 /help lists commands"})},Ho=()=>{Z=!1,R.setCompactionPrompt(null),R.setCompactionIndicator("compaction queued...");let y=me;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(y)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Wr=()=>{Z=!1,R.setCompactionPrompt(null)},vs=y=>{let v=R.compactionPromptSpec();if(!v)return;let C=v.options.length;if(C===0)return;let O=((v.selectedIndex+y)%C+C)%C;O!==v.selectedIndex&&R.setCompactionPrompt({...v,selectedIndex:O})},Bi=y=>{if(!Z)return;let v=R.compactionPromptSpec();if(!v)return;if(y.kind==="hint"){if(y.action==="cancel"){Wr();return}v.options[v.selectedIndex]?.key==="y"?Ho():Wr();return}let C=v.options[y.index];if(C){if(y.select===!0){y.index!==v.selectedIndex&&R.setCompactionPrompt({...v,selectedIndex:y.index});return}C.key==="y"?Ho():Wr()}},uo=y=>{if(!Z)return!1;if(y.type==="key"){if(y.name==="escape")return Wr(),!0;if(y.name==="up")return vs(-1),!0;if(y.name==="down")return vs(1),!0;if(y.name==="enter"){let v=R.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Ho():Wr(),!0}}if(y.type==="char"){let v=y.ch.toLowerCase();if(v==="y"||v==="1")return Ho(),!0;if(v==="n"||v==="2")return Wr(),!0}return!0},Hi=y=>R.isHelpPromptActive()?(y.type==="key"&&y.name==="ctrl-g",R.setHelpPrompt(null),!0):!1,md=["tools","plan","thoughts","diffs","mouse","enter","sidebar","theme"],gd=0,jr=null,qr=[],zr=[],wn=[],Gn=0,On=null,yd=null,Cn=(y,v)=>{y!=="chooser"&&(U=null),On=y,yd=v,R.setFormPrompt(AP(v))},Fn=y=>{On===y&&(On=null,yd=null,U=null,K=new Map,R.setFormPrompt(null))},_f=y=>{switch(y){case"tools":return o.toolsExpanded?"expanded":"collapsed";case"plan":return o.planExpanded?"expanded":"collapsed";case"thoughts":return o.showThoughts?"shown":"hidden";case"diffs":return o.showFileUpdates;case"mouse":return o.mouseEnabled?"on":"off";case"enter":return o.defaultEnterAction;case"sidebar":return R.isSidebarVisible()?"shown":"hidden";case"theme":return Qa}},$f=y=>{switch(y){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";case"theme":return"Theme"}},yr=()=>({title:"Session options",rows:md.map(y=>({id:y,kind:"select",label:$f(y),value:_f(y)})),cursor:gd,hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 cycle"},{label:"\u23CE next",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]}),Of=()=>{On==="options"&&Cn("options",yr())},fo=()=>{if(On==="options"){Fn("options");return}gd=0,Cn("options",yr())},Kr=()=>{jr!==null&&Cn("questions",I$(jr,qr,wn,Gn))},wd=()=>{jr=null,qr=[],zr=[],wn=[],Gn=0,Fn("questions")},Fg=async()=>{if(jr!==null){wd();return}try{let v=await b.request(kP,{sessionId:me}),C=C4(v.questions??[]);if(C.length===0){R.notify("no open questions");return}let O=A4(C);jr=O,Gn=0,qr=O.map(T=>R4(T.representative)),zr=O.map(()=>!1),wn=O.map(()=>!1),Kr()}catch(y){R.notify("clarifier unavailable"),ge({src:"questions",step:"list_failed",error:y.message})}},po=()=>{let y=Rg.find(C=>C.name===Qa);if(y===void 0)return;Zy(y.palette,{...y.overrides,background:Fr,foreground:S$}),$S(),Hg(),qg(),Oe(),R.fullRedraw();let v=cS(y.palette,Qa,Fr);v!==void 0&&R.notify(v)},Ui=(y=1)=>{if(Rg.length===0){R.notify("no themes available");return}let v=q_(Rg.map(C=>C.name),Qa,y);v!==void 0&&(Qa=v,po())},bn=null,Wi=y=>{bn!==null&&(clearTimeout(bn),bn=null),e.tui.themeBackground===void 0&&(Fr!==void 0&&Fr.kind==="rgb"&&y.kind==="rgb"&&Fr.r===y.r&&Fr.g===y.g&&Fr.b===y.b||(Fr=y,po()))};v$=y=>{e.tui.themeBackground===void 0&&(bn!==null&&clearTimeout(bn),bn=setTimeout(()=>{bn=null,Wi(zM(y))},200),bn.unref?.(),we("\x1B]11;?\x07"))},x$=Wi;let Uo=(y,v=1)=>{switch(y){case"tools":o.toolsExpanded=!o.toolsExpanded,Ft.clear(),Mt.clear(),Hg();break;case"plan":o.planExpanded=!o.planExpanded,Yn=null,Oe();break;case"thoughts":o.showThoughts=!o.showThoughts,R.setHideThoughts(!o.showThoughts);break;case"diffs":o.showFileUpdates=o.showFileUpdates==="diff"?"edit":"diff",wr.clear(),qg();break;case"mouse":{let C=!R.isMouseEnabled();R.setMouseEnabled(C),o.mouseEnabled=C;break}case"enter":o.defaultEnterAction=o.defaultEnterAction==="amend"?"enqueue":"amend";break;case"sidebar":Zg(!R.isSidebarVisible());break;case"theme":Ui(v);break}Of()},nr=y=>{(async()=>{try{switch(y){case"tools":case"plan":R.notify(`${$f(y)} is session-only \u2014 not saved`);return;case"thoughts":await Zi("showThoughts",o.showThoughts);break;case"diffs":await Zi("showFileUpdates",o.showFileUpdates);break;case"mouse":await Zi("mouse",o.mouseEnabled);break;case"enter":await Zi("defaultEnterAction",o.defaultEnterAction);break;case"sidebar":await hy(R.isSidebarVisible());break;case"theme":await Zi("theme",Qa);break}R.notify(`saved default: ${$f(y)} ${_f(y)}`)}catch(v){R.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},bd=y=>{let v=C=>md[C];switch(y.type){case"row":{gd=y.row;let C=y.viaDigit===!0?v(y.row):void 0;C?Uo(C):Of();return}case"cycle":{let C=v(y.row);C&&(gd=y.row,Uo(C,y.delta));return}case"advance":{let C=v(y.row);C&&Uo(C);return}case"save":{let C=v(y.row);C&&nr(C);return}case"close":case"cancel":Fn("options");return;default:return}},fl=(y,v)=>{if(y.type==="key"){if(y.name==="ctrl-o")return Fn("options"),!0;if(y.name==="ctrl-d")return Fn("options"),!1}return bd(Vu(v,y)),!0},kd="title",pl=(y,v)=>{let C=y.rows.find(O=>O.id===v);return C?.kind==="text"?C.editor.text:""},hl=y=>{if(On!=="title"){if(r.readonly===!0){R.notify("view-only: rename disabled");return}if(me==="__new__"){R.notify("no active session to rename");return}Cn("title",EP({title:"Rename session",id:kd,label:"title:",initial:y,hints:[{label:"\u23CE save",action:"commit"},{label:"Esc cancel",action:"close"}]}))}},vd=y=>{let v=pl(y,kd).trim(),C=me;Fn("title"),v.length!==0&&Au(t,C,v).catch(O=>{R.notify(`rename failed: ${O.message}`)})},E=(y,v)=>{switch(v.type){case"commit":vd(y);return;case"close":case"cancel":Fn("title");return;case"edited":Cn("title",y);return;default:return}},M=(y,v)=>(E(v,Vu(v,y)),!0),U=null,K=new Map,se=(y,v)=>{let C=y.options.find(N=>N.value===v);if(C)return C.value;let O=v.toLowerCase(),T=y.options.filter(N=>N.value.toLowerCase().startsWith(O));return T.length===1?T[0].value:null},oe=y=>{if(r.readonly===!0)return R.notify(`view-only: ${y} switching disabled`),null;if(me==="__new__")return R.notify("no active session yet"),null;let v=gr.find(C=>C.id===y);return!v||v.options.length===0?(R.notify(`no ${y} option advertised for this session`),null):v},pe=y=>{if(On==="chooser"&&U?.kind==="values"&&U.configId===y)return;let v=oe(y);v&&(U={kind:"values",configId:y},Cn("chooser",IP(v)))},nt=()=>{if(gr.length===0){R.notify("no config options advertised for this session");return}U={kind:"index"},K=new Map,Cn("chooser",qk(gr,K))},Dt=y=>{Cn("chooser",{...qk(gr,K),cursor:y})},tn=()=>{let y=new Map(gr.map(v=>[v.id,v.currentValue]));for(let[v,C]of K)y.get(v)!==C&&Et(v,C);K=new Map},Et=(y,v)=>{R.notify(`switching ${y} to ${v}\u2026`),b.request("session/set_config_option",{sessionId:me,configId:y,value:v}).catch(C=>{R.notify(`${y} switch failed: ${C instanceof Error?C.message:String(C)}`)})},xs=(y,v)=>{(async()=>{try{if(y==="agent")await Jo(v);else{let C=It||td||"";if(!C){R.notify(`can't save a ${y} default without an agent`);return}await Pl(C,y,v)}R.notify(`saved default: ${y} ${v}`)}catch(C){R.notify(`save failed: ${C instanceof Error?C.message:String(C)}`)}})()},Sd=(y,v)=>{let C=U;if(C===null)return;let O=H=>y.rows[H]?.id,T=H=>{let te=O(H);return te===void 0?void 0:gr.find(le=>le.id===te)},N=H=>K.get(H.id)??H.currentValue;switch(v.type){case"row":Cn("chooser",{...y,cursor:v.row});return;case"cycle":{let H=T(v.row);if(!H)return;K.set(H.id,CP(H,N(H),v.delta)),Dt(v.row);return}case"advance":tn(),Fn("chooser");return;case"commit":{let H=O(v.row);if(C.kind!=="values"||H===void 0)return;Fn("chooser"),Et(C.configId,H);return}case"save":{if(C.kind==="values"){let te=O(v.row);te!==void 0&&(xs(C.configId,te),Fn("chooser"),Et(C.configId,te));return}let H=T(v.row);if(H){let te=N(H);xs(H.id,te),te!==H.currentValue&&Et(H.id,te)}return}case"close":K=new Map,Fn("chooser");return;case"cancel":K=new Map,Fn("chooser");return;default:return}},ji=(y,v)=>U===null?!1:(Sd(v,Vu(v,y)),!0),qi=y=>{let v=yd;if(On===null||v===null)return!1;switch(On){case"questions":return Ff(y);case"options":return fl(y,v);case"title":return M(y,v);case"chooser":return ji(y,v)}},ml=y=>{let v=yd;if(!(On===null||v===null))for(let C of TP(v,y))switch(On){case"options":bd(C);break;case"title":E(v,C);break;case"chooser":Sd(v,C);break;case"questions":gl(jr===null?{type:"noop"}:R$(C,jr,qr,zr,wn,me));break}},gl=y=>{switch(y.type){case"noop":return;case"row":Gn=y.selectedRow,Kr();return;case"cycle":Gn=y.selectedRow,qr[y.selectedRow]=y.newValueIndex,zr[y.selectedRow]=!0,wn[y.selectedRow]=!1,Kr();return;case"dismiss-toggle":{let v=y.selectedRow;wn[v]?(wn[v]=!1,zr[v]=!1):(wn[v]=!0,zr[v]=!0),Kr();return}case"discard":wd();return;case"save":{let v=y.dispatches;if(wd(),v.length===0)return;(async()=>{let C=0,O=0,T=0;for(let H of v)try{await b.request(H.method,H.params),H.type==="dismiss"?O++:C++}catch(te){T++,ge({src:"questions",step:"dispatch_failed",method:H.method,error:te.message})}let N=[];C>0&&N.push(`${C} answered`),O>0&&N.push(`${O} dismissed`),T>0&&N.push(`${T} failed`),N.length>0&&R.notify(`clarifier: ${N.join(", ")}`)})();return}}},Ff=y=>jr===null?!1:(gl(P4(y,!0,jr,qr,zr,wn,Gn,me)),!0),rr=()=>{if(!I){I=!0,$?($.cancel(),$=null,F=null):F!==null&&(Gs(t,F).catch(()=>{}),F=null),process.off("SIGINT",Mf),process.platform!=="win32"&&process.off("SIGCONT",xf),de!==null&&(clearInterval(de),de=null),Rt!==null&&(clearInterval(Rt),Rt=null),ro();for(let y of ws.values())clearTimeout(y);ws.clear(),US(),HS(),Kt!==null&&(clearInterval(Kt),Kt=null),Ve!==null&&(clearInterval(Ve),Ve=null),qn!==null&&(k4(qn,{recursive:!0,force:!0}),qn=null),R.clearWindowTitle(),R.stop({keepFullscreen:!0}),ha(Qe,Zt).catch(()=>{}),w.close().catch(()=>{})}},xd=(y=0)=>{rr(),Wt&&(Wt(null),Wt=null),y!==0&&process.exit(y)},yl=async()=>{if(ge({src:"switch-session",step:"entered",finishSessionNull:Wt===null}),!Wt)return;$?($.cancel(),$=null,F=null):F!==null&&(Gs(t,F).catch(()=>{}),F=null),ed(),ro(),R.setSynthesisIndicator(null);let y=Be.state().buffer.join(`
|
|
297
|
-
`);y.replace(/\s+$/,"").length>0&&Ur(y),R.pauseRepaint(),R.stop({keepFullscreen:!0}),ha(Qe,Zt).catch(()=>{});let v=!1,C=null;try{let O=null,T=null,N=await go();for(;O===null;){let ie=await Ks(t,{includeNonInteractive:!0}),ln=[];try{ln=await Aa(t)}catch{}let xt=vn=>ff({cwd:vn,config:N,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},...r.agentId!==void 0?{fallbackAgentId:r.agentId}:{},availableAgents:ln}),qe=vn=>ff({cwd:vn,config:N,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},availableAgents:ln}),{agentId:ht,model:Jt}=await xt(tt),Fe=await nS(n,{cwd:tt,sessions:ie,config:e,target:t,currentSessionId:me,prefs:i,...ht?{composerAgentId:ht}:{},...Jt?{composerModel:Jt}:{},...ln.length>0?{availableAgents:ln}:{},onComposerAgentChange:(vn,Gi)=>{mf(o,vn,Gi)},onCwdChange:qe});if(Fe.kind==="abort")return;if(Fe.kind==="exit"){v=!0,xd(0);return}if(Fe.kind==="new"){O={choice:Fe,sessions:ie};break}if(Fe.kind==="fork"){let vn=await P$(n,t,Fe,ie);if(vn.kind==="cancel")return;if(vn.kind==="back")continue;O={choice:{kind:"attach",sessionId:vn.ctx.sessionId,...vn.ctx.agentId?{agentId:vn.ctx.agentId}:{}},sessions:ie},T={readonly:!1,cwd:vn.ctx.cwd},vn.ctx.resumeHint!==void 0&&(T.resumeHint=vn.ctx.resumeHint);break}let un=ie.find(vn=>vn.sessionId===Fe.sessionId);if(!(un!==void 0&&!!un.importedFromMachine&&!un.remote&&!un.upstreamSessionId&&Fe.readonly!==!0)){if(t.isLocal&&un&&!un.importedFromMachine&&!un.remote&&Fe.readonly!==!0&&!(await Ju(un.cwd)).ok){Fe.installStatus?.finalize(),delete Fe.installStatus;let Gi=await Ja(n,un,{defaultCwd:mt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Gi.kind==="cancel")return;if(Gi.kind==="back")continue;O={choice:Fe,sessions:ie},T={readonly:!1,cwd:Gi.path,resumeHint:{agentId:Fe.agentId??un.agentId??"",cwd:Gi.path,upstreamSessionId:""}};break}O={choice:Fe,sessions:ie};break}let Gf={...r,readonly:!1};Fe.installStatus?.finalize(),delete Fe.installStatus;let xl=await T$(n,t,un,Fe,Gf);if(xl.kind==="cancel")return;xl.kind!=="back"&&(O={choice:Fe,sessions:ie},T={readonly:Gf.readonly===!0,cwd:xl.ctx.cwd},xl.ctx.resumeHint!==void 0&&(T.resumeHint=xl.ctx.resumeHint))}let{choice:H}=O;if(r.terminalHostLauncher&&(H.kind==="attach"||H.kind==="new")){H.installStatus?.finalize(),delete H.installStatus,C=await mS(H,O.sessions,T?.cwd??tt);return}let te=Wt;if(Wt=null,rr(),v=!0,H.kind==="new"){let{sessionId:ie,agentId:ln,...xt}=r,qe={...xt,cwd:H.cwd??tt,forceNew:!0,readonly:!1};H.prompt!==void 0&&(qe.initialPrompt=H.prompt),H.attachments&&H.attachments.length>0&&(qe.initialAttachments=H.attachments),H.agentId!==void 0&&(qe.agentId=H.agentId,H.agentExplicit&&mf(o,H.agentId,H.model)),H.model!==void 0&&(qe.model=H.model),H.installStatus!==void 0&&(qe.installStatus=H.installStatus),te(qe);return}if(H.kind!=="attach")return;let le={...r,sessionId:H.sessionId,cwd:T?.cwd??tt,readonly:T?.readonly??H.readonly===!0};H.agentId!==void 0&&(le.agentId=H.agentId),T?.resumeHint!==void 0?le.resumeHint=T.resumeHint:delete le.resumeHint,H.jumpToRecordedAt!==void 0?le.jumpToRecordedAt=H.jumpToRecordedAt:delete le.jumpToRecordedAt,H.installStatus!==void 0?le.installStatus=H.installStatus:delete le.installStatus,te(le)}finally{!v&&Wt&&(R.start({skipFullscreen:!0}),R.resumeRepaint(),C&&R.notify(C))}},Gr=async(y="next")=>{if(!Wt)return;let v=await Ks(t,{status:"warm"});if(v.length<=1)return;let C=v.findIndex(ie=>ie.sessionId===me),N=((C===-1?0:C)+(y==="prev"?-1:1)+v.length)%v.length,H=v[N],te=Wt;Wt=null,rr();let le={...r,sessionId:H.sessionId,cwd:tt,readonly:!1,resolved:H};H.agentId!==void 0&&(le.agentId=H.agentId),te(le)},Wo=async y=>{if(!Wt)return;let v=await Ks(t,{includeNonInteractive:!0}),C=y.trim();if(!C){R.notify("usage: /session <id|next|prev>");return}let O=C.startsWith(sn)?[C]:[C,sn+C],T=v.find(te=>O.includes(te.sessionId));if(!T){let te=v.filter(le=>O.some(ie=>le.sessionId.startsWith(ie)));if(te.length===1)T=te[0];else if(te.length>1){R.notify(`ambiguous session id: ${C} (${te.length} matches)`);return}}if(!T){R.notify(`no session matches: ${C}`);return}if(T.sessionId===me){R.notify("already on that session");return}if(r.terminalHostLauncher){let te=await mS({kind:"attach",sessionId:T.sessionId},v,T.cwd??tt);R.notify(te);return}let N=Wt;Wt=null,rr();let H={...r,sessionId:T.sessionId,cwd:T.cwd??tt,readonly:!1,resolved:T};T.agentId!==void 0&&(H.agentId=T.agentId),delete H.resumeHint,N(H)},zi=y=>{switch(y.type){case"send":o.defaultEnterAction==="amend"?Nf(y.text,y.attachments,y.displayText):jo(y.text,y.attachments,y.displayText);return;case"amend":o.defaultEnterAction==="amend"?jo(y.text,y.attachments,y.displayText):Nf(y.text,y.attachments,y.displayText);return;case"queue-edit":{let v=Lf(y.index);if(!v)return;let C=[];y.text.length>0&&C.push({type:"text",text:y.text});for(let O of y.attachments)C.push({type:"image",data:O.data,mimeType:O.mimeType});b.request("hydra-acp/prompt/update",{sessionId:me,messageId:v,prompt:C}).then(O=>{let T=O;if(T.updated||T.reason==="ok"){let N=Is.get(v);N&&(N.text=y.text,N.displayText=y.displayText??y.text,N.attachments=y.attachments)}else R.notify(`queue edit skipped (${T.reason})`)}).catch(O=>{R.notify(`queue edit failed: ${O.message}`)});return}case"queue-remove":{let v=Lf(y.index);if(!v)return;b.request("hydra-acp/prompt/cancel",{sessionId:me,messageId:v}).then(C=>{let O=C;!O.cancelled&&O.reason!=="ok"&&R.notify(`queue cancel skipped (${O.reason})`)}).catch(C=>{R.notify(`queue cancel failed: ${C.message}`)});return}case"cancel":{if(R.isOverlayOpen()){$&&($.cancel(),$=null,F=null),R.closeBtwOverlay();return}let v=tr[0];if(y.prefill&&v){let C=Ln.size===0,O=Be.state().buffer.every(T=>T==="");C&&O&&(id={text:v.text,attachments:v.attachments})}v?v.cancel():W>0&&cl(),ll();return}case"exit":hd();return;case"plan-toggle":Df(y.on);return;case"redraw-banner":R.setBanner({});return;case"redraw":R.fullRedraw();return;case"scroll-to-top":R.scrollToTop();return;case"scroll-to-bottom":R.scrollToBottom();return;case"switch-session":yl().catch(v=>{ge({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":Gr("next").catch(()=>{});return;case"prev-live-session":Gr("prev").catch(()=>{});return;case"toggle-options":fo();return;case"toggle-sidebar":Zg(!R.isSidebarVisible());return;case"toggle-questions":Fg();return;case"toggle-thoughts":o.showThoughts=!o.showThoughts,R.setHideThoughts(!o.showThoughts),R.notify(o.showThoughts?"thoughts shown":"thoughts hidden");return;case"show-help":ul();return;case"escalate-search":R.enterScrollbackSearch(),R.updateScrollbackSearchTerm(y.query);return;case"attachment-request":Ng(y.source);return;case"edit-in-editor":Lg();return}},Lg=async()=>{let y=await Gm(Be.expandedText(),{suspend:()=>R.stop(),resume:()=>R.start(),notify:v=>R.notify(v)});y!==null&&(Be.setBuffer(y,Be.state().attachments),R.setAttachments(Be.state().attachments),R.refreshPrompt())},Id=async y=>{if(!In){R.notify("agent does not accept image attachments");return}let v=0;for(let C of y){if(C.startsWith("data:")){let T=Yk(C);if(!T){R.notify("unsupported data: URI");continue}if(T.sizeBytes>Xs){R.notify(`image too large (${Mr(T.sizeBytes)}, max ${Mr(Xs)})`);continue}Be.addAttachment({mimeType:T.mimeType,data:T.data,name:"pasted image",sizeBytes:T.sizeBytes}),v++;continue}let O=Qu(C);if(!O){R.notify(`unsupported image type: ${Ri.basename(C)}`);continue}try{let T=await fS.readFile(C);if(T.length>Xs){R.notify(`image too large (${Mr(T.length)}, max ${Mr(Xs)})`);continue}Be.addAttachment({mimeType:O,data:T.toString("base64"),name:Ri.basename(C),sizeBytes:T.length}),v++}catch(T){R.notify(`cannot read ${Ri.basename(C)}: ${T.message}`)}}v>0&&(R.setAttachments(Be.state().attachments),R.refreshPrompt())},Ng=async(y="clipboard")=>{let v=y==="primary"?await DP():await jm();if(!v.ok){R.notify(v.reason);return}if(v.kind==="image"){if(!In){R.notify("agent does not accept image attachments");return}Be.addAttachment(v.attachment),R.setAttachments(Be.state().attachments),R.refreshPrompt();return}let C=Be.feed({type:"paste",text:v.text});for(let O of C)zi(O);R.refreshPrompt()},Ki=y=>{let v=y.attachmentCount>0?`${y.text} \xB7 \u{1F4CE}\xD7${y.attachmentCount}`:y.text;return y.held?`\u23F8 ${v}`:v},Cd=(y,v)=>{let C=Array.isArray(v)?v:[],O="",T=0;for(let N of C){if(!N||typeof N!="object")continue;let H=N;H.type==="text"&&typeof H.text=="string"?O+=H.text:H.type==="image"&&(T+=1)}return{messageId:y,text:ot(O),attachmentCount:T}},Ln=new Map,Jn=[],Is=new Map,Jr=new Set,Vr=null,ho=()=>{let y=[...Ln.values()],v=y.map(Ki);R.setQueuedPrompts(v),R.setBanner({queued:y.length}),R.setSidebarSnapshot({queued:y.length}),Be.setQueue(y.map(C=>C.text))},Lf=y=>[...Ln.values()][y]?.messageId;if(oo&&oo.length>0){for(let y of oo){if(y.position===0){ve=y.messageId;continue}Ln.set(y.messageId,Cd(y.messageId,y.prompt))}Ln.size>0&&ho()}let jo=(y,v,C)=>{R.scrollToBottom(),!Rd(y)&&(Ur(y,C),wl(y,v,C))},Vn=(y,v,C)=>{if(R.scrollToBottom(),Rd(y))return;if(Ur(y,C),!bs||ve===void 0){wl(y,v,C);return}let O=ve,T=[];y.length>0&&T.push({type:"text",text:y});for(let te of v)T.push({type:"image",data:te.data,mimeType:te.mimeType});let N={text:y,displayText:C??y,attachments:v,flushed:!1};Jn.push(N);let H=()=>{let te=Jn.indexOf(N);te>=0&&Jn.splice(te,1),N.messageId!==void 0&&Is.delete(N.messageId)};b.request("hydra-acp/prompt/amend",{sessionId:me,targetMessageId:O,prompt:T}).then(te=>{let le=te;if(le.amended&&le.reason==="ok"){Je(1,"self");return}if(H(),le.reason==="target_completed"){R.notify("previous response finished \u2014 press Enter to send as a new turn"),Be.setBuffer(y,v),R.refreshPrompt();return}if(le.reason==="target_cancelled"){R.notify("amend skipped \u2014 previous turn was cancelled"),Be.setBuffer(y,v),R.refreshPrompt();return}if(le.reason==="target_not_found"){R.notify("amend skipped \u2014 no matching prompt"),Be.setBuffer(y,v),R.refreshPrompt();return}}).catch(te=>{H(),R.notify(`amend failed: ${te.message}`),Be.setBuffer(y,v),R.refreshPrompt()})},Nf=(y,v,C)=>{if(R.scrollToBottom(),Rd(y))return;if(Ur(y,C),!Dr){Vn(y,v,C);return}let O=[];y.length>0&&O.push({type:"text",text:y});for(let H of v)O.push({type:"image",data:H.data,mimeType:H.mimeType});let T={text:y,displayText:C??y,attachments:v,flushed:!1};Jn.push(T);let N=()=>{let H=Jn.indexOf(T);H>=0&&Jn.splice(H,1),T.messageId!==void 0&&Is.delete(T.messageId)};b.request("_session/steering",{sessionId:me,prompt:O}).then(H=>{let te=H;if(te.outcome==="injected"){let le=Jn.indexOf(T);le>=0&&Jn.splice(le,1),T.flushed=!0,A({kind:"user-text",text:T.displayText,attachments:T.attachments}),Vr=T;return}if(te.outcome==="startedNewTurn"){te.detached!==!0&&Je(1,"self");return}N(),R.notify("steering failed"),Be.setBuffer(y,v),R.refreshPrompt()}).catch(H=>{if(H.code===-32601){N(),Vn(y,v,C);return}N(),R.notify(`steering failed: ${H.message}`),Be.setBuffer(y,v),R.refreshPrompt()})},Df=async y=>{if(Do.length===0){R.notify("no modes advertised by agent");return}let v=R.currentModeId(),C=Do.findIndex(N=>N.id===v),O=C===-1?0:(C+1)%Do.length,T=Do[O]?.id;if(T){R.setBanner({currentMode:T});try{await b.request("session/set_mode",{sessionId:me,modeId:T})}catch(N){R.notify(`set_mode failed: ${N.message}`)}}},Rd=y=>{let v=y.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
|
|
298
|
-
`))return!1;let C=v.indexOf(" "),O=C===-1?v:v.slice(0,C);switch(O){case"/quit":case"/exit":return hd(),!0;case"/clear":return Gt.clear(),Cs.clear(),L.length=0,ee.clear(),Te=null,X=null,$e=null,Yr.clear(),wr.clear(),ze.clear(),Ft.clear(),ae.clear(),lt.clear(),We.clear(),R.clearScrollback(),!0;case"/help":{let T=[{prefix:" ",body:"Built-in commands:",bodyStyle:"local-heading"}];for(let N of Cf)T.push({prefix:" ",body:` ${N.name.padEnd(12)} ${N.description??""}`,bodyStyle:"local-item"});if(dd.length>0){T.push({prefix:" ",body:"Agent commands:",bodyStyle:"local-heading"});for(let N of dd)T.push({prefix:" ",body:` ${N.name.padEnd(12)} ${N.description??""}`,bodyStyle:"local-item"})}return R.appendLines(T),!0}case"/agent":case"/model":case"/mode":{let T=O.slice(1),N=C===-1?"":v.slice(C+1).trim();if(!N)return pe(T),!0;let H=oe(T);if(!H)return!0;let te=se(H,N);return te===null?(R.notify(`unknown ${T}: ${N}`),!0):te===H.currentValue?(R.notify(`already on ${T} ${te}`),!0):(Et(T,te),!0)}case"/hydra":{let T=C===-1?"":v.slice(C+1).trim(),N=T.length>0?T.split(/\s+/):[];return N[0]!=="config"||N.length>2?!1:N.length===1?(nt(),!0):gr.some(H=>H.id===N[1])?(pe(N[1]),!0):!1}case"/title":{let T=C===-1?"":v.slice(C+1).trim();return T?r.readonly===!0?(R.notify("view-only: rename disabled"),!0):(Au(t,me,T).catch(N=>{R.notify(`rename failed: ${N.message}`)}),!0):(hl(R.sessionTitle()??""),!0)}case"/sessions":return R.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"notice"}]),!0;case"/resume":return yl().catch(T=>{ge({src:"switch-session-failed",stack:T instanceof Error?T.stack??T.message:String(T)})}),!0;case"/session":{let T=C===-1?"":v.slice(C+1).trim();return T?T==="next"||T==="prev"?(Gr(T).catch(N=>{R.notify(`session ${T} failed: ${N.message}`)}),!0):(Wo(T).catch(N=>{R.notify(`session switch failed: ${N.message}`)}),!0):(yl().catch(N=>{ge({src:"switch-session-failed",stack:N instanceof Error?N.stack??N.message:String(N)})}),!0)}case"/rename":{let T=C===-1?"":v.slice(C+1).trim(),N=T.length>0?`/hydra title ${T}`:"/hydra title";return Ur(v,v),wl(N,[],v),!0}case"/btw":{let T=C===-1?"":v.slice(C+1).trim();if(!T)return R.isOverlayOpen()?($&&($.cancel(),$=null,F=null),R.closeBtwOverlay(),!0):(R.reopenBtwOverlay()||R.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"notice-error"}]),!0);if(me==="__new__")return R.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"notice-error"}]),!0;Y+=1;let N=Y;$&&($.cancel(),$=null);let H=null;F!==null&&!J?H=F:F!==null&&(Gs(t,F).catch(()=>{}),F=null),J=!1,R.openBtwOverlay(),R.setBtwOverlayStatus({label:"busy",style:"busy"});let te=new Bm({getMaxWidth:()=>{let xt=R.width();return xt>0?xt:void 0}});te.on("changed",()=>{R.setBtwOverlayContent(te.getLines())});let le={};te.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:T}]});let ie=xt=>{te.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:xt}})},ln={};return H!==null&&(ln.reuseSessionId=H),MP(t,me,T,ln).then(xt=>{if(N!==Y){xt.cancel();return}$=xt,F=xt.sessionId,R.setBtwOverlayMeta({sessionId:xt.sessionId}),xt.on("event",qe=>{if(N===Y)if(qe.kind==="update"){te.append(qe.update);let ht=Ws(qe.update);if(ht&&ht.kind==="usage-update"){let Jt=!1;ht.used!==void 0&&le.used!==ht.used&&(le.used=ht.used,Jt=!0),ht.size!==void 0&&le.size!==ht.size&&(le.size=ht.size,Jt=!0),ht.costAmount!==void 0&&le.costAmount!==ht.costAmount&&(le.costAmount=ht.costAmount,Jt=!0),ht.costCurrency!==void 0&&le.costCurrency!==ht.costCurrency&&(le.costCurrency=ht.costCurrency,Jt=!0),Jt&&R.setBtwOverlayMeta({usage:{...le}})}}else qe.kind==="completed"?(R.setBtwOverlayStatus({label:"done",style:"done"}),$=null):qe.kind==="cancelled"?(R.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),$=null,F=null):qe.kind==="errored"&&(R.setBtwOverlayStatus({label:"errored",style:"errored"}),ie(`btw errored: ${qe.error.message}`),F!==null&&Gs(t,F).catch(()=>{}),$=null,F=null)})}).catch(xt=>{if(N!==Y)return;let qe=xt instanceof Error?xt.message:String(xt);R.setBtwOverlayStatus({label:"errored",style:"errored"}),ie(`btw startup failed: ${qe}`),R.appendLines([{prefix:" ",body:`btw startup failed: ${qe}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(me==="__new__")return R.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"notice-error"}]),!0;let T=C===-1?"":v.slice(C+1).trim(),N=me;return(async()=>{try{let H=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(N)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!H.ok){let qe=await H.text().catch(()=>"");R.appendLines([{prefix:" ",body:`/export failed: HTTP ${H.status} ${qe}`.trim(),bodyStyle:"notice-error"}]);return}let te=await H.text(),le=new Date().toISOString().replace(/[:.]/g,"-"),ie=`hydra-${st(N)}-${le}.md`,ln=T.length>0?mt(T):ie,xt=Ri.resolve(ln);await fS.mkdir(Ri.dirname(xt),{recursive:!0}),await fS.writeFile(xt,te,{encoding:"utf8",mode:384}),R.appendLines([{prefix:" ",body:`Wrote ${xt}`,bodyStyle:"notice-ok"}])}catch(H){R.appendLines([{prefix:" ",body:`/export failed: ${H.message}`,bodyStyle:"notice-error"}])}})(),!0}default:return!1}},wl=async(y,v,C)=>{let O=[];y.length>0&&O.push({type:"text",text:y});for(let qe of v)O.push({type:"image",data:qe.data,mimeType:qe.mimeType});Je(1,"self");let T={text:y,displayText:C??y,attachments:v,flushed:!1};Jn.push(T),W===1&&(at=!1);let N=!1,H=!1,te=null,le=qe=>{typeof xe<"u"&&xe!==null&&xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:qe,bodyStyle:"tool-status-fail"}])},ie=!1,ln={text:y,attachments:v,cancel:()=>{if(at){at=!1,ie=!0,le("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),b.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(ht=>{le(`force-stop failed: ${ht.message}`)});return}if(N)return;N=!0,b.notify("session/cancel",{sessionId:me}).catch(()=>{});let qe=Date.now();te=setTimeout(()=>{H||Ut>=qe||(at=!0,le("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent)."))},Za)}};tr.push(ln);let xt;try{let qe=await b.request("session/prompt",{sessionId:me,prompt:O});qe&&typeof qe.stopReason=="string"&&(xt=qe.stopReason)}catch(qe){let ht=Jn.indexOf(T);ht>=0&&Jn.splice(ht,1),T.messageId!==void 0&&Is.delete(T.messageId),ie?R.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):R.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:qe.message,bodyStyle:"tool-status-fail"}])}finally{H=!0;let qe=tr.indexOf(ln);if(qe>=0&&tr.splice(qe,1),qe===0&&tr.length>0&&(at=!1),te!==null&&(clearTimeout(te),te=null),Je(-1),T.flushed&&Vr===T){let ht=T.messageId!==void 0&&Jr.has(T.messageId);ht&&T.messageId!==void 0&&Jr.delete(T.messageId);let Jt={kind:"turn-complete"};xt!==void 0&&(Jt.stopReason=xt),ht&&(Jt.amended=!0),A(Jt),Vr=null}if(id!==null){let{text:ht,attachments:Jt}=id;id=null,Be.state().buffer.every(un=>un==="")&&(Be.setBuffer(ht,Jt),R.refreshPrompt())}}},Gt=new Map;Xa=()=>{for(let y of Gt.values())if(uv(y.status))return!0;return!1};let Yr=new Map,wr=new Map,Cs=new Map,L=[],ee=new Map,fe=[],Q=0,Se=`tools:${Q}`,ze=new Map,Ft=new Map,Mt=new Set,dn=new Map,ae=new Map,lt=new Map,We=new Map,Te=null,X=null,$e=null,_e=null,vt=null,St=!1,Yn=null,Qr=e.tui.maxToolItems,cn=e.tui.maxPlanItems,Rs=()=>({maxPlanItems:Yn??o.planExpanded?1/0:cn}),qo=y=>{let v=F4(y.entries);St&&(St=!1,L4({stale:!0,hasKey:R.hasKey("plan"),prevFingerprint:vt,fingerprint:v})==="fresh"&&R.clearKey("plan")),vt=v;let C=Ro(y,Rs());C.length>0&&R.upsertLines("plan",[{body:""},...C]);let O=y.entries.length>0&&y.entries.every(T=>(T.status??"pending")==="completed");R.setStickyBottomKey(O?null:"plan")},Oe=()=>{if(_e===null)return;let y=Ro(_e,Rs());y.length>0&&R.upsertLines("plan",[{body:""},...y])},Xe="",kn=null,bl=0,Dg,W$=()=>{if(kn===null)return;let y=R.width(),v=Ao(Xe,y>0?{maxWidth:y}:void 0);v.length!==0&&R.upsertLines(kn,v)},j$=(y,v)=>{y.length!==0&&(kn===null&&(R.ensureSeparator(),kn=`agent:${bl}`,bl+=1,Xe="",Dg=v),Xe+=y,lt.set(kn,Xe),W$())},Xr=()=>{kn=null,Xe="",Dg=void 0},Ad="",zo=null,xS=0,Bg,q$=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),z$=()=>{if(zo===null||Ad.length===0)return;let y=Hc(Ad);y.length!==0&&R.upsertLines(zo,y)},IS=y=>{let v=ae.get(y);if(v===void 0)return[];let C=Hc(v.text);return v.workerTaskId&&C.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"muted"}),C},K$=(y,v)=>{y.length!==0&&(zo===null&&(R.ensureSeparator("thought"),zo=`thought:${xS}`,xS+=1,Ad="",Bg=v),Ad+=y,ae.set(zo,{text:Ad,workerTaskId:v}),z$())},Zr=()=>{Bg=void 0,zo=null,Ad=""},CS=y=>B4({...y,collapsedLimit:Qr}),RS=y=>Ft.get(y)??o.toolsExpanded,sr=()=>{if(Te===null)return;let{lines:y,rowOwners:v}=CS({order:L,states:Gt,startedAt:Te,endedAt:X,stopReason:$e,expanded:RS(Se),perToolExpanded:Mt});R.upsertLines(Se,y),dn.set(Se,v)},Bf=y=>{let v=ze.get(y);if(!v)return;let{lines:C,rowOwners:O}=CS({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:RS(y),perToolExpanded:Mt});R.upsertLines(y,C),dn.set(y,O)},Hg=()=>{Te!==null&&!ze.has(Se)&&sr();for(let y of ze.keys())Bf(y)},Ug=()=>{Te!==null&&ze.set(Se,{order:[...L],states:new Map(Gt),startedAt:Te,endedAt:X??Date.now(),stopReason:$e,rowOwners:dn.get(Se)??[]})},AS=y=>{Q+=1,Se=`tools:${Q}`,Te=y??Date.now(),X=null,$e=null,sr()};function G$(y){if(!y||typeof y!="object")return null;let v=y,C=Array.isArray(v.content)?v.content:void 0,O=[],T=N=>{if(typeof N=="string"){O.push({text:zt(N)});return}if(N&&typeof N=="object"){let H=N;typeof H.__hydraBlob=="string"&&O.push({hash:H.__hydraBlob})}};for(let N of C??[]){if(!N||typeof N!="object")continue;let H=N;if(H.type==="content"&&H.content&&typeof H.content=="object"){let te=H.content;if(te.text!==void 0){T(te.text);continue}}if(H.type==="text"&&H.text!==void 0){T(H.text);continue}H.text!==void 0&&T(H.text)}if(O.length===0)for(let N of hA(v))T(N);return O.length>0?O:null}let TS=(y,v)=>{let C=v.map(N=>"text"in N?N.text:"").join(`
|
|
299
|
-
`);if(C.length===0)return;let{text:O,truncated:T}=k0(C);y.resultText=O,y.resultTruncated=T},Hf=new Set,J$=(y,v)=>{!v.some(O=>"hash"in O)||Hf.has(y)||(Hf.add(y),(async()=>{let O=await Promise.all(v.map(async N=>"text"in N?N:{text:await jg(N.hash)??""}));Hf.delete(y);let T=Gt.get(y);if(!T)for(let N of ze.values()){let H=N.states.get(y);if(H){T=H;break}}if(T){TS(T,O),Gt.has(y)&&sr();for(let[N,H]of ze)H.states.has(y)&&Bf(N);R.repaintNow()}})().catch(()=>{Hf.delete(y)}))},Wg=(y,v)=>{let C=v??Gt.get(y);if(C===void 0)return;let O=r$(C,Yr.get(y)??C.editDiff,tt);if(O===null){ee.delete(y);return}ee.set(y,O)},ES=(y,v,C,O,T,N,H,te,le,ie,ln,xt,qe=!1)=>{let ht=!Gt.has(y),Jt=Gt.get(y),Fe=Jt??{initialTitle:v??"tool",latestTitle:v??"tool",status:C??"pending",startedAt:xt??Date.now()};if(!Jt&&le!==void 0&&(Fe.workerTaskId=le),ln!==void 0&&Fe.rawKind===void 0&&(Fe.rawKind=ln),Jt&&v!==void 0&&(Fe.latestTitle=v),N!==void 0&&Fe.detail===void 0&&(Fe.detail=N),H!==void 0&&Fe.detailFull===void 0&&(Fe.detailFull=H),te!==void 0&&te.length>0&&(Fe.locations=te),Jt&&C!==void 0&&(Fe.status=C),Jt||(Fe.status=C??"pending"),Fe.endedAt===void 0&&ek(Fe.status)&&(Fe.endedAt=xt??Date.now(),Fe.startedAt!==void 0&&Fe.endedAt<Fe.startedAt&&(Fe.endedAt=Fe.startedAt),Xg()),O!==void 0&&(Fe.errorText=O),T!==void 0&&(Fe.editDiff=T),ie!==void 0){let Ko=Cb(ie);Ko!==void 0&&(Fe.resultSummary=Ko)}if(ie!==void 0){let Ko=G$(ie);Ko!==null&&(TS(Fe,Ko),Ko.some(Gf=>"hash"in Gf)&&J$(y,Ko))}Gt.set(y,Fe),Wg(y,Fe);let un=i$(ie);un!==null&&(fe=un,Xg(),un.length>0&&qo({kind:"plan",entries:un})),ht&&(B_({blockOpen:Te!==null,isStart:qe})&&(Q+=1,Se=`tools:${Q}`,Te=Date.now(),X=null,$e=null),Te!==null&&L.push(y),R.isSidebarVisible()&&Sl())},jg=async y=>{try{let v=await b.request("hydra-acp/session/tool_content",{sessionId:me,hash:y});return typeof v?.content=="string"?v.content:null}catch{return null}},Uf=new Set,V$=(y,v)=>{Uf.has(y)||v.oldRef===void 0&&v.newRef===void 0||(Uf.add(y),(async()=>{let[C,O]=await Promise.all([v.oldRef?jg(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?jg(v.newRef.hash):Promise.resolve(v.newText)]);if(v.oldRef!==void 0&&C===null||v.newRef!==void 0&&O===null){Uf.delete(y);let ie=MS(y,v,Qb(v,"diff",{deferredStatus:"error"}));ie.length>0&&(R.upsertLines(`editdiff:${y}`,ie),R.repaintNow());return}let N={...v.path!==void 0?{path:v.path}:{},oldText:C??"",newText:O??""};Yr.set(y,N);let H=Gt.get(y);H?.editDiff&&(H.editDiff=N),Wg(y),Uf.delete(y);let te=wr.get(y),le=te===void 0?o.showFileUpdates:te?"diff":"edit";le!=="none"&&(Wf(y,N,le==="diff"?"diff":"edit"),R.repaintNow())})())},PS=new Map,MS=(y,v,C)=>{let O=PS.get(y);return O===void 0&&(O=Gt.get(y)?.locations?.[0]?.line??aO(v),PS.set(y,O)),O===null?C:C.map(T=>T.links===void 0?T:{...T,links:T.links.map(N=>({...N,url:`${N.url}#L${O}`}))})},Wf=(y,v,C)=>{let O=`editdiff:${y}`,T=MS(y,v,Qb(v,C));if(T.length===0){R.removeKey(O);return}R.upsertLines(O,T),C==="diff"&&(v.oldRef!==void 0||v.newRef!==void 0)&&R.notifyWhenVisible(O)},Y$=y=>{if(!y.startsWith("editdiff:"))return;let v=y.slice(9),C=Yr.get(v);C&&(C.oldRef!==void 0||C.newRef!==void 0)&&V$(v,C)},_S=y=>{let v=`editdiff:${y}`,C=o.showFileUpdates,O=Gt.get(y),T;if(C==="none"||!O?.editDiff||O.status!=="completed")T=null;else{let H=wr.get(y);T=H!==void 0?H?"diff":"edit":C==="diff"?"diff":"edit"}if(T===null){R.removeKey(v);return}let N=O.editDiff;Yr.set(y,N),Wg(y),Wf(y,N,T)},qg=()=>{let y=o.showFileUpdates;for(let[v,C]of Yr){let O=`editdiff:${v}`,T=wr.get(v),N=T===void 0?y:T?"diff":"edit";if(N==="none"){R.removeKey(O);continue}Wf(v,C,N==="diff"?"diff":"edit")}},$S=()=>{let y=R.width(),v=y>0?{maxWidth:y}:void 0;for(let[O,T]of lt){let N=Ao(T,v);N.length>0&&R.upsertLines(O,N)}let C=new Set;for(let O of We.values())for(let T of O)C.add(T);for(let O of ae.keys()){if(C.has(O))continue;let T=IS(O);T.length>0&&R.upsertLines(O,T)}},OS=()=>{R.isSidebarOverlay()||(Hg(),qg(),Oe(),$S())},zg=!1,jf=null,FS=y=>{p$("git",["status","--porcelain=v2","--branch"],{cwd:y,timeout:3e3,maxBuffer:4*1024*1024},(v,C)=>{zg=!1,R.setSidebarSnapshot({git:v?null:t$(C,jf)})})},kl=()=>{if(zg||tt===null)return;if(jn){R.setSidebarSnapshot({git:null});return}let y=tt;if(zg=!0,jf!==null){FS(y);return}p$("git",["rev-parse","--show-toplevel"],{cwd:y,timeout:3e3},(v,C)=>{v||(jf=C.trim()||null),FS(y)})},Kg=!1,Gg=()=>{Kg||(Kg=!0,(async()=>{try{let y=await
|
|
296
|
+
`),y.sessionId!=="__new__"&&(r.pickerSelect=y.sessionId),delete r.initialPrompt,delete r.initialAttachments}let d=await y$(n,e,t,r,i,o);if(!d)return n.grabInput(!1),ge({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=d.resolved?.status==="warm"&&t.isLocal,l=d.sessionId==="__new__"?"Starting new session\u2026":d.isFreshFork?"Forking session\u2026":d.resolved?.status==="warm"?"Attaching to session\u2026":"Resuming session\u2026",u=r.installStatus;r.installStatus&&delete r.installStatus;let f=d.installStatus??u??bg(c?"":l,k_(n));c||f.write(l);let p=t.isLocal?async()=>(await rn(await He())).wsUrl:t.wsUrl,m=t.isLocal?async()=>["acp.v1",`hydra-acp-token.${(await rn(await He())).token}`]:["acp.v1",`hydra-acp-token.${t.token}`],h=null,g=null,w=new Gc({url:p,subprotocols:m,onConnect:async y=>{y||h&&await h()},onDisconnect:y=>{g&&g(y)},log:y=>ge({src:"resilient-ws",line:y})}),b=new pn(w);await w.start(),b.onNotification(bp,y=>{let v=JI.safeParse(y);v.success&&f.applyProgress(v.data)});let k=[],S=null,I=!1,x=!1,A=(y,v,C)=>{y&&(S?S(y,v,C):k.push({event:y,rawUpdate:v,recordedAt:C}))},_,P=y=>{y!==_&&(_=y,y!==void 0&&R.appendLines([{prefix:" ",body:`\u2500\u2500 T${y} \u2500\u2500`,bodyStyle:"muted"}]))},$=null,F=null,J=!1,Y=0,W=0,Z=!1,ne=!1,ve,Ne=null,Re=null,Ge=!1,Ae=!1,de=null,De=!1,it=null,Rt=null,Me=null,Kt=null,Ve=null,ys=null,Ti=!1,mr=()=>setInterval(()=>{if(xe===null)return;if(Ne===null){it!==null&&xe.setBanner({});return}let y=ys===null?0:Date.now()-ys;y<m$&&(Ti=!1);let C=it===null&&!Xa()&&y>=m$;xe.setBanner({elapsedMs:Date.now()-Ne,stalled:C}),C&&!Ti&&(Ti=!0,xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`no output for ${Math.round(y/6e4)}m and nothing running. ^C to cancel`,bodyStyle:"tool-status-fail"}])),sr()},1e3),ce=!1,Je=(y,v,C)=>{let O=W;W=Math.max(0,W+y),ge({src:"pending-turns",delta:y,before:O,after:W,origin:v??null,label:C??null}),y>0&&xM({origin:v??null,label:C});let T=typeof xe<"u"&&xe!==null;O===0&&W>0?(ne=!1,Ne=Date.now(),ys=Date.now(),xe?.setSidebarSnapshot({busySince:Ne}),an?.setTurnRunning(!0),T&&xe.setBanner({status:"busy",elapsedMs:0,stalled:!1}),de===null&&T&&(de=mr())):O>0&&W===0?(ne=!1,er!==null&&(clearTimeout(er),er=null),at=!1,Ne=null,Ge?Re=Date.now():Ae=!0,xe?.setSidebarSnapshot({busySince:null,lastTurnEndedAt:Re}),ys=null,an?.setTurnRunning(!1),de!==null&&it===null&&(clearInterval(de),de=null),T&&xe.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):W>0&&ne&&(ne=!1,T&&xe.setBanner({status:"busy",stalled:!1}))},xe=null,an=null,Xa=()=>!1,Lr,Nr,Oo=null,Mg=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction","_hydra_workspace","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),sl=y=>{let{update:v}=y??{},C=HI(y),O=js(v,{cwd:tt});U4(v,O),ys=Date.now();let T=v?.sessionUpdate;if(typeof T=="string"&&!Mg.has(T)){let N=v??{};typeof N.messageId=="string"&&(Lr=N.messageId);let H=yp(y);H!==void 0&&(Nr=H)}if(T==="prompt_received"){let N=F_(v?.sentBy);Je(1,N.origin,N.label)}else O?.kind==="turn-complete"&&(Je(-1),J=!0);if(T==="permission_resolved"){kf(v);return}if(T==="_hydra_compaction"){ro(v);return}if(T==="_hydra_workspace"){Ei(v);return}if(T==="clarifier_question_asked"){let N=v,H=typeof N.question?.question=="string"?N.question.question:"",te=H.length>50?H.slice(0,49)+"\u2026":H;R.notify(te?`new question: ${te} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}T==="clarifier_question_answered"||T==="clarifier_question_dismissed"||(A(O,v,C),Pi(v))};b.onNotification("session/update",y=>{if(!I){if(Oo!==null){Oo.push(y);return}sl(y)}}),b.onNotification("hydra-acp/session/closed",()=>{if(I)return;W>0&&Je(-W),typeof xe<"u"&&xe!==null&&xe.setBanner({status:"cold",elapsedMs:void 0}),$n()});let ws=new Map,Fo=200,Ut=0,at=!1,Za=4e3,er=null;b.onNotification("hydra-acp/prompt_queue/added",y=>{if(I)return;let v=y??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let O=v.messageId,T=v.prompt,N=setTimeout(()=>{I||(ws.delete(O),Ln.set(O,Cd(O,T)),xe&&an&&mo())},Fo);ws.set(O,N)}else Ln.set(v.messageId,Cd(v.messageId,v.prompt)),xe&&an&&mo();if(Br!==void 0&&v.originator?.clientId===Br){let O=Jn.shift();O&&(O.messageId=v.messageId,Is.set(v.messageId,O))}});let Wn=(y,v)=>{let C=Ln.get(y);C!==void 0&&(v?C.held=!0:delete C.held,xe&&an&&mo())},gn=(y,v)=>{v!==void 0&&xe?.setSidebarSnapshot({armedTasks:v}),it!==y&&(it=y,xe?.setBanner({armedSince:y??void 0}),xe?.setSidebarSnapshot({armedSince:y}),y!==null&&de===null&&xe!==null&&(de=mr()),y===null&&Ne===null&&de!==null&&(clearInterval(de),de=null))};b.onNotification("hydra-acp/session/armed_tasks_updated",y=>{if(I)return;let v=y??{},C=typeof v.count=="number"?v.count:0;gn(C>0&&typeof v.since=="number"?v.since:null,Array.isArray(v.tasks)?pS(v.tasks):void 0)}),b.onNotification("hydra-acp/prompt_queue/held",y=>{if(I)return;let v=y??{};typeof v.messageId=="string"&&Wn(v.messageId,!0)}),b.onNotification("hydra-acp/prompt_queue/released",y=>{if(I)return;let v=y??{};typeof v.messageId=="string"&&Wn(v.messageId,!1)}),b.onNotification("hydra-acp/prompt_queue/updated",y=>{if(I)return;let v=y??{};if(typeof v.messageId!="string")return;let C=Ln.get(v.messageId);if(C===void 0)return;let O=Cd(v.messageId,v.prompt);C.held&&(O.held=!0),Ln.set(v.messageId,O);let T=Is.get(v.messageId);if(T){let N=Array.isArray(v.prompt)?v.prompt:[],H="",te=[];for(let le of N){if(!le||typeof le!="object")continue;let ie=le;ie.type==="text"&&typeof ie.text=="string"?H+=ie.text:ie.type==="image"&&typeof ie.data=="string"&&typeof ie.mimeType=="string"&&te.push({data:ie.data,mimeType:ie.mimeType,sizeBytes:Math.floor(ie.data.length*3/4)})}T.text=H,T.attachments=te}xe&&an&&mo()}),b.onNotification("hydra-acp/prompt_queue/removed",y=>{if(I)return;let v=y??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(ve=v.messageId);let C=ws.get(v.messageId);C!==void 0&&(clearTimeout(C),ws.delete(v.messageId)),Ln.delete(v.messageId)&&xe&&an&&mo();let T=Is.get(v.messageId);T&&(Is.delete(v.messageId),v.reason==="started"&&(T.flushed=!0,A({kind:"user-text",text:T.displayText,attachments:T.attachments}),Vr=T))}),b.onNotification("hydra-acp/cancel_failed",y=>{if(I)return;let v=y??{};if(!(typeof xe<"u"&&xe!==null))return;Ut=Date.now();let O=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";if(v.reason==="unresponsive"){xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`agent kept resuming after repeated cancels${O} \u2014 hydra restarted it automatically.`,bodyStyle:"tool-status-fail"}]);return}at=!0;let T=typeof v.code=="number"?` (${v.code})`:"";xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${T}${O} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),b.onNotification("hydra-acp/prompt/amended",y=>{if(I)return;let v=y??{};if(typeof v.cancelledMessageId!="string")return;let C=v.cancelledMessageId;Jr.add(C),Vr!==null&&Vr.messageId!==void 0&&Vr.messageId===C&&(A({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Vr=null,Jr.delete(C))}),b.onNotification("hydra-acp/context_self_compacted",()=>{I||R.notify("agent compacted its own context \u2014 recall armed",4e3)});let ro=y=>{let v=y??{},C=typeof v.phase=="string"?v.phase:void 0;if(C==="started")R.setCompactionIndicator("compacting...");else if(C==="iteration")R.setCompactionIndicator("compacting...");else if(C==="deferred")R.setCompactionIndicator("compaction queued (waiting for idle)");else if(C==="swapped")R.setCompactionIndicator(null),R.notify("compacted",2e3);else if(C==="rolled_back")R.setCompactionIndicator(null),R.notify("rolled back",2e3);else if(C==="failed"){R.setCompactionIndicator(null);let O=typeof v.error=="string"?v.error:"unknown error",T=O.length>40?O.slice(0,40)+"...":O;R.notify(`compaction failed: ${T}`,5e3)}},Ei=y=>{let v=y??{},C=typeof v.phase=="string"?v.phase:void 0;if(C==="drift"){let N=typeof v.behind=="number"?v.behind:0;R.notify(N>0?`source moved on, ${N} commit(s) ahead \u2014 /hydra workspace sync`:"source moved on \u2014 /hydra workspace sync",6e3);return}if(C==="provisioning"){R.setWorkspaceIndicator("creating workspace...");return}if(C==="setup"){R.setWorkspaceIndicator("running workspace setup...");return}if(C==="swapping"){R.setWorkspaceIndicator("moving session into workspace...");return}if(C==="landing"){R.setWorkspaceIndicator("merging workspace back...");return}if(C==="applying"){R.setWorkspaceIndicator("staging workspace changes...");return}if(C==="returning"){R.setWorkspaceIndicator("returning to source tree...");return}if(C==="failed"){R.setWorkspaceIndicator(null);let N=typeof v.error=="string"?v.error:"unknown error";R.notify(`workspace failed: ${N.length>40?N.slice(0,40)+"...":N}`,5e3);return}if(C!=="entered"&&C!=="left"||(R.setWorkspaceIndicator(null),typeof v.cwd!="string"||v.cwd.length===0))return;tt=v.cwd,jf=null;let O=typeof v.sourceCwd=="string"?v.sourceCwd:v.cwd,T=typeof v.label=="string"?v.label:void 0;R.setSessionbar({cwd:v.cwd,...C==="entered"&&T!==void 0?{workspace:{label:T,path:v.cwd,sourceCwd:O}}:{workspace:void 0}}),kl(),R.setSidebarSnapshot({workspace:C==="entered"&&T!==void 0?{label:T,path:v.cwd}:null}),R.notify(C==="entered"?`isolated in ${T??"a workspace"}`:"returned to source tree",2e3)},ol=()=>{Rt===null&&(Rt=setInterval(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!y.ok)return;let v=await y.json();v.forkSynthesisState===void 0?(R.setSynthesisIndicator(null),R.notify("synthesis complete",2e3),Rt!==null&&(clearInterval(Rt),Rt=null)):v.forkSynthesisState==="failed"&&(R.setSynthesisIndicator("\u26A0 synthesis failed"),R.notify("synthesis failed \u2014 fork still usable via recall",8e3),Rt!==null&&(clearInterval(Rt),Rt=null))}catch{}},5e3))},ed=()=>{Rt!==null&&(clearInterval(Rt),Rt=null)},so=()=>{Me!==null&&(clearInterval(Me),Me=null)},$n=()=>{if(Me!==null)return;let y=!1;Me=setInterval(async()=>{if(!(y||I)){y=!0;try{let v=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!v.ok){v.status===404&&so();return}if((await v.json()).status!=="warm")return;so(),ge({src:"cold-watch",step:"warm-detected",sessionId:me}),h&&await h({skipInitialize:!0,beforeReplay:()=>{xe?.appendLines([{prefix:" ",body:"-- session resumed by another client, catching up --",bodyStyle:"muted"}])}})}catch{}finally{y=!1}}},M4)},kf=y=>{let v=y??{},C=typeof v.toolCallId=="string"?v.toolCallId:void 0,O;v.outcome&&typeof v.outcome=="object"?O=v.outcome:typeof v.chosenOptionId=="string"&&(O={kind:"selected",optionId:v.chosenOptionId}),yn(C,O?{outcome:O}:void 0)},Ye=null,yn=(y,v)=>{if(!Ye||Ye.toolCallId&&y&&Ye.toolCallId!==y)return;let C=Ye.resolve;Ye=null,R.setPermissionPrompt(null),C(v??{outcome:{outcome:"cancelled"}})},Pi=y=>{if(!Ye?.toolCallId)return;let v=y??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===Ye.toolCallId&&(!v.status||v.status==="pending"||yn(v.toolCallId,void 0))},Mi=()=>{if(!Ye){R.setPermissionPrompt(null);return}R.setPermissionPrompt({title:Ye.title,detail:Ye.detail,options:Ye.options.map(y=>({label:y.name})),selectedIndex:Ye.selectedIndex})},oo=y=>{if(!Ye)return;let{options:v,resolve:C}=Ye;if(Ye=null,R.setPermissionPrompt(null),y===null){C({outcome:{outcome:"cancelled"}});return}C({outcome:{outcome:"selected",optionId:y}})};b.onRequest("session/request_permission",async y=>{if(I)return{outcome:{outcome:"cancelled"}};if(r.dangerouslySkipPermissions)return Da(y);let v=y??{},O=(Array.isArray(v.options)?v.options:[]).map(le=>({optionId:le.optionId,name:ot(le.name??""),...le.kind!==void 0?{kind:le.kind}:{}})),T=v.toolCall?.title??v.toolCall?.name??"tool",N=ot(T),H=ot(EE(TE(y))),te=v.toolCall?.toolCallId;return O.length===0?(R.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${N} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(le=>{Ye={title:N,detail:H,options:O,selectedIndex:0,resolve:le,toolCallId:te},Mi()})}),b.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let _i,td,In=!0,bs=!1,Dr=!1;try{let y=await b.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Ue}});td=y?.agentInfo?.name,y?.agentCapabilities?.promptCapabilities?.image===!1&&(In=!1),bs=Pn(y?._meta??void 0).prompt?.amending===!0,Dr=y?._meta?.steering?.supported===!0}catch{}let me=d.sessionId,It=d.agentId,tt=d.cwd,Qt;t.isLocal||(d.remote=t.display);let vf=d.remote,jn=Qc(d),qn=null,il=()=>(qn===null&&(qn=w4(Ri.join(v4(),"hydra-remote-exec-"))),qn),$i=()=>jn?il():tt,Oi=d.jumpToRecordedAt,Br,Xt,Fi,Lo,nd,rd,sd,io,No,Hr,od,ao,Sf=!1;if(d.sessionId==="__new__"){let y={};r.agentId&&(y.agentId=r.agentId),r.name&&(y.title=r.name),r.model&&(y.model=r.model),r.workspace===!0&&(y.workspace={});let v={cwd:d.cwd,...Object.keys(y).length>0?{_meta:{[ut]:y}}:{}},C;try{C=await gE({request:()=>b.request("session/new",v),showBanner:(N,H,te)=>yE(n,N,H,te,{authenticate:le=>b.request("authenticate",{methodId:le,_meta:{[ut]:{agentId:N}}})}),resolveOnboarding:async N=>{if(N)try{return(await Aa(t)).find(le=>le.id===N)?.onboarding}catch{return}},fallbackAgentId:r.agentId})}catch(N){n.grabInput(!1),ge({src:"grab",site:"runSession.session-new-failed",on:!1}),w.close().catch(()=>{});let H=N instanceof Error?N.message:String(N);ge({src:"session-new-failed",agentId:r.agentId??null,message:H});let te=await T_(n,r.agentId,H,{canGoBack:!r.forceNew});if(te==="cancel")return null;let le={...r};return delete le.sessionId,delete le.resume,te==="retry"?le.forceNew=!0:(delete le.forceNew,delete le.agentId),le}if(C.kind==="cancel")return n.grabInput(!1),ge({src:"grab",site:"runSession.auth-cancel",on:!1}),w.close().catch(()=>{}),null;if(C.kind==="back"){n.grabInput(!1),ge({src:"grab",site:"runSession.auth-back",on:!1}),w.close().catch(()=>{});let N={...r};return delete N.sessionId,delete N.forceNew,delete N.resume,delete N.agentId,N}let O=C.result;f.write(l),me=O.sessionId,Rv(me),s.sessionId=me,s.readonly=!1;let T=Pn(O._meta??void 0);T.clientId&&(Br=T.clientId),_i=T.upstreamSessionId,T.agentId&&(It=T.agentId),T.cwd&&(tt=T.cwd),Xt=T.workspaceInfo,T.title&&(Qt=T.title),Fi=T.currentModel,Lo=T.currentMode,No=T.currentUsage,Hr=T.turnStartedAt,od=T.armedSince,ao=T.armedTaskList,T.availableCommands&&(nd=xh(T.availableCommands)),T.availableModes&&(rd=T.availableModes),sd=h$(O.configOptions),io=T.queue}else{let y={};r.readonly===!0&&(y.readonly=!0),e.tui.toolContent==="references"&&(y.toolContent="references"),r.drip===!0&&(y.replayMode="drip",r.dripSpeed!==void 0&&(y.dripSpeed=r.dripSpeed)),d.resumeHint!==void 0&&(y.resume={upstreamSessionId:d.resumeHint.upstreamSessionId,agentId:d.resumeHint.agentId,cwd:d.resumeHint.cwd});let v=await b.request("session/attach",{sessionId:d.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:Ue},...Object.keys(y).length>0?{_meta:{[ut]:y}}:{}});me=v.sessionId,Rv(me),v.clientId&&(Br=v.clientId),s.sessionId=me,s.readonly=r.readonly===!0;let C=Pn(v._meta??void 0);Sf=C.resurrected===!0,_i=C.upstreamSessionId,C.agentId&&(It=C.agentId),C.cwd&&(tt=C.cwd),Xt=C.workspaceInfo,C.title&&(Qt=C.title),Fi=C.currentModel,Lo=C.currentMode,No=C.currentUsage,Hr=C.turnStartedAt,od=C.armedSince,ao=C.armedTaskList,C.availableCommands&&(nd=xh(C.availableCommands)),C.availableModes&&(rd=C.availableModes),sd=h$(v.configOptions),io=C.queue}let Qe=D.tuiHistoryFile(me),Li=D.globalTuiHistoryFile(),Zt=await du(Qe).catch(()=>[]),en=await du(Li).catch(()=>[]);en.length>e.tui.promptHistoryMaxEntries&&(en=en.slice(en.length-e.tui.promptHistoryMaxEntries));let co=[...Zt],Be=new Mo({history:nh(en,co)});an=Be;let zn=!1,Ni=()=>{xe?.setBanner({hintsExhausted:ER(Zt.length,e.tui.composer.hintTurns)})},Ur=(y,v)=>{let C=y.replace(/\n+$/,"");if(C.length===0)return;let O=(v??y).replace(/\n+$/,""),T=cu(Zt,C),N=T!==Zt;Zt=T,co=cu(co,O);let H=cu(en,C,e.tui.promptHistoryMaxEntries),te=H!==en;en=H,Be.setHistory(nh(en,co)),N&&ha(Qe,Zt).catch(()=>{}),te&&PR(Li,C).catch(()=>{}),Ni(),xe?.clearHintReveal()};W>0&&Be.setTurnRunning(!0);let tr=[],id=null;a_(d_(e.tui.ambiguousWidth,process.env,k$)),x0(e.tui.diffContextLines);let ad=!1,R,xf=()=>{ad&&(ad=!1,R.start())},_g=()=>{ad||(ad=!0,R.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",xf);let If=_4(e.tui.openFileCommand);R=new fg({term:n,dispatcher:Be,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:o.mouseEnabled,inAppSelection:o.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:If?.argv,openFileSource:If?.source,openFileInTerminal:e.tui.openFileInTerminal,progressIndicator:e.tui.progressIndicator,readonly:r.readonly===!0,onSidebarCollapseChange:(y,v)=>{o.sidebarCollapsed=xe?.sidebarCollapsedIds()??[],!v&&(y==="git"?kl():y==="sessions"?Gg():y==="resources"&&BS(),Sl())},onSuspend:process.platform!=="win32"?_g:void 0,onLayoutChange:()=>{OS()},onBlockClick:(y,v,C)=>{dO(y,v,C)},onHydraLinkClick:y=>(Wo(y),!0),onBlockVisible:y=>{Y$(y)},onHoverRun:y=>{if(!y.startsWith("thought:"))return null;let v=We.get(y);if(v!==void 0&&v.length>0)return new Set(v);let C=R.contiguousRun(y,new Set(ae.keys()));return C.length>0?new Set(C):null},onBarAction:(y,v)=>{if(y==="toggle-mode"){Df(!0);return}if(y==="rename-session"){hl(v);return}if(y==="choose-model"){pe("model");return}if(y==="choose-agent"){pe("agent");return}if(y==="choose-mode"){pe("mode");return}let C=y==="switch-session"?{type:"switch-session"}:y==="detach"?{type:"exit"}:y==="toggle-options"?{type:"toggle-options"}:{type:"show-help"};r.readonly===!0&&hS(C)||zi(C)},onFormClick:y=>ml(y),onPermissionClick:y=>Ef(y),onCompactionClick:y=>Bi(y),onHelpClick:()=>R.setHelpPrompt(null),onMouse:y=>{if(y.kind!=="press"||y.button!=="middle")return;let v={type:"attachment-request",source:"primary"};r.readonly===!0&&hS(v)||zi(v)},onKey:y=>{for(let v of y){if(Z&&fo(v)){v.type==="key"&&ge({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(Ye&&$g(v)){v.type==="key"&&ge({src:"key-swallowed",site:"permission",name:v.name});continue}if(Hi(v)){v.type==="key"&&ge({src:"key-swallowed",site:"help",name:v.name});continue}if(qi(v)){v.type==="key"&&ge({src:"key-swallowed",site:`form:${On??"none"}`,name:v.name});continue}if(Tf(v)){v.type==="key"&&ge({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(Af(v)){v.type==="key"&&ge({src:"key-swallowed",site:"completion",name:v.name});continue}if(At(v)){v.type==="key"&&ge({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&R.isScrolledBack()){R.scrollToBottom();continue}if(v.type==="attachment-paths"){Id(v.paths);continue}if(v.type==="key"&&Kn(v.name)){ge({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let C=Be.feed(v);for(let O of C)r.readonly===!0&&hS(O)||zi(O)}cd(),R.setBannerSearchIndicator(Be.state().historySearchQuery),R.setAttachments(Be.state().attachments),R.refreshPrompt()}}),xe=R,R.setStickyBottomKey("plan");let Cf=[{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:"/title",description:"Rename this session: /title [title] (no arg opens the field)"},{name:"/model",description:"Switch model: /model [model-id] (no arg opens the picker)"},{name:"/mode",description:"Switch mode: /mode [mode-id] (no arg opens the picker)"},{name:"/agent",description:"Switch agent: /agent [agent-id] (no arg opens the picker)"},{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]"}],dd=nd??[],Do=rd??[],gr=sd??[],Rf=()=>{let y=new Set,v=[];for(let C of[...Cf,...dd])y.has(C.name)||(y.add(C.name),v.push(C));return v},al=()=>{let y=Be.state().buffer,v=y[0]??"";if(!v.startsWith("/"))return[];if(y.length>1)return[];let C=v.indexOf(" "),O=C===-1?v:v.slice(0,C);if(O.lastIndexOf("/")>0)return[];let T=Rf().filter(N=>N.name.startsWith(O));return T.length===1&&T[0]?.name===O?[]:T},lo=[],cd=()=>{let y=al();if(y.length>0){lo=[],R.setCompletions(y);return}R.setCompletions(lo)},Af=y=>{if(y.type!=="key"||y.name!=="tab")return lo.length>0&&(lo=[]),!1;let v=al();if(R.isOverlayOpen()&&v.length===0)return R.toggleFocusedPane(),!0;if(v.length>0){lo=[];let C=Be.state().buffer[0]??"",O=m_({matches:v.map(T=>T.name),firstLine:C});return O===null||Be.replaceFirstLine(O),!0}return ld()},ld=()=>{if(jn)return!1;let y=Be.state(),v=y.buffer[y.row]??"",C=gg(v,y.col);if(C===null)return!1;let O=yg(C.token,tt);return O===null?!1:(O.replacement!==C.token&&Be.replaceRangeOnCurrentLine(C.start,y.col,O.replacement),lo=O.candidates.length>1?O.candidates.map(T=>({name:T})):[],!0)},At=y=>!R.isOverlayOpen()||y.type!=="key"||y.name!=="escape"&&y.name!=="ctrl-c"?!1:($&&($.cancel(),$=null,F=null),R.closeBtwOverlay(),!0),Tf=y=>{if(!R.isScrollbackSearchActive())return y.type==="key"&&y.name==="ctrl-r"&&R.isScrolledBack()?(R.enterScrollbackSearch(),R.updateScrollbackSearchTerm(""),!0):!1;if(y.type==="char"){let v=R.scrollbackSearchTerm()+y.ch;return R.updateScrollbackSearchTerm(v),!0}if(y.type==="paste"){let v=R.scrollbackSearchTerm()+y.text.replace(/\n/g," ");return R.updateScrollbackSearchTerm(v),!0}if(y.type==="key")switch(y.name){case"ctrl-r":return R.advanceScrollbackSearch(),!0;case"ctrl-s":return R.retreatScrollbackSearch(),!0;case"backspace":{let v=R.scrollbackSearchTerm();return v.length===0?R.cancelScrollbackSearch():R.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return R.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return R.cancelScrollbackSearch(),!0;default:return!0}return!0},Ef=y=>{if(!Ye)return;let v=Ye.options;if(y.kind==="hint"){if(y.action==="cancel"){oo(null);return}oo(v[Ye.selectedIndex]?.optionId??null);return}let C=v[y.index];if(C){if(y.select===!0){Ye.selectedIndex=y.index,Mi();return}oo(C.optionId)}},$g=y=>{if(!Ye)return!1;let v=Ye.options;if(y.type==="key")switch(y.name){case"up":return Ye.selectedIndex=Math.max(0,Ye.selectedIndex-1),Mi(),!0;case"down":return Ye.selectedIndex=Math.min(v.length-1,Ye.selectedIndex+1),Mi(),!0;case"enter":{let C=v[Ye.selectedIndex];return C&&oo(C.optionId),!0}case"escape":case"ctrl-c":return oo(null),!0;default:return!0}if(y.type==="char"&&/^[1-9]$/.test(y.ch)){let C=parseInt(y.ch,10)-1,O=v[C];return O&&oo(O.optionId),!0}return!0},Kn=y=>{let v=e.tui.hotkeys[y];return v?(wg(v,{sessionId:me,cwd:$i(),agentId:It||td||"",baseUrl:t.baseUrl,tokenFile:D.authToken()},{notify:C=>R.notify(C),cwd:$i(),emitLines:C=>{R.appendLines(C.map(O=>{let T;switch(O.style){case"meta":T="muted";break;case"stderr":case"error":T="tool-status-fail";break;default:T="notice"}return{prefix:" ",body:O.text,bodyStyle:T}}))}}),!0):!1},ud=()=>It||td||"?",Ct=ud(),Ot={...No??{}};f.finalize(),R.start({skipFullscreen:!0}),R.setHideThoughts(!o.showThoughts),R.setBarConfig({composer:e.tui.composer,sessionbar:e.tui.sessionbar});let Bo=sS(tf({composer:e.tui.composer,sessionbar:e.tui.sessionbar}),e.tui.scriptRefreshMs),dl=y=>{let v=a.get(y);if(v===void 0)return;let C={HYDRA_ACP_TOKEN:v,HYDRA_ACP_DAEMON_URL:t.baseUrl};return me!==null&&(C.HYDRA_ACP_SESSION_ID=me),C};if(Bo.size>0){let y=P_({cwd:$i,envFor:dl,onOutput:(v,C)=>R.setScriptOutput(v,C)});Kt=setInterval(()=>{y.poll(Bo,Date.now())},1e3),Kt.unref?.(),y.poll(Bo,Date.now())}let ks=kv(e.tui.sidebar.gadgets);R.setSidebarProcessGadgets(tg(ks)),R.setSidebarGadgets(ks.map(eg));let fd=hv(ks,e.tui.scriptRefreshMs),pd=new Map;for(let y of tg(ks)){let v=pd.get(y.script)??[];v.push(y.id),pd.set(y.script,v)}let uo=()=>{let y=new Map;for(let[v,C]of fd)(pd.get(v)??[]).some(T=>R.isSidebarGadgetActive(T))&&y.set(v,C);return y};if(fd.size>0){let y=Sg({cwd:$i,envFor:dl,sanitize:uM,onOutput:(v,C)=>R.setProcessOutput(v,C)});Ve=setInterval(()=>{y.poll(uo(),Date.now())},1e3),Ve.unref?.(),y.poll(uo(),Date.now())}Ni(),R.setSidebarWidth(e.tui.sidebar.width??null),R.setSidebarBorder(e.tui.sidebar.border),R.setSidebarSnapshot({usage:{...Ot},model:Fi??null,mode:Lo??null,sessionId:me===null?null:st(me),host:me===null?null:Bs(me)?.name??null,agent:Ct,workspace:Xt===void 0?null:{label:Xt.label,path:Xt.path}}),R.setSessionbar({agent:Ct,cwd:tt,remote:vf,...Xt===void 0?{}:{workspace:{label:Xt.label,path:Xt.path,sourceCwd:Xt.sourceCwd}},sessionId:me,title:Qt,model:Fi,usage:{...Ot}}),Lo&&R.setBanner({currentMode:Lo}),Uu().then(y=>{y&&R.notify(`\u2728 ${Wu(y)}`,3e4)}).catch(()=>{});let Wt=null,Di=new Promise(y=>{Wt=y}),cl=()=>{if(b.notify("session/cancel",{sessionId:me}).catch(()=>{}),er===null){let y=Date.now();er=setTimeout(()=>{er=null,W!==0&&(Ut>=y||at||(at=!0,xe?.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"cancel not acknowledged by agent; the turn is still running. Cancel again to force-stop (restarts the agent).",bodyStyle:"tool-status-fail"}])))},Za)}},Pf=()=>{at=!1,xe!==null&&xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"force-stopping agent \u2014 turn aborted; resumes on your next message\u2026",bodyStyle:"tool-status-fail"}]),b.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(()=>{})},ll=()=>{xe!==null&&W===1&&(ne=!0,xe.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Mf=()=>{let y=tr[0];if(y){y.cancel(),ll();return}if(W>0){at?Pf():cl(),ll();return}hd()},hd=()=>{xd(0)},Og=()=>{let y="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...o.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",y]]:[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",v]],...$4]},ul=()=>{if(R.isHelpPromptActive()){R.setHelpPrompt(null);return}R.setHelpPrompt({title:`Hotkeys \xB7 hydra-acp v${Ue}`,entries:Og(),hint:"any key dismisses \xB7 /help lists commands"})},Ho=()=>{Z=!1,R.setCompactionPrompt(null),R.setCompactionIndicator("compaction queued...");let y=me;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(y)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Wr=()=>{Z=!1,R.setCompactionPrompt(null)},vs=y=>{let v=R.compactionPromptSpec();if(!v)return;let C=v.options.length;if(C===0)return;let O=((v.selectedIndex+y)%C+C)%C;O!==v.selectedIndex&&R.setCompactionPrompt({...v,selectedIndex:O})},Bi=y=>{if(!Z)return;let v=R.compactionPromptSpec();if(!v)return;if(y.kind==="hint"){if(y.action==="cancel"){Wr();return}v.options[v.selectedIndex]?.key==="y"?Ho():Wr();return}let C=v.options[y.index];if(C){if(y.select===!0){y.index!==v.selectedIndex&&R.setCompactionPrompt({...v,selectedIndex:y.index});return}C.key==="y"?Ho():Wr()}},fo=y=>{if(!Z)return!1;if(y.type==="key"){if(y.name==="escape")return Wr(),!0;if(y.name==="up")return vs(-1),!0;if(y.name==="down")return vs(1),!0;if(y.name==="enter"){let v=R.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Ho():Wr(),!0}}if(y.type==="char"){let v=y.ch.toLowerCase();if(v==="y"||v==="1")return Ho(),!0;if(v==="n"||v==="2")return Wr(),!0}return!0},Hi=y=>R.isHelpPromptActive()?(y.type==="key"&&y.name==="ctrl-g",R.setHelpPrompt(null),!0):!1,md=["tools","plan","thoughts","diffs","mouse","enter","sidebar","theme"],gd=0,jr=null,qr=[],zr=[],wn=[],Gn=0,On=null,yd=null,Cn=(y,v)=>{y!=="chooser"&&(U=null),On=y,yd=v,R.setFormPrompt(AP(v))},Fn=y=>{On===y&&(On=null,yd=null,U=null,K=new Map,R.setFormPrompt(null))},_f=y=>{switch(y){case"tools":return o.toolsExpanded?"expanded":"collapsed";case"plan":return o.planExpanded?"expanded":"collapsed";case"thoughts":return o.showThoughts?"shown":"hidden";case"diffs":return o.showFileUpdates;case"mouse":return o.mouseEnabled?"on":"off";case"enter":return o.defaultEnterAction;case"sidebar":return R.isSidebarVisible()?"shown":"hidden";case"theme":return Qa}},$f=y=>{switch(y){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";case"theme":return"Theme"}},yr=()=>({title:"Session options",rows:md.map(y=>({id:y,kind:"select",label:$f(y),value:_f(y)})),cursor:gd,hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 cycle"},{label:"\u23CE next",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]}),Of=()=>{On==="options"&&Cn("options",yr())},po=()=>{if(On==="options"){Fn("options");return}gd=0,Cn("options",yr())},Kr=()=>{jr!==null&&Cn("questions",I$(jr,qr,wn,Gn))},wd=()=>{jr=null,qr=[],zr=[],wn=[],Gn=0,Fn("questions")},Fg=async()=>{if(jr!==null){wd();return}try{let v=await b.request(kP,{sessionId:me}),C=C4(v.questions??[]);if(C.length===0){R.notify("no open questions");return}let O=A4(C);jr=O,Gn=0,qr=O.map(T=>R4(T.representative)),zr=O.map(()=>!1),wn=O.map(()=>!1),Kr()}catch(y){R.notify("clarifier unavailable"),ge({src:"questions",step:"list_failed",error:y.message})}},ho=()=>{let y=Rg.find(C=>C.name===Qa);if(y===void 0)return;Zy(y.palette,{...y.overrides,background:Fr,foreground:S$}),$S(),Hg(),qg(),Oe(),R.fullRedraw();let v=cS(y.palette,Qa,Fr);v!==void 0&&R.notify(v)},Ui=(y=1)=>{if(Rg.length===0){R.notify("no themes available");return}let v=q_(Rg.map(C=>C.name),Qa,y);v!==void 0&&(Qa=v,ho())},bn=null,Wi=y=>{bn!==null&&(clearTimeout(bn),bn=null),e.tui.themeBackground===void 0&&(Fr!==void 0&&Fr.kind==="rgb"&&y.kind==="rgb"&&Fr.r===y.r&&Fr.g===y.g&&Fr.b===y.b||(Fr=y,ho()))};v$=y=>{e.tui.themeBackground===void 0&&(bn!==null&&clearTimeout(bn),bn=setTimeout(()=>{bn=null,Wi(zM(y))},200),bn.unref?.(),we("\x1B]11;?\x07"))},x$=Wi;let Uo=(y,v=1)=>{switch(y){case"tools":o.toolsExpanded=!o.toolsExpanded,Ft.clear(),Mt.clear(),Hg();break;case"plan":o.planExpanded=!o.planExpanded,Yn=null,Oe();break;case"thoughts":o.showThoughts=!o.showThoughts,R.setHideThoughts(!o.showThoughts);break;case"diffs":o.showFileUpdates=o.showFileUpdates==="diff"?"edit":"diff",wr.clear(),qg();break;case"mouse":{let C=!R.isMouseEnabled();R.setMouseEnabled(C),o.mouseEnabled=C;break}case"enter":o.defaultEnterAction=o.defaultEnterAction==="amend"?"enqueue":"amend";break;case"sidebar":Zg(!R.isSidebarVisible());break;case"theme":Ui(v);break}Of()},nr=y=>{(async()=>{try{switch(y){case"tools":case"plan":R.notify(`${$f(y)} is session-only \u2014 not saved`);return;case"thoughts":await Zi("showThoughts",o.showThoughts);break;case"diffs":await Zi("showFileUpdates",o.showFileUpdates);break;case"mouse":await Zi("mouse",o.mouseEnabled);break;case"enter":await Zi("defaultEnterAction",o.defaultEnterAction);break;case"sidebar":await hy(R.isSidebarVisible());break;case"theme":await Zi("theme",Qa);break}R.notify(`saved default: ${$f(y)} ${_f(y)}`)}catch(v){R.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},bd=y=>{let v=C=>md[C];switch(y.type){case"row":{gd=y.row;let C=y.viaDigit===!0?v(y.row):void 0;C?Uo(C):Of();return}case"cycle":{let C=v(y.row);C&&(gd=y.row,Uo(C,y.delta));return}case"advance":{let C=v(y.row);C&&Uo(C);return}case"save":{let C=v(y.row);C&&nr(C);return}case"close":case"cancel":Fn("options");return;default:return}},fl=(y,v)=>{if(y.type==="key"){if(y.name==="ctrl-o")return Fn("options"),!0;if(y.name==="ctrl-d")return Fn("options"),!1}return bd(Vu(v,y)),!0},kd="title",pl=(y,v)=>{let C=y.rows.find(O=>O.id===v);return C?.kind==="text"?C.editor.text:""},hl=y=>{if(On!=="title"){if(r.readonly===!0){R.notify("view-only: rename disabled");return}if(me==="__new__"){R.notify("no active session to rename");return}Cn("title",EP({title:"Rename session",id:kd,label:"title:",initial:y,hints:[{label:"\u23CE save",action:"commit"},{label:"Esc cancel",action:"close"}]}))}},vd=y=>{let v=pl(y,kd).trim(),C=me;Fn("title"),v.length!==0&&Au(t,C,v).catch(O=>{R.notify(`rename failed: ${O.message}`)})},E=(y,v)=>{switch(v.type){case"commit":vd(y);return;case"close":case"cancel":Fn("title");return;case"edited":Cn("title",y);return;default:return}},M=(y,v)=>(E(v,Vu(v,y)),!0),U=null,K=new Map,se=(y,v)=>{let C=y.options.find(N=>N.value===v);if(C)return C.value;let O=v.toLowerCase(),T=y.options.filter(N=>N.value.toLowerCase().startsWith(O));return T.length===1?T[0].value:null},oe=y=>{if(r.readonly===!0)return R.notify(`view-only: ${y} switching disabled`),null;if(me==="__new__")return R.notify("no active session yet"),null;let v=gr.find(C=>C.id===y);return!v||v.options.length===0?(R.notify(`no ${y} option advertised for this session`),null):v},pe=y=>{if(On==="chooser"&&U?.kind==="values"&&U.configId===y)return;let v=oe(y);v&&(U={kind:"values",configId:y},Cn("chooser",IP(v)))},nt=()=>{if(gr.length===0){R.notify("no config options advertised for this session");return}U={kind:"index"},K=new Map,Cn("chooser",qk(gr,K))},Dt=y=>{Cn("chooser",{...qk(gr,K),cursor:y})},tn=()=>{let y=new Map(gr.map(v=>[v.id,v.currentValue]));for(let[v,C]of K)y.get(v)!==C&&Et(v,C);K=new Map},Et=(y,v)=>{R.notify(`switching ${y} to ${v}\u2026`),b.request("session/set_config_option",{sessionId:me,configId:y,value:v}).catch(C=>{R.notify(`${y} switch failed: ${C instanceof Error?C.message:String(C)}`)})},xs=(y,v)=>{(async()=>{try{if(y==="agent")await Jo(v);else{let C=It||td||"";if(!C){R.notify(`can't save a ${y} default without an agent`);return}await Pl(C,y,v)}R.notify(`saved default: ${y} ${v}`)}catch(C){R.notify(`save failed: ${C instanceof Error?C.message:String(C)}`)}})()},Sd=(y,v)=>{let C=U;if(C===null)return;let O=H=>y.rows[H]?.id,T=H=>{let te=O(H);return te===void 0?void 0:gr.find(le=>le.id===te)},N=H=>K.get(H.id)??H.currentValue;switch(v.type){case"row":Cn("chooser",{...y,cursor:v.row});return;case"cycle":{let H=T(v.row);if(!H)return;K.set(H.id,CP(H,N(H),v.delta)),Dt(v.row);return}case"advance":tn(),Fn("chooser");return;case"commit":{let H=O(v.row);if(C.kind!=="values"||H===void 0)return;Fn("chooser"),Et(C.configId,H);return}case"save":{if(C.kind==="values"){let te=O(v.row);te!==void 0&&(xs(C.configId,te),Fn("chooser"),Et(C.configId,te));return}let H=T(v.row);if(H){let te=N(H);xs(H.id,te),te!==H.currentValue&&Et(H.id,te)}return}case"close":K=new Map,Fn("chooser");return;case"cancel":K=new Map,Fn("chooser");return;default:return}},ji=(y,v)=>U===null?!1:(Sd(v,Vu(v,y)),!0),qi=y=>{let v=yd;if(On===null||v===null)return!1;switch(On){case"questions":return Ff(y);case"options":return fl(y,v);case"title":return M(y,v);case"chooser":return ji(y,v)}},ml=y=>{let v=yd;if(!(On===null||v===null))for(let C of TP(v,y))switch(On){case"options":bd(C);break;case"title":E(v,C);break;case"chooser":Sd(v,C);break;case"questions":gl(jr===null?{type:"noop"}:R$(C,jr,qr,zr,wn,me));break}},gl=y=>{switch(y.type){case"noop":return;case"row":Gn=y.selectedRow,Kr();return;case"cycle":Gn=y.selectedRow,qr[y.selectedRow]=y.newValueIndex,zr[y.selectedRow]=!0,wn[y.selectedRow]=!1,Kr();return;case"dismiss-toggle":{let v=y.selectedRow;wn[v]?(wn[v]=!1,zr[v]=!1):(wn[v]=!0,zr[v]=!0),Kr();return}case"discard":wd();return;case"save":{let v=y.dispatches;if(wd(),v.length===0)return;(async()=>{let C=0,O=0,T=0;for(let H of v)try{await b.request(H.method,H.params),H.type==="dismiss"?O++:C++}catch(te){T++,ge({src:"questions",step:"dispatch_failed",method:H.method,error:te.message})}let N=[];C>0&&N.push(`${C} answered`),O>0&&N.push(`${O} dismissed`),T>0&&N.push(`${T} failed`),N.length>0&&R.notify(`clarifier: ${N.join(", ")}`)})();return}}},Ff=y=>jr===null?!1:(gl(P4(y,!0,jr,qr,zr,wn,Gn,me)),!0),rr=()=>{if(!I){I=!0,$?($.cancel(),$=null,F=null):F!==null&&(Js(t,F).catch(()=>{}),F=null),process.off("SIGINT",Mf),process.platform!=="win32"&&process.off("SIGCONT",xf),de!==null&&(clearInterval(de),de=null),Rt!==null&&(clearInterval(Rt),Rt=null),so();for(let y of ws.values())clearTimeout(y);ws.clear(),US(),HS(),Kt!==null&&(clearInterval(Kt),Kt=null),Ve!==null&&(clearInterval(Ve),Ve=null),qn!==null&&(k4(qn,{recursive:!0,force:!0}),qn=null),R.clearWindowTitle(),R.stop({keepFullscreen:!0}),ha(Qe,Zt).catch(()=>{}),w.close().catch(()=>{})}},xd=(y=0)=>{rr(),Wt&&(Wt(null),Wt=null),y!==0&&process.exit(y)},yl=async()=>{if(ge({src:"switch-session",step:"entered",finishSessionNull:Wt===null}),!Wt)return;$?($.cancel(),$=null,F=null):F!==null&&(Js(t,F).catch(()=>{}),F=null),ed(),so(),R.setSynthesisIndicator(null);let y=Be.state().buffer.join(`
|
|
297
|
+
`);y.replace(/\s+$/,"").length>0&&Ur(y),R.pauseRepaint(),R.stop({keepFullscreen:!0}),ha(Qe,Zt).catch(()=>{});let v=!1,C=null;try{let O=null,T=null,N=await yo();for(;O===null;){let ie=await Gs(t,{includeNonInteractive:!0}),ln=[];try{ln=await Aa(t)}catch{}let xt=vn=>ff({cwd:vn,config:N,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},...r.agentId!==void 0?{fallbackAgentId:r.agentId}:{},availableAgents:ln}),qe=vn=>ff({cwd:vn,config:N,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},availableAgents:ln}),{agentId:ht,model:Jt}=await xt(tt),Fe=await nS(n,{cwd:tt,sessions:ie,config:e,target:t,currentSessionId:me,prefs:i,...ht?{composerAgentId:ht}:{},...Jt?{composerModel:Jt}:{},...ln.length>0?{availableAgents:ln}:{},onComposerAgentChange:(vn,Gi)=>{mf(o,vn,Gi)},onCwdChange:qe});if(Fe.kind==="abort")return;if(Fe.kind==="exit"){v=!0,xd(0);return}if(Fe.kind==="new"){O={choice:Fe,sessions:ie};break}if(Fe.kind==="fork"){let vn=await P$(n,t,Fe,ie);if(vn.kind==="cancel")return;if(vn.kind==="back")continue;O={choice:{kind:"attach",sessionId:vn.ctx.sessionId,...vn.ctx.agentId?{agentId:vn.ctx.agentId}:{}},sessions:ie},T={readonly:!1,cwd:vn.ctx.cwd},vn.ctx.resumeHint!==void 0&&(T.resumeHint=vn.ctx.resumeHint);break}let un=ie.find(vn=>vn.sessionId===Fe.sessionId);if(!(un!==void 0&&!!un.importedFromMachine&&!un.remote&&!un.upstreamSessionId&&Fe.readonly!==!0)){if(t.isLocal&&un&&!un.importedFromMachine&&!un.remote&&Fe.readonly!==!0&&!(await Ju(un.cwd)).ok){Fe.installStatus?.finalize(),delete Fe.installStatus;let Gi=await Ja(n,un,{defaultCwd:mt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Gi.kind==="cancel")return;if(Gi.kind==="back")continue;O={choice:Fe,sessions:ie},T={readonly:!1,cwd:Gi.path,resumeHint:{agentId:Fe.agentId??un.agentId??"",cwd:Gi.path,upstreamSessionId:""}};break}O={choice:Fe,sessions:ie};break}let Gf={...r,readonly:!1};Fe.installStatus?.finalize(),delete Fe.installStatus;let xl=await T$(n,t,un,Fe,Gf);if(xl.kind==="cancel")return;xl.kind!=="back"&&(O={choice:Fe,sessions:ie},T={readonly:Gf.readonly===!0,cwd:xl.ctx.cwd},xl.ctx.resumeHint!==void 0&&(T.resumeHint=xl.ctx.resumeHint))}let{choice:H}=O;if(r.terminalHostLauncher&&(H.kind==="attach"||H.kind==="new")){H.installStatus?.finalize(),delete H.installStatus,C=await mS(H,O.sessions,T?.cwd??tt);return}let te=Wt;if(Wt=null,rr(),v=!0,H.kind==="new"){let{sessionId:ie,agentId:ln,...xt}=r,qe={...xt,cwd:H.cwd??tt,forceNew:!0,readonly:!1};H.prompt!==void 0&&(qe.initialPrompt=H.prompt),H.attachments&&H.attachments.length>0&&(qe.initialAttachments=H.attachments),H.agentId!==void 0&&(qe.agentId=H.agentId,H.agentExplicit&&mf(o,H.agentId,H.model)),H.model!==void 0&&(qe.model=H.model),H.installStatus!==void 0&&(qe.installStatus=H.installStatus),te(qe);return}if(H.kind!=="attach")return;let le={...r,sessionId:H.sessionId,cwd:T?.cwd??tt,readonly:T?.readonly??H.readonly===!0};H.agentId!==void 0&&(le.agentId=H.agentId),T?.resumeHint!==void 0?le.resumeHint=T.resumeHint:delete le.resumeHint,H.jumpToRecordedAt!==void 0?le.jumpToRecordedAt=H.jumpToRecordedAt:delete le.jumpToRecordedAt,H.installStatus!==void 0?le.installStatus=H.installStatus:delete le.installStatus,te(le)}finally{!v&&Wt&&(R.start({skipFullscreen:!0}),R.resumeRepaint(),C&&R.notify(C))}},Gr=async(y="next")=>{if(!Wt)return;let v=await Gs(t,{status:"warm"});if(v.length<=1)return;let C=v.findIndex(ie=>ie.sessionId===me),N=((C===-1?0:C)+(y==="prev"?-1:1)+v.length)%v.length,H=v[N],te=Wt;Wt=null,rr();let le={...r,sessionId:H.sessionId,cwd:tt,readonly:!1,resolved:H};H.agentId!==void 0&&(le.agentId=H.agentId),te(le)},Wo=async y=>{if(!Wt)return;let v=await Gs(t,{includeNonInteractive:!0}),C=y.trim();if(!C){R.notify("usage: /session <id|next|prev>");return}let O=C.startsWith(sn)?[C]:[C,sn+C],T=v.find(te=>O.includes(te.sessionId));if(!T){let te=v.filter(le=>O.some(ie=>le.sessionId.startsWith(ie)));if(te.length===1)T=te[0];else if(te.length>1){R.notify(`ambiguous session id: ${C} (${te.length} matches)`);return}}if(!T){R.notify(`no session matches: ${C}`);return}if(T.sessionId===me){R.notify("already on that session");return}if(r.terminalHostLauncher){let te=await mS({kind:"attach",sessionId:T.sessionId},v,T.cwd??tt);R.notify(te);return}let N=Wt;Wt=null,rr();let H={...r,sessionId:T.sessionId,cwd:T.cwd??tt,readonly:!1,resolved:T};T.agentId!==void 0&&(H.agentId=T.agentId),delete H.resumeHint,N(H)},zi=y=>{switch(y.type){case"send":o.defaultEnterAction==="amend"?Nf(y.text,y.attachments,y.displayText):jo(y.text,y.attachments,y.displayText);return;case"amend":o.defaultEnterAction==="amend"?jo(y.text,y.attachments,y.displayText):Nf(y.text,y.attachments,y.displayText);return;case"queue-edit":{let v=Lf(y.index);if(!v)return;let C=[];y.text.length>0&&C.push({type:"text",text:y.text});for(let O of y.attachments)C.push({type:"image",data:O.data,mimeType:O.mimeType});b.request("hydra-acp/prompt/update",{sessionId:me,messageId:v,prompt:C}).then(O=>{let T=O;if(T.updated||T.reason==="ok"){let N=Is.get(v);N&&(N.text=y.text,N.displayText=y.displayText??y.text,N.attachments=y.attachments)}else R.notify(`queue edit skipped (${T.reason})`)}).catch(O=>{R.notify(`queue edit failed: ${O.message}`)});return}case"queue-remove":{let v=Lf(y.index);if(!v)return;b.request("hydra-acp/prompt/cancel",{sessionId:me,messageId:v}).then(C=>{let O=C;!O.cancelled&&O.reason!=="ok"&&R.notify(`queue cancel skipped (${O.reason})`)}).catch(C=>{R.notify(`queue cancel failed: ${C.message}`)});return}case"cancel":{if(R.isOverlayOpen()){$&&($.cancel(),$=null,F=null),R.closeBtwOverlay();return}let v=tr[0];if(y.prefill&&v){let C=Ln.size===0,O=Be.state().buffer.every(T=>T==="");C&&O&&(id={text:v.text,attachments:v.attachments})}v?v.cancel():W>0&&cl(),ll();return}case"exit":hd();return;case"plan-toggle":Df(y.on);return;case"redraw-banner":R.setBanner({});return;case"redraw":R.fullRedraw();return;case"scroll-to-top":R.scrollToTop();return;case"scroll-to-bottom":R.scrollToBottom();return;case"switch-session":yl().catch(v=>{ge({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":Gr("next").catch(()=>{});return;case"prev-live-session":Gr("prev").catch(()=>{});return;case"toggle-options":po();return;case"toggle-sidebar":Zg(!R.isSidebarVisible());return;case"toggle-questions":Fg();return;case"toggle-thoughts":o.showThoughts=!o.showThoughts,R.setHideThoughts(!o.showThoughts),R.notify(o.showThoughts?"thoughts shown":"thoughts hidden");return;case"show-help":ul();return;case"escalate-search":R.enterScrollbackSearch(),R.updateScrollbackSearchTerm(y.query);return;case"attachment-request":Ng(y.source);return;case"edit-in-editor":Lg();return}},Lg=async()=>{let y=await Gm(Be.expandedText(),{suspend:()=>R.stop(),resume:()=>R.start(),notify:v=>R.notify(v)});y!==null&&(Be.setBuffer(y,Be.state().attachments),R.setAttachments(Be.state().attachments),R.refreshPrompt())},Id=async y=>{if(!In){R.notify("agent does not accept image attachments");return}let v=0;for(let C of y){if(C.startsWith("data:")){let T=Yk(C);if(!T){R.notify("unsupported data: URI");continue}if(T.sizeBytes>Zs){R.notify(`image too large (${Mr(T.sizeBytes)}, max ${Mr(Zs)})`);continue}Be.addAttachment({mimeType:T.mimeType,data:T.data,name:"pasted image",sizeBytes:T.sizeBytes}),v++;continue}let O=Qu(C);if(!O){R.notify(`unsupported image type: ${Ri.basename(C)}`);continue}try{let T=await fS.readFile(C);if(T.length>Zs){R.notify(`image too large (${Mr(T.length)}, max ${Mr(Zs)})`);continue}Be.addAttachment({mimeType:O,data:T.toString("base64"),name:Ri.basename(C),sizeBytes:T.length}),v++}catch(T){R.notify(`cannot read ${Ri.basename(C)}: ${T.message}`)}}v>0&&(R.setAttachments(Be.state().attachments),R.refreshPrompt())},Ng=async(y="clipboard")=>{let v=y==="primary"?await DP():await jm();if(!v.ok){R.notify(v.reason);return}if(v.kind==="image"){if(!In){R.notify("agent does not accept image attachments");return}Be.addAttachment(v.attachment),R.setAttachments(Be.state().attachments),R.refreshPrompt();return}let C=Be.feed({type:"paste",text:v.text});for(let O of C)zi(O);R.refreshPrompt()},Ki=y=>{let v=y.attachmentCount>0?`${y.text} \xB7 \u{1F4CE}\xD7${y.attachmentCount}`:y.text;return y.held?`\u23F8 ${v}`:v},Cd=(y,v)=>{let C=Array.isArray(v)?v:[],O="",T=0;for(let N of C){if(!N||typeof N!="object")continue;let H=N;H.type==="text"&&typeof H.text=="string"?O+=H.text:H.type==="image"&&(T+=1)}return{messageId:y,text:ot(O),attachmentCount:T}},Ln=new Map,Jn=[],Is=new Map,Jr=new Set,Vr=null,mo=()=>{let y=[...Ln.values()],v=y.map(Ki);R.setQueuedPrompts(v),R.setBanner({queued:y.length}),R.setSidebarSnapshot({queued:y.length}),Be.setQueue(y.map(C=>C.text))},Lf=y=>[...Ln.values()][y]?.messageId;if(io&&io.length>0){for(let y of io){if(y.position===0){ve=y.messageId;continue}Ln.set(y.messageId,Cd(y.messageId,y.prompt))}Ln.size>0&&mo()}let jo=(y,v,C)=>{R.scrollToBottom(),!Rd(y)&&(Ur(y,C),wl(y,v,C))},Vn=(y,v,C)=>{if(R.scrollToBottom(),Rd(y))return;if(Ur(y,C),!bs||ve===void 0){wl(y,v,C);return}let O=ve,T=[];y.length>0&&T.push({type:"text",text:y});for(let te of v)T.push({type:"image",data:te.data,mimeType:te.mimeType});let N={text:y,displayText:C??y,attachments:v,flushed:!1};Jn.push(N);let H=()=>{let te=Jn.indexOf(N);te>=0&&Jn.splice(te,1),N.messageId!==void 0&&Is.delete(N.messageId)};b.request("hydra-acp/prompt/amend",{sessionId:me,targetMessageId:O,prompt:T}).then(te=>{let le=te;if(le.amended&&le.reason==="ok"){Je(1,"self");return}if(H(),le.reason==="target_completed"){R.notify("previous response finished \u2014 press Enter to send as a new turn"),Be.setBuffer(y,v),R.refreshPrompt();return}if(le.reason==="target_cancelled"){R.notify("amend skipped \u2014 previous turn was cancelled"),Be.setBuffer(y,v),R.refreshPrompt();return}if(le.reason==="target_not_found"){R.notify("amend skipped \u2014 no matching prompt"),Be.setBuffer(y,v),R.refreshPrompt();return}}).catch(te=>{H(),R.notify(`amend failed: ${te.message}`),Be.setBuffer(y,v),R.refreshPrompt()})},Nf=(y,v,C)=>{if(R.scrollToBottom(),Rd(y))return;if(Ur(y,C),!Dr){Vn(y,v,C);return}let O=[];y.length>0&&O.push({type:"text",text:y});for(let H of v)O.push({type:"image",data:H.data,mimeType:H.mimeType});let T={text:y,displayText:C??y,attachments:v,flushed:!1};Jn.push(T);let N=()=>{let H=Jn.indexOf(T);H>=0&&Jn.splice(H,1),T.messageId!==void 0&&Is.delete(T.messageId)};b.request("_session/steering",{sessionId:me,prompt:O}).then(H=>{let te=H;if(te.outcome==="injected"){let le=Jn.indexOf(T);le>=0&&Jn.splice(le,1),T.flushed=!0,A({kind:"user-text",text:T.displayText,attachments:T.attachments}),Vr=T;return}if(te.outcome==="startedNewTurn"){te.detached!==!0&&Je(1,"self");return}N(),R.notify("steering failed"),Be.setBuffer(y,v),R.refreshPrompt()}).catch(H=>{if(H.code===-32601){N(),Vn(y,v,C);return}N(),R.notify(`steering failed: ${H.message}`),Be.setBuffer(y,v),R.refreshPrompt()})},Df=async y=>{if(Do.length===0){R.notify("no modes advertised by agent");return}let v=R.currentModeId(),C=Do.findIndex(N=>N.id===v),O=C===-1?0:(C+1)%Do.length,T=Do[O]?.id;if(T){R.setBanner({currentMode:T});try{await b.request("session/set_mode",{sessionId:me,modeId:T})}catch(N){R.notify(`set_mode failed: ${N.message}`)}}},Rd=y=>{let v=y.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
|
|
298
|
+
`))return!1;let C=v.indexOf(" "),O=C===-1?v:v.slice(0,C);switch(O){case"/quit":case"/exit":return hd(),!0;case"/clear":return Gt.clear(),Cs.clear(),L.length=0,ee.clear(),Te=null,X=null,$e=null,Yr.clear(),wr.clear(),ze.clear(),Ft.clear(),ae.clear(),lt.clear(),We.clear(),R.clearScrollback(),!0;case"/help":{let T=[{prefix:" ",body:"Built-in commands:",bodyStyle:"local-heading"}];for(let N of Cf)T.push({prefix:" ",body:` ${N.name.padEnd(12)} ${N.description??""}`,bodyStyle:"local-item"});if(dd.length>0){T.push({prefix:" ",body:"Agent commands:",bodyStyle:"local-heading"});for(let N of dd)T.push({prefix:" ",body:` ${N.name.padEnd(12)} ${N.description??""}`,bodyStyle:"local-item"})}return R.appendLines(T),!0}case"/agent":case"/model":case"/mode":{let T=O.slice(1),N=C===-1?"":v.slice(C+1).trim();if(!N)return pe(T),!0;let H=oe(T);if(!H)return!0;let te=se(H,N);return te===null?(R.notify(`unknown ${T}: ${N}`),!0):te===H.currentValue?(R.notify(`already on ${T} ${te}`),!0):(Et(T,te),!0)}case"/hydra":{let T=C===-1?"":v.slice(C+1).trim(),N=T.length>0?T.split(/\s+/):[];return N[0]!=="config"||N.length>2?!1:N.length===1?(nt(),!0):gr.some(H=>H.id===N[1])?(pe(N[1]),!0):!1}case"/title":{let T=C===-1?"":v.slice(C+1).trim();return T?r.readonly===!0?(R.notify("view-only: rename disabled"),!0):(Au(t,me,T).catch(N=>{R.notify(`rename failed: ${N.message}`)}),!0):(hl(R.sessionTitle()??""),!0)}case"/sessions":return R.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"notice"}]),!0;case"/resume":return yl().catch(T=>{ge({src:"switch-session-failed",stack:T instanceof Error?T.stack??T.message:String(T)})}),!0;case"/session":{let T=C===-1?"":v.slice(C+1).trim();return T?T==="next"||T==="prev"?(Gr(T).catch(N=>{R.notify(`session ${T} failed: ${N.message}`)}),!0):(Wo(T).catch(N=>{R.notify(`session switch failed: ${N.message}`)}),!0):(yl().catch(N=>{ge({src:"switch-session-failed",stack:N instanceof Error?N.stack??N.message:String(N)})}),!0)}case"/rename":{let T=C===-1?"":v.slice(C+1).trim(),N=T.length>0?`/hydra title ${T}`:"/hydra title";return Ur(v,v),wl(N,[],v),!0}case"/btw":{let T=C===-1?"":v.slice(C+1).trim();if(!T)return R.isOverlayOpen()?($&&($.cancel(),$=null,F=null),R.closeBtwOverlay(),!0):(R.reopenBtwOverlay()||R.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"notice-error"}]),!0);if(me==="__new__")return R.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"notice-error"}]),!0;Y+=1;let N=Y;$&&($.cancel(),$=null);let H=null;F!==null&&!J?H=F:F!==null&&(Js(t,F).catch(()=>{}),F=null),J=!1,R.openBtwOverlay(),R.setBtwOverlayStatus({label:"busy",style:"busy"});let te=new Bm({getMaxWidth:()=>{let xt=R.width();return xt>0?xt:void 0}});te.on("changed",()=>{R.setBtwOverlayContent(te.getLines())});let le={};te.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:T}]});let ie=xt=>{te.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:xt}})},ln={};return H!==null&&(ln.reuseSessionId=H),MP(t,me,T,ln).then(xt=>{if(N!==Y){xt.cancel();return}$=xt,F=xt.sessionId,R.setBtwOverlayMeta({sessionId:xt.sessionId}),xt.on("event",qe=>{if(N===Y)if(qe.kind==="update"){te.append(qe.update);let ht=js(qe.update);if(ht&&ht.kind==="usage-update"){let Jt=!1;ht.used!==void 0&&le.used!==ht.used&&(le.used=ht.used,Jt=!0),ht.size!==void 0&&le.size!==ht.size&&(le.size=ht.size,Jt=!0),ht.costAmount!==void 0&&le.costAmount!==ht.costAmount&&(le.costAmount=ht.costAmount,Jt=!0),ht.costCurrency!==void 0&&le.costCurrency!==ht.costCurrency&&(le.costCurrency=ht.costCurrency,Jt=!0),Jt&&R.setBtwOverlayMeta({usage:{...le}})}}else qe.kind==="completed"?(R.setBtwOverlayStatus({label:"done",style:"done"}),$=null):qe.kind==="cancelled"?(R.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),$=null,F=null):qe.kind==="errored"&&(R.setBtwOverlayStatus({label:"errored",style:"errored"}),ie(`btw errored: ${qe.error.message}`),F!==null&&Js(t,F).catch(()=>{}),$=null,F=null)})}).catch(xt=>{if(N!==Y)return;let qe=xt instanceof Error?xt.message:String(xt);R.setBtwOverlayStatus({label:"errored",style:"errored"}),ie(`btw startup failed: ${qe}`),R.appendLines([{prefix:" ",body:`btw startup failed: ${qe}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(me==="__new__")return R.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"notice-error"}]),!0;let T=C===-1?"":v.slice(C+1).trim(),N=me;return(async()=>{try{let H=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(N)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!H.ok){let qe=await H.text().catch(()=>"");R.appendLines([{prefix:" ",body:`/export failed: HTTP ${H.status} ${qe}`.trim(),bodyStyle:"notice-error"}]);return}let te=await H.text(),le=new Date().toISOString().replace(/[:.]/g,"-"),ie=`hydra-${st(N)}-${le}.md`,ln=T.length>0?mt(T):ie,xt=Ri.resolve(ln);await fS.mkdir(Ri.dirname(xt),{recursive:!0}),await fS.writeFile(xt,te,{encoding:"utf8",mode:384}),R.appendLines([{prefix:" ",body:`Wrote ${xt}`,bodyStyle:"notice-ok"}])}catch(H){R.appendLines([{prefix:" ",body:`/export failed: ${H.message}`,bodyStyle:"notice-error"}])}})(),!0}default:return!1}},wl=async(y,v,C)=>{let O=[];y.length>0&&O.push({type:"text",text:y});for(let qe of v)O.push({type:"image",data:qe.data,mimeType:qe.mimeType});Je(1,"self");let T={text:y,displayText:C??y,attachments:v,flushed:!1};Jn.push(T),W===1&&(at=!1);let N=!1,H=!1,te=null,le=qe=>{typeof xe<"u"&&xe!==null&&xe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:qe,bodyStyle:"tool-status-fail"}])},ie=!1,ln={text:y,attachments:v,cancel:()=>{if(at){at=!1,ie=!0,le("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),b.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(ht=>{le(`force-stop failed: ${ht.message}`)});return}if(N)return;N=!0,b.notify("session/cancel",{sessionId:me}).catch(()=>{});let qe=Date.now();te=setTimeout(()=>{H||Ut>=qe||(at=!0,le("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent)."))},Za)}};tr.push(ln);let xt;try{let qe=await b.request("session/prompt",{sessionId:me,prompt:O});qe&&typeof qe.stopReason=="string"&&(xt=qe.stopReason)}catch(qe){let ht=Jn.indexOf(T);ht>=0&&Jn.splice(ht,1),T.messageId!==void 0&&Is.delete(T.messageId),ie?R.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):R.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:qe.message,bodyStyle:"tool-status-fail"}])}finally{H=!0;let qe=tr.indexOf(ln);if(qe>=0&&tr.splice(qe,1),qe===0&&tr.length>0&&(at=!1),te!==null&&(clearTimeout(te),te=null),Je(-1),T.flushed&&Vr===T){let ht=T.messageId!==void 0&&Jr.has(T.messageId);ht&&T.messageId!==void 0&&Jr.delete(T.messageId);let Jt={kind:"turn-complete"};xt!==void 0&&(Jt.stopReason=xt),ht&&(Jt.amended=!0),A(Jt),Vr=null}if(id!==null){let{text:ht,attachments:Jt}=id;id=null,Be.state().buffer.every(un=>un==="")&&(Be.setBuffer(ht,Jt),R.refreshPrompt())}}},Gt=new Map;Xa=()=>{for(let y of Gt.values())if(uv(y.status))return!0;return!1};let Yr=new Map,wr=new Map,Cs=new Map,L=[],ee=new Map,fe=[],Q=0,Se=`tools:${Q}`,ze=new Map,Ft=new Map,Mt=new Set,dn=new Map,ae=new Map,lt=new Map,We=new Map,Te=null,X=null,$e=null,_e=null,vt=null,St=!1,Yn=null,Qr=e.tui.maxToolItems,cn=e.tui.maxPlanItems,Rs=()=>({maxPlanItems:Yn??o.planExpanded?1/0:cn}),qo=y=>{let v=F4(y.entries);St&&(St=!1,L4({stale:!0,hasKey:R.hasKey("plan"),prevFingerprint:vt,fingerprint:v})==="fresh"&&R.clearKey("plan")),vt=v;let C=Ro(y,Rs());C.length>0&&R.upsertLines("plan",[{body:""},...C]);let O=y.entries.length>0&&y.entries.every(T=>(T.status??"pending")==="completed");R.setStickyBottomKey(O?null:"plan")},Oe=()=>{if(_e===null)return;let y=Ro(_e,Rs());y.length>0&&R.upsertLines("plan",[{body:""},...y])},Xe="",kn=null,bl=0,Dg,W$=()=>{if(kn===null)return;let y=R.width(),v=Ao(Xe,y>0?{maxWidth:y}:void 0);v.length!==0&&R.upsertLines(kn,v)},j$=(y,v)=>{y.length!==0&&(kn===null&&(R.ensureSeparator(),kn=`agent:${bl}`,bl+=1,Xe="",Dg=v),Xe+=y,lt.set(kn,Xe),W$())},Xr=()=>{kn=null,Xe="",Dg=void 0},Ad="",zo=null,xS=0,Bg,q$=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),z$=()=>{if(zo===null||Ad.length===0)return;let y=Hc(Ad);y.length!==0&&R.upsertLines(zo,y)},IS=y=>{let v=ae.get(y);if(v===void 0)return[];let C=Hc(v.text);return v.workerTaskId&&C.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"muted"}),C},K$=(y,v)=>{y.length!==0&&(zo===null&&(R.ensureSeparator("thought"),zo=`thought:${xS}`,xS+=1,Ad="",Bg=v),Ad+=y,ae.set(zo,{text:Ad,workerTaskId:v}),z$())},Zr=()=>{Bg=void 0,zo=null,Ad=""},CS=y=>B4({...y,collapsedLimit:Qr}),RS=y=>Ft.get(y)??o.toolsExpanded,sr=()=>{if(Te===null)return;let{lines:y,rowOwners:v}=CS({order:L,states:Gt,startedAt:Te,endedAt:X,stopReason:$e,expanded:RS(Se),perToolExpanded:Mt});R.upsertLines(Se,y),dn.set(Se,v)},Bf=y=>{let v=ze.get(y);if(!v)return;let{lines:C,rowOwners:O}=CS({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:RS(y),perToolExpanded:Mt});R.upsertLines(y,C),dn.set(y,O)},Hg=()=>{Te!==null&&!ze.has(Se)&&sr();for(let y of ze.keys())Bf(y)},Ug=()=>{Te!==null&&ze.set(Se,{order:[...L],states:new Map(Gt),startedAt:Te,endedAt:X??Date.now(),stopReason:$e,rowOwners:dn.get(Se)??[]})},AS=y=>{Q+=1,Se=`tools:${Q}`,Te=y??Date.now(),X=null,$e=null,sr()};function G$(y){if(!y||typeof y!="object")return null;let v=y,C=Array.isArray(v.content)?v.content:void 0,O=[],T=N=>{if(typeof N=="string"){O.push({text:zt(N)});return}if(N&&typeof N=="object"){let H=N;typeof H.__hydraBlob=="string"&&O.push({hash:H.__hydraBlob})}};for(let N of C??[]){if(!N||typeof N!="object")continue;let H=N;if(H.type==="content"&&H.content&&typeof H.content=="object"){let te=H.content;if(te.text!==void 0){T(te.text);continue}}if(H.type==="text"&&H.text!==void 0){T(H.text);continue}H.text!==void 0&&T(H.text)}if(O.length===0)for(let N of hA(v))T(N);return O.length>0?O:null}let TS=(y,v)=>{let C=v.map(N=>"text"in N?N.text:"").join(`
|
|
299
|
+
`);if(C.length===0)return;let{text:O,truncated:T}=k0(C);y.resultText=O,y.resultTruncated=T},Hf=new Set,J$=(y,v)=>{!v.some(O=>"hash"in O)||Hf.has(y)||(Hf.add(y),(async()=>{let O=await Promise.all(v.map(async N=>"text"in N?N:{text:await jg(N.hash)??""}));Hf.delete(y);let T=Gt.get(y);if(!T)for(let N of ze.values()){let H=N.states.get(y);if(H){T=H;break}}if(T){TS(T,O),Gt.has(y)&&sr();for(let[N,H]of ze)H.states.has(y)&&Bf(N);R.repaintNow()}})().catch(()=>{Hf.delete(y)}))},Wg=(y,v)=>{let C=v??Gt.get(y);if(C===void 0)return;let O=r$(C,Yr.get(y)??C.editDiff,tt);if(O===null){ee.delete(y);return}ee.set(y,O)},ES=(y,v,C,O,T,N,H,te,le,ie,ln,xt,qe=!1)=>{let ht=!Gt.has(y),Jt=Gt.get(y),Fe=Jt??{initialTitle:v??"tool",latestTitle:v??"tool",status:C??"pending",startedAt:xt??Date.now()};if(!Jt&&le!==void 0&&(Fe.workerTaskId=le),ln!==void 0&&Fe.rawKind===void 0&&(Fe.rawKind=ln),Jt&&v!==void 0&&(Fe.latestTitle=v),N!==void 0&&Fe.detail===void 0&&(Fe.detail=N),H!==void 0&&Fe.detailFull===void 0&&(Fe.detailFull=H),te!==void 0&&te.length>0&&(Fe.locations=te),Jt&&C!==void 0&&(Fe.status=C),Jt||(Fe.status=C??"pending"),Fe.endedAt===void 0&&ek(Fe.status)&&(Fe.endedAt=xt??Date.now(),Fe.startedAt!==void 0&&Fe.endedAt<Fe.startedAt&&(Fe.endedAt=Fe.startedAt),Xg()),O!==void 0&&(Fe.errorText=O),T!==void 0&&(Fe.editDiff=T),ie!==void 0){let Ko=Cb(ie);Ko!==void 0&&(Fe.resultSummary=Ko)}if(ie!==void 0){let Ko=G$(ie);Ko!==null&&(TS(Fe,Ko),Ko.some(Gf=>"hash"in Gf)&&J$(y,Ko))}Gt.set(y,Fe),Wg(y,Fe);let un=i$(ie);un!==null&&(fe=un,Xg(),un.length>0&&qo({kind:"plan",entries:un})),ht&&(B_({blockOpen:Te!==null,isStart:qe})&&(Q+=1,Se=`tools:${Q}`,Te=Date.now(),X=null,$e=null),Te!==null&&L.push(y),R.isSidebarVisible()&&Sl())},jg=async y=>{try{let v=await b.request("hydra-acp/session/tool_content",{sessionId:me,hash:y});return typeof v?.content=="string"?v.content:null}catch{return null}},Uf=new Set,V$=(y,v)=>{Uf.has(y)||v.oldRef===void 0&&v.newRef===void 0||(Uf.add(y),(async()=>{let[C,O]=await Promise.all([v.oldRef?jg(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?jg(v.newRef.hash):Promise.resolve(v.newText)]);if(v.oldRef!==void 0&&C===null||v.newRef!==void 0&&O===null){Uf.delete(y);let ie=MS(y,v,Qb(v,"diff",{deferredStatus:"error"}));ie.length>0&&(R.upsertLines(`editdiff:${y}`,ie),R.repaintNow());return}let N={...v.path!==void 0?{path:v.path}:{},oldText:C??"",newText:O??""};Yr.set(y,N);let H=Gt.get(y);H?.editDiff&&(H.editDiff=N),Wg(y),Uf.delete(y);let te=wr.get(y),le=te===void 0?o.showFileUpdates:te?"diff":"edit";le!=="none"&&(Wf(y,N,le==="diff"?"diff":"edit"),R.repaintNow())})())},PS=new Map,MS=(y,v,C)=>{let O=PS.get(y);return O===void 0&&(O=Gt.get(y)?.locations?.[0]?.line??aO(v),PS.set(y,O)),O===null?C:C.map(T=>T.links===void 0?T:{...T,links:T.links.map(N=>({...N,url:`${N.url}#L${O}`}))})},Wf=(y,v,C)=>{let O=`editdiff:${y}`,T=MS(y,v,Qb(v,C));if(T.length===0){R.removeKey(O);return}R.upsertLines(O,T),C==="diff"&&(v.oldRef!==void 0||v.newRef!==void 0)&&R.notifyWhenVisible(O)},Y$=y=>{if(!y.startsWith("editdiff:"))return;let v=y.slice(9),C=Yr.get(v);C&&(C.oldRef!==void 0||C.newRef!==void 0)&&V$(v,C)},_S=y=>{let v=`editdiff:${y}`,C=o.showFileUpdates,O=Gt.get(y),T;if(C==="none"||!O?.editDiff||O.status!=="completed")T=null;else{let H=wr.get(y);T=H!==void 0?H?"diff":"edit":C==="diff"?"diff":"edit"}if(T===null){R.removeKey(v);return}let N=O.editDiff;Yr.set(y,N),Wg(y),Wf(y,N,T)},qg=()=>{let y=o.showFileUpdates;for(let[v,C]of Yr){let O=`editdiff:${v}`,T=wr.get(v),N=T===void 0?y:T?"diff":"edit";if(N==="none"){R.removeKey(O);continue}Wf(v,C,N==="diff"?"diff":"edit")}},$S=()=>{let y=R.width(),v=y>0?{maxWidth:y}:void 0;for(let[O,T]of lt){let N=Ao(T,v);N.length>0&&R.upsertLines(O,N)}let C=new Set;for(let O of We.values())for(let T of O)C.add(T);for(let O of ae.keys()){if(C.has(O))continue;let T=IS(O);T.length>0&&R.upsertLines(O,T)}},OS=()=>{R.isSidebarOverlay()||(Hg(),qg(),Oe(),$S())},zg=!1,jf=null,FS=y=>{p$("git",["status","--porcelain=v2","--branch"],{cwd:y,timeout:3e3,maxBuffer:4*1024*1024},(v,C)=>{zg=!1,R.setSidebarSnapshot({git:v?null:t$(C,jf)})})},kl=()=>{if(zg||tt===null)return;if(jn){R.setSidebarSnapshot({git:null});return}let y=tt;if(zg=!0,jf!==null){FS(y);return}p$("git",["rev-parse","--show-toplevel"],{cwd:y,timeout:3e3},(v,C)=>{v||(jf=C.trim()||null),FS(y)})},Kg=!1,Gg=()=>{Kg||(Kg=!0,(async()=>{try{let y=await Gs(t,{status:"warm"}),v=[];for(let C of y)C.sessionId!==me&&v.push({sessionId:C.sessionId,label:C.title!==void 0&&C.title.length>0?C.title:st(C.sessionId),busy:C.busy===!0,armed:(C.armedTasks??0)>0,blocked:C.awaitingInput===!0});R.setSidebarSnapshot({liveSessions:v})}catch{}finally{Kg=!1}})())},Q$="hydra",X$="agent",qf=null,Jg=!1,zf=null,vl=null,Vg=null,Yg=!1,LS=(()=>{try{let y=new URL(t.baseUrl).hostname;return y==="127.0.0.1"||y==="localhost"||y==="::1"||y==="[::1]"}catch{return!1}})(),NS=()=>{Yg||me===null||(Yg=!0,(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(y.ok){let v=await y.json();Vg=typeof v.agentPid=="number"?v.agentPid:null}}catch{}finally{Yg=!1}})())},DS=()=>{Jg||(Jg=!0,(async()=>{try{let y=[],v=process.cpuUsage(),C=Date.now();y.push({label:Q$,rssBytes:process.memoryUsage.rss(),cpuFraction:c$(v,zf,vl===null?0:C-vl),processes:1}),zf=v,vl=C;let O=Vg;if(O!==null){let T=await u$([O]),N=l$(T,qf,O);N!==null&&y.push({label:X$,...N}),qf=T}R.setSidebarSnapshot({resources:y})}finally{Jg=!1}})())},BS=()=>{R.isSidebarGadgetActive("resources")&&(qf=null,zf=null,vl=null,LS&&NS(),DS())},Z$=()=>{qf=null,zf=null,vl=null,Vg=null,R.setSidebarSnapshot({resources:[]})},eO=()=>{R.isSidebarGadgetActive("sessions")&&Gg()},tO=()=>{R.setSidebarSnapshot({liveSessions:[]})},nO=()=>{R.isSidebarGadgetActive("git")&&kl()},HS=()=>{R.setSidebarSnapshot({git:null})},rO=5,Td=null,Qg=0,sO=()=>{Td===null&&(Qg=0,Td=setInterval(()=>{Qg++;let y=Qg%rO===0;(Ne!==null||y)&&Sl(),y&&R.isSidebarGadgetActive("git")&&kl(),y&&R.isSidebarGadgetActive("sessions")&&Gg(),y&&R.isSidebarGadgetActive("resources")&&(LS&&NS(),DS())},1e3),Td.unref?.())},US=()=>{Td!==null&&(clearInterval(Td),Td=null)},Xg=()=>{R.isSidebarVisible()&&(Sl(),R.isSidebarGadgetActive("git")&&kl())},Zg=y=>{o.sidebarVisible=y,R.setSidebarVisible(y),OS(),Sl(),R.isSidebarSuppressed()?R.notify("sidebar needs a wider terminal (80+ columns)"):y&&R.isSidebarOverlay()&&R.notify("sidebar overlaying transcript (too wide to reflow)"),R.fullRedraw(),y?(nO(),eO(),BS(),sO()):(HS(),tO(),Z$(),US())},Sl=()=>{R.setSidebarSnapshot({busySince:Ne,lastTurnEndedAt:Re,queued:Ln.size,plan:oO(),editedFiles:iO(),running:eM(L,Gt,tt),sessionId:me===null?null:st(me),agent:ud()})},oO=()=>_e!==null&&_e.entries.length>0?_e.entries:fe,iO=()=>s$(ee.values()),aO=y=>{if(!y.path||jn)return null;let v=zt(y.oldText).split(`
|
|
300
300
|
`),C=zt(y.newText).split(`
|
|
301
301
|
`),O=0,T=Math.min(v.length,C.length);for(;O<T&&v[O]===C[O];)O++;let N=C[O];if(!N)return null;let H=Ri.isAbsolute(y.path)?y.path:Ri.resolve(tt,y.path),te;try{te=b4(H,"utf8")}catch{return null}let le=te.split(`
|
|
302
|
-
`);for(let ie=0;ie<le.length;ie++)if(le[ie]===N)return ie+1;return null},dO=(y,v,C=null)=>{if(y.startsWith("editdiff:")){let O=y.slice(9),T=Yr.get(O);if(!T)return;let N=wr.get(O)??o.showFileUpdates==="diff";wr.set(O,!N),Wf(O,T,N?"edit":"diff"),R.repaintNow();return}if(y==="plan"){if(_e===null)return;Yn=!(Yn??o.planExpanded),Oe(),R.repaintNow();return}if(y.startsWith("tools:")){if(C===null&&v===0){let N=Ft.get(y)??o.toolsExpanded;Ft.set(y,!N),y===Se&&Te!==null?sr():Bf(y),R.repaintNow();return}let T=C??dn.get(y)?.[v];if(!T)return;O4(T,Mt),y===Se&&Te!==null?sr():Bf(y),R.repaintNow();return}if(y.startsWith("thought:")){if(!ae.has(y))return;let O=We.get(y);if(O!==void 0){We.delete(y),R.setRunCollapsed(O,!1,IS(y)),R.repaintNow();return}let T=R.contiguousRun(y,new Set(ae.keys()));if(T.length===0)return;let N=T[0];We.set(N,T),R.setRunCollapsed(T,!0,[q$()]),R.repaintNow();return}};S=(y,v,C)=>{if(y.kind==="available-commands"){dd=y.commands,cd();return}if(y.kind==="available-modes"){Do=y.modes;return}if(y.kind==="config-options"){gr=y.options;let T=y.options.find(H=>H.id==="agent");T&&T.currentValue&&T.currentValue!==It&&(It=T.currentValue,R.setSessionbar({agent:T.currentValue}),R.setSidebarSnapshot({agent:ud()}));let N=y.options.find(H=>H.id==="mode");N&&(Do=N.options.map(H=>({id:H.value,name:H.name??H.value,...H.description!==void 0?{description:H.description}:{}})));return}if(y.kind==="mode-changed"){R.setBanner({currentMode:y.mode||void 0}),R.setSidebarSnapshot({mode:y.mode||null});return}if(y.kind==="session-info"){y.title!==void 0&&R.setSessionbar({title:y.title}),y.agentId!==void 0&&y.agentId!==It&&(It=y.agentId,R.setSessionbar({agent:y.agentId}),R.setSidebarSnapshot({agent:ud()})),y.pendingAgentSwap!==void 0&&(typeof y.pendingAgentSwap=="string"?R.setCompactionIndicator(`switching to ${y.pendingAgentSwap}...`):(R.setCompactionIndicator(null),y.agentId!==void 0&&R.notify(`switched to ${y.agentId}`,2e3)));return}if(y.kind==="usage-update"){let T=!1;y.used!==void 0&&Ot.used!==y.used&&(Ot.used=y.used,T=!0),y.size!==void 0&&Ot.size!==y.size&&(Ot.size=y.size,T=!0),y.costAmount!==void 0&&Ot.costAmount!==y.costAmount&&(Ot.costAmount=y.costAmount,T=!0),y.costCurrency!==void 0&&Ot.costCurrency!==y.costCurrency&&(Ot.costCurrency=y.costCurrency,T=!0),T&&(R.setSessionbar({usage:{...Ot}}),R.setSidebarSnapshot({usage:{...Ot}}));return}if(y.kind==="user-text"){zn&&Ur(y.text),Xr(),Zr(),Te!==null&&(X=C??Date.now(),sr()),Vr=null,R.ensureSeparator();let T=Ro(y);T.length>0&&(C!==void 0&&(T[0].recordedAt=C),R.appendLines(T)),Ug(),St=!0,R.setStickyBottomKey(null),_e=null,Yn=null,Gt.clear(),Cs.clear(),L.length=0,X=null,AS(C),R.redraw();return}if(y.kind==="agent-text"){Zr(),kn!==null&&Dg!==y.workerTaskId&&Xr(),kn===null&&P(y.workerTaskId),j$(y.text,y.workerTaskId);return}if(y.kind==="agent-thought"){Xr(),zo!==null&&Bg!==y.workerTaskId&&Zr(),zo===null&&P(y.workerTaskId),K$(y.text,y.workerTaskId);return}if(y.kind==="exit-plan-mode"){Xr(),Zr();let T=Cs.get(y.toolCallId),N={plan:y.plan??T?.plan??"",status:y.status??T?.status};if(Cs.set(y.toolCallId,N),N.plan.length===0)return;let H=R0(N);H.length>0&&R.upsertLines(y.toolCallId,H);return}if(y.kind==="tool-call"){y.parentToolUseId===void 0&&(Xr(),Zr()),Gt.has(y.toolCallId)||P(y.workerTaskId),ES(y.toolCallId,y.title,y.status,void 0,y.editDiff,y.detail,y.detailFull,y.locations,y.workerTaskId,v,y.rawKind,C,!0),sr(),_S(y.toolCallId);return}if(y.kind==="plan"){Xr(),Zr(),_e=y,Xg(),qo(y);return}if(y.kind==="turn-started"){if(!y.unsolicited)return;Xr(),Zr(),R.ensureSeparator(),R.appendLines(Ro(y)),De||(De=!0,Je(1,"agent",y.cause??null));return}if(y.kind==="turn-ended"){if(!y.unsolicited)return;Xr(),Zr(),Te!==null&&X===null&&(X=C??Date.now(),sr()),De&&(De=!1,Je(-1));return}if(y.kind==="tool-call-update"){y.parentToolUseId===void 0&&(Xr(),Zr()),ES(y.toolCallId,y.title,y.status,y.errorText,y.editDiff,y.detail,y.detailFull,y.locations,y.workerTaskId,v,void 0,C),y.upstreamInterrupted&&(ce=!0),sr(),_S(y.toolCallId);return}y.kind==="model-changed"&&(R.setSessionbar({model:y.model}),R.setSidebarSnapshot({model:y.model}));let O=Ro(y);if(O.length>0&&R.appendLines(O),y.kind==="turn-complete"){ve=void 0,Xr(),Zr();let T=y.amended?"amended":y.stopReason;if(!y.amended&&ce&&(T===void 0||T==="end_turn")&&(T="error"),_e!==null&&T!==void 0&&T!=="end_turn"){let N=Ro({..._e,stopped:!0,amended:y.amended===!0},Rs());N.length>0&&R.upsertLines("plan",[{body:""},...N])}_e=null,Yn=null,St=!0,R.setStickyBottomKey(null),Te!==null?(X=C??Date.now(),$e=T??null,sr(),Ug()):T!==void 0&&T!=="end_turn"&&T!=="amended"&&R.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${T}`,bodyStyle:"tool-status-fail"}]),Gt.clear(),Cs.clear(),L.length=0,Te=null,X=null,$e=null,ce=!1,R.ensureSeparator(),D_({pendingTurns:W,queueSize:Ln.size,ownTurnInFlight:tr.length>0,hasInFlightHead:ve!==void 0,replayDraining:x,amended:y.amended===!0})&&Je(-W)}};let WS=k;k=[];let Kf=[];for(let{event:y}of WS)y.kind==="user-text"&&typeof y.text=="string"&&Kf.push(y.text);R.pauseRepaint(),x=!0;try{for(let{event:y,rawUpdate:v,recordedAt:C}of WS)S(y,v,C);Oi!==void 0&&R.scrollToTurnAt(Oi)}finally{x=!1,R.resumeRepaint()}if(Kf.length>0){let y=lb(Zt,Kf);y!==Zt&&(Zt=y,ao=lb(ao,Kf),Be.setHistory(nh(en,ao)),ha(Qe,Zt).catch(()=>{}),Ni())}zn=!0,R.setSidebarCollapsed(o.sidebarCollapsed),o.sidebarVisible&&Zg(!0),(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!y.ok)return;let v=await y.json();if(typeof v.pendingAgentSwap=="string")R.setCompactionIndicator(`switching to ${v.pendingAgentSwap}...`);else{let N=v.compactionState?.status;N==="requested"||N==="running"?R.setCompactionIndicator("compacting..."):(N==="swap_pending"||N==="swap_deferred")&&R.setCompactionIndicator("compaction queued (waiting for idle)")}if(!Sf||v.shouldCompact!==!0)return;let C=v.currentUsage?.used,O=v.currentUsage?.size,T=typeof C=="number"&&typeof O=="number"&&O>0?`This session is using ${Zs(C)} of its ${Zs(O)} token context window.`:`This session has ~${sA(v.approxTokens??0)} tokens of history above the compaction watermark.`;Z=!0,R.setCompactionPrompt({message:T,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!y.ok)return;let v=await y.json();if(Ae&&Re===null&&Ne===null&&typeof v.updatedAt=="string"){let C=Date.parse(v.updatedAt);Number.isFinite(C)&&(Re=C,R.setSidebarSnapshot({lastTurnEndedAt:Re}))}v.forkSynthesisState==="running"?(R.setSynthesisIndicator("synthesizing context\u2026"),ol()):v.forkSynthesisState==="failed"&&(R.setSynthesisIndicator("\u26A0 synthesis failed"),R.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Hr!==void 0&&W>0?(Ne=Hr,R.setBanner({status:"busy",elapsedMs:Date.now()-Hr}),de===null&&(de=mr()),Te===null&&AS(Hr),Te=Hr,sr()):Hr===void 0&&W>0&&Je(-W),gn(od??null,io===void 0?void 0:pS(io)),Ge=!0;let cO=()=>{if(Ye){let y=Ye.resolve;Ye=null,R.setPermissionPrompt(null),y({outcome:{outcome:"cancelled"}})}Xr(),Zr()},jS=()=>{Te!==null&&(X=Date.now(),$e="reconnect-recovery-failed",sr(),Ug(),Gt.clear(),Cs.clear(),L.length=0,Te=null,X=null,$e=null)};return g=y=>{ge({src:"reconnect",step:"disconnect",message:y?.message}),R.setBanner({status:"disconnected",elapsedMs:void 0})},h=async y=>{let v=y?.skipInitialize===!0;if(ge({src:"reconnect",step:"begin",sessionId:me,skipInitialize:v}),t.isLocal)try{let ie=await rn(await He());(ie.baseUrl!==t.baseUrl||ie.wsUrl!==t.wsUrl||ie.token!==t.token)&&(ge({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:ie.baseUrl}),t.baseUrl=ie.baseUrl,t.wsUrl=ie.wsUrl,t.display=ie.display,t.token=ie.token)}catch(ie){ge({src:"reconnect",step:"target-refresh-failed",message:ie instanceof Error?ie.message:String(ie)})}cO();let C={jsonrpc:"2.0",id:`tui-reinit-${gS()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Ue}}};if(!v){ge({src:"reconnect",step:"initialize-send"});try{await w.request(C),ge({src:"reconnect",step:"initialize-ok"})}catch(ie){ge({src:"reconnect",step:"initialize-fail",message:ie.message})}}let O=Lr!==void 0||Nr!==void 0,T={jsonrpc:"2.0",id:`tui-reattach-${gS()}`,method:"session/attach",params:{sessionId:me,historyPolicy:O?"after_message":"none",...O&&Lr!==void 0?{afterMessageId:Lr}:{},...O&&Nr!==void 0?{afterSeq:Nr}:{},clientInfo:{name:"hydra-acp-tui",version:Ue},...(()=>{let ie={};return _i!==void 0&&(ie.resume={upstreamSessionId:_i,agentId:It,cwd:tt}),e.tui.toolContent==="references"&&(ie.toolContent="references"),Object.keys(ie).length>0?{_meta:{[ut]:ie}}:{}})()}};Oo=[];let N,H,te;ge({src:"reconnect",step:"attach-send",useAfterMessage:O,lastSeenMessageId:Lr,lastSeenSeq:Nr});try{let ie=await w.request(T);if(ge({src:"reconnect",step:"attach-resp",hasError:!!ie.error}),ie.error)throw new Error(ie.error.message);te=N_(ie.result),N=te.appliedPolicy,te.clientId!==void 0&&(Br=te.clientId)}catch(ie){H=ie,ge({src:"reconnect",step:"attach-fail",message:H.message})}let le=Oo??[];if(Oo=null,H)jS(),R.appendLines([{prefix:" ",body:`reattach failed: ${H.message}`,bodyStyle:"tool-status-fail"}]);else if(O&&N!=="after_message")jS(),R.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{le.length>0&&y?.beforeReplay?.(),x=!0;try{for(let ie of le)sl(ie)}finally{x=!1}}if(H||ro(),te){let ie=H_({daemonTurnStartedAt:te.turnStartedAt,pendingTurns:W});ie.pendingTurnsDelta!==0&&Je(ie.pendingTurnsDelta),ie.banner==="busy"&&ie.busySince!==void 0?(Ne=ie.busySince,R.setBanner({status:"busy",elapsedMs:Date.now()-ie.busySince}),de===null&&(de=mr())):R.setBanner({status:"ready",elapsedMs:void 0}),te.armedTasks!==void 0&&gn(te.armedTasks>0?te.armedSince??null:null,te.armedTaskList===void 0?void 0:pS(te.armedTaskList))}else R.setBanner({status:W>0?"busy":"ready",elapsedMs:W>0?0:void 0});ge({src:"reconnect",step:"end"})},b.onClose(y=>{y&&B(n,"notice-error",`
|
|
302
|
+
`);for(let ie=0;ie<le.length;ie++)if(le[ie]===N)return ie+1;return null},dO=(y,v,C=null)=>{if(y.startsWith("editdiff:")){let O=y.slice(9),T=Yr.get(O);if(!T)return;let N=wr.get(O)??o.showFileUpdates==="diff";wr.set(O,!N),Wf(O,T,N?"edit":"diff"),R.repaintNow();return}if(y==="plan"){if(_e===null)return;Yn=!(Yn??o.planExpanded),Oe(),R.repaintNow();return}if(y.startsWith("tools:")){if(C===null&&v===0){let N=Ft.get(y)??o.toolsExpanded;Ft.set(y,!N),y===Se&&Te!==null?sr():Bf(y),R.repaintNow();return}let T=C??dn.get(y)?.[v];if(!T)return;O4(T,Mt),y===Se&&Te!==null?sr():Bf(y),R.repaintNow();return}if(y.startsWith("thought:")){if(!ae.has(y))return;let O=We.get(y);if(O!==void 0){We.delete(y),R.setRunCollapsed(O,!1,IS(y)),R.repaintNow();return}let T=R.contiguousRun(y,new Set(ae.keys()));if(T.length===0)return;let N=T[0];We.set(N,T),R.setRunCollapsed(T,!0,[q$()]),R.repaintNow();return}};S=(y,v,C)=>{if(y.kind==="available-commands"){dd=y.commands,cd();return}if(y.kind==="available-modes"){Do=y.modes;return}if(y.kind==="config-options"){gr=y.options;let T=y.options.find(H=>H.id==="agent");T&&T.currentValue&&T.currentValue!==It&&(It=T.currentValue,R.setSessionbar({agent:T.currentValue}),R.setSidebarSnapshot({agent:ud()}));let N=y.options.find(H=>H.id==="mode");N&&(Do=N.options.map(H=>({id:H.value,name:H.name??H.value,...H.description!==void 0?{description:H.description}:{}})));return}if(y.kind==="mode-changed"){R.setBanner({currentMode:y.mode||void 0}),R.setSidebarSnapshot({mode:y.mode||null});return}if(y.kind==="session-info"){y.title!==void 0&&R.setSessionbar({title:y.title}),y.agentId!==void 0&&y.agentId!==It&&(It=y.agentId,R.setSessionbar({agent:y.agentId}),R.setSidebarSnapshot({agent:ud()})),y.pendingAgentSwap!==void 0&&(typeof y.pendingAgentSwap=="string"?R.setCompactionIndicator(`switching to ${y.pendingAgentSwap}...`):(R.setCompactionIndicator(null),y.agentId!==void 0&&R.notify(`switched to ${y.agentId}`,2e3)));return}if(y.kind==="usage-update"){let T=!1;y.used!==void 0&&Ot.used!==y.used&&(Ot.used=y.used,T=!0),y.size!==void 0&&Ot.size!==y.size&&(Ot.size=y.size,T=!0),y.costAmount!==void 0&&Ot.costAmount!==y.costAmount&&(Ot.costAmount=y.costAmount,T=!0),y.costCurrency!==void 0&&Ot.costCurrency!==y.costCurrency&&(Ot.costCurrency=y.costCurrency,T=!0),T&&(R.setSessionbar({usage:{...Ot}}),R.setSidebarSnapshot({usage:{...Ot}}));return}if(y.kind==="user-text"){zn&&Ur(y.text),Xr(),Zr(),Te!==null&&(X=C??Date.now(),sr()),Vr=null,R.ensureSeparator();let T=Ro(y);T.length>0&&(C!==void 0&&(T[0].recordedAt=C),R.appendLines(T)),Ug(),St=!0,R.setStickyBottomKey(null),_e=null,Yn=null,Gt.clear(),Cs.clear(),L.length=0,X=null,AS(C),R.redraw();return}if(y.kind==="agent-text"){Zr(),kn!==null&&Dg!==y.workerTaskId&&Xr(),kn===null&&P(y.workerTaskId),j$(y.text,y.workerTaskId);return}if(y.kind==="agent-thought"){Xr(),zo!==null&&Bg!==y.workerTaskId&&Zr(),zo===null&&P(y.workerTaskId),K$(y.text,y.workerTaskId);return}if(y.kind==="exit-plan-mode"){Xr(),Zr();let T=Cs.get(y.toolCallId),N={plan:y.plan??T?.plan??"",status:y.status??T?.status};if(Cs.set(y.toolCallId,N),N.plan.length===0)return;let H=R0(N);H.length>0&&R.upsertLines(y.toolCallId,H);return}if(y.kind==="tool-call"){y.parentToolUseId===void 0&&(Xr(),Zr()),Gt.has(y.toolCallId)||P(y.workerTaskId),ES(y.toolCallId,y.title,y.status,void 0,y.editDiff,y.detail,y.detailFull,y.locations,y.workerTaskId,v,y.rawKind,C,!0),sr(),_S(y.toolCallId);return}if(y.kind==="plan"){Xr(),Zr(),_e=y,Xg(),qo(y);return}if(y.kind==="turn-started"){if(!y.unsolicited)return;Xr(),Zr(),R.ensureSeparator(),R.appendLines(Ro(y)),De||(De=!0,Je(1,"agent",y.cause??null));return}if(y.kind==="turn-ended"){if(!y.unsolicited)return;Xr(),Zr(),Te!==null&&X===null&&(X=C??Date.now(),sr()),De&&(De=!1,Je(-1));return}if(y.kind==="tool-call-update"){y.parentToolUseId===void 0&&(Xr(),Zr()),ES(y.toolCallId,y.title,y.status,y.errorText,y.editDiff,y.detail,y.detailFull,y.locations,y.workerTaskId,v,void 0,C),y.upstreamInterrupted&&(ce=!0),sr(),_S(y.toolCallId);return}y.kind==="model-changed"&&(R.setSessionbar({model:y.model}),R.setSidebarSnapshot({model:y.model}));let O=Ro(y);if(O.length>0&&R.appendLines(O),y.kind==="turn-complete"){ve=void 0,Xr(),Zr();let T=y.amended?"amended":y.stopReason;if(!y.amended&&ce&&(T===void 0||T==="end_turn")&&(T="error"),_e!==null&&T!==void 0&&T!=="end_turn"){let N=Ro({..._e,stopped:!0,amended:y.amended===!0},Rs());N.length>0&&R.upsertLines("plan",[{body:""},...N])}_e=null,Yn=null,St=!0,R.setStickyBottomKey(null),Te!==null?(X=C??Date.now(),$e=T??null,sr(),Ug()):T!==void 0&&T!=="end_turn"&&T!=="amended"&&R.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${T}`,bodyStyle:"tool-status-fail"}]),Gt.clear(),Cs.clear(),L.length=0,Te=null,X=null,$e=null,ce=!1,R.ensureSeparator(),D_({pendingTurns:W,queueSize:Ln.size,ownTurnInFlight:tr.length>0,hasInFlightHead:ve!==void 0,replayDraining:x,amended:y.amended===!0})&&Je(-W)}};let WS=k;k=[];let Kf=[];for(let{event:y}of WS)y.kind==="user-text"&&typeof y.text=="string"&&Kf.push(y.text);R.pauseRepaint(),x=!0;try{for(let{event:y,rawUpdate:v,recordedAt:C}of WS)S(y,v,C);Oi!==void 0&&R.scrollToTurnAt(Oi)}finally{x=!1,R.resumeRepaint()}if(Kf.length>0){let y=lb(Zt,Kf);y!==Zt&&(Zt=y,co=lb(co,Kf),Be.setHistory(nh(en,co)),ha(Qe,Zt).catch(()=>{}),Ni())}zn=!0,R.setSidebarCollapsed(o.sidebarCollapsed),o.sidebarVisible&&Zg(!0),(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!y.ok)return;let v=await y.json();if(typeof v.pendingAgentSwap=="string")R.setCompactionIndicator(`switching to ${v.pendingAgentSwap}...`);else{let N=v.compactionState?.status;N==="requested"||N==="running"?R.setCompactionIndicator("compacting..."):(N==="swap_pending"||N==="swap_deferred")&&R.setCompactionIndicator("compaction queued (waiting for idle)")}if(!Sf||v.shouldCompact!==!0)return;let C=v.currentUsage?.used,O=v.currentUsage?.size,T=typeof C=="number"&&typeof O=="number"&&O>0?`This session is using ${eo(C)} of its ${eo(O)} token context window.`:`This session has ~${sA(v.approxTokens??0)} tokens of history above the compaction watermark.`;Z=!0,R.setCompactionPrompt({message:T,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let y=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!y.ok)return;let v=await y.json();if(Ae&&Re===null&&Ne===null&&typeof v.updatedAt=="string"){let C=Date.parse(v.updatedAt);Number.isFinite(C)&&(Re=C,R.setSidebarSnapshot({lastTurnEndedAt:Re}))}v.forkSynthesisState==="running"?(R.setSynthesisIndicator("synthesizing context\u2026"),ol()):v.forkSynthesisState==="failed"&&(R.setSynthesisIndicator("\u26A0 synthesis failed"),R.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Hr!==void 0&&W>0?(Ne=Hr,R.setBanner({status:"busy",elapsedMs:Date.now()-Hr}),de===null&&(de=mr()),Te===null&&AS(Hr),Te=Hr,sr()):Hr===void 0&&W>0&&Je(-W),gn(od??null,ao===void 0?void 0:pS(ao)),Ge=!0;let cO=()=>{if(Ye){let y=Ye.resolve;Ye=null,R.setPermissionPrompt(null),y({outcome:{outcome:"cancelled"}})}Xr(),Zr()},jS=()=>{Te!==null&&(X=Date.now(),$e="reconnect-recovery-failed",sr(),Ug(),Gt.clear(),Cs.clear(),L.length=0,Te=null,X=null,$e=null)};return g=y=>{ge({src:"reconnect",step:"disconnect",message:y?.message}),R.setBanner({status:"disconnected",elapsedMs:void 0})},h=async y=>{let v=y?.skipInitialize===!0;if(ge({src:"reconnect",step:"begin",sessionId:me,skipInitialize:v}),t.isLocal)try{let ie=await rn(await He());(ie.baseUrl!==t.baseUrl||ie.wsUrl!==t.wsUrl||ie.token!==t.token)&&(ge({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:ie.baseUrl}),t.baseUrl=ie.baseUrl,t.wsUrl=ie.wsUrl,t.display=ie.display,t.token=ie.token)}catch(ie){ge({src:"reconnect",step:"target-refresh-failed",message:ie instanceof Error?ie.message:String(ie)})}cO();let C={jsonrpc:"2.0",id:`tui-reinit-${gS()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Ue}}};if(!v){ge({src:"reconnect",step:"initialize-send"});try{await w.request(C),ge({src:"reconnect",step:"initialize-ok"})}catch(ie){ge({src:"reconnect",step:"initialize-fail",message:ie.message})}}let O=Lr!==void 0||Nr!==void 0,T={jsonrpc:"2.0",id:`tui-reattach-${gS()}`,method:"session/attach",params:{sessionId:me,historyPolicy:O?"after_message":"none",...O&&Lr!==void 0?{afterMessageId:Lr}:{},...O&&Nr!==void 0?{afterSeq:Nr}:{},clientInfo:{name:"hydra-acp-tui",version:Ue},...(()=>{let ie={};return _i!==void 0&&(ie.resume={upstreamSessionId:_i,agentId:It,cwd:tt}),e.tui.toolContent==="references"&&(ie.toolContent="references"),Object.keys(ie).length>0?{_meta:{[ut]:ie}}:{}})()}};Oo=[];let N,H,te;ge({src:"reconnect",step:"attach-send",useAfterMessage:O,lastSeenMessageId:Lr,lastSeenSeq:Nr});try{let ie=await w.request(T);if(ge({src:"reconnect",step:"attach-resp",hasError:!!ie.error}),ie.error)throw new Error(ie.error.message);te=N_(ie.result),N=te.appliedPolicy,te.clientId!==void 0&&(Br=te.clientId)}catch(ie){H=ie,ge({src:"reconnect",step:"attach-fail",message:H.message})}let le=Oo??[];if(Oo=null,H)jS(),R.appendLines([{prefix:" ",body:`reattach failed: ${H.message}`,bodyStyle:"tool-status-fail"}]);else if(O&&N!=="after_message")jS(),R.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{le.length>0&&y?.beforeReplay?.(),x=!0;try{for(let ie of le)sl(ie)}finally{x=!1}}if(H||so(),te){let ie=H_({daemonTurnStartedAt:te.turnStartedAt,pendingTurns:W});ie.pendingTurnsDelta!==0&&Je(ie.pendingTurnsDelta),ie.banner==="busy"&&ie.busySince!==void 0?(Ne=ie.busySince,R.setBanner({status:"busy",elapsedMs:Date.now()-ie.busySince}),de===null&&(de=mr())):R.setBanner({status:"ready",elapsedMs:void 0}),te.armedTasks!==void 0&&gn(te.armedTasks>0?te.armedSince??null:null,te.armedTaskList===void 0?void 0:pS(te.armedTaskList))}else R.setBanner({status:W>0?"busy":"ready",elapsedMs:W>0?0:void 0});ge({src:"reconnect",step:"end"})},b.onClose(y=>{y&&B(n,"notice-error",`
|
|
303
303
|
connection lost: ${y.message}
|
|
304
|
-
`),xd(y?1:0)}),process.on("SIGINT",Mf),Cg.length>0&&(R.appendLines(Cg.map(y=>({prefix:" ",body:`theme: ${y}`,bodyStyle:"notice-error"}))),Cg=[]),hf.length>0&&(R.notify(hf.join(" \xB7 "),1e4),hf=[]),d.sessionId==="__new__"&&(r.initialPrompt||r.initialAttachments&&r.initialAttachments.length>0)&&jo(r.initialPrompt??"",r.initialAttachments??[]),await Di}async function y$(n,e,t,r,s,o){let i=r.cwd??process.cwd();if(r.sessionId){let d={sessionId:r.sessionId,agentId:r.agentId??"",cwd:i};r.resumeHint!==void 0&&(d.resumeHint=r.resumeHint),r.resolved!==void 0&&(d.resolved=r.resolved);let c=qa(r.resolved);return c!==void 0&&(d.remote=c),r.jumpToRecordedAt!==void 0&&(d.jumpToRecordedAt=r.jumpToRecordedAt),d}if(r.forceNew)return await b$(n,t,r,o)!=="ok"?null:w$(r,i,e);if(r.resume){let d=MM();if(d){let f=(await
|
|
305
|
-
`),null)}let a=await
|
|
304
|
+
`),xd(y?1:0)}),process.on("SIGINT",Mf),Cg.length>0&&(R.appendLines(Cg.map(y=>({prefix:" ",body:`theme: ${y}`,bodyStyle:"notice-error"}))),Cg=[]),hf.length>0&&(R.notify(hf.join(" \xB7 "),1e4),hf=[]),d.sessionId==="__new__"&&(r.initialPrompt||r.initialAttachments&&r.initialAttachments.length>0)&&jo(r.initialPrompt??"",r.initialAttachments??[]),await Di}async function y$(n,e,t,r,s,o){let i=r.cwd??process.cwd();if(r.sessionId){let d={sessionId:r.sessionId,agentId:r.agentId??"",cwd:i};r.resumeHint!==void 0&&(d.resumeHint=r.resumeHint),r.resolved!==void 0&&(d.resolved=r.resolved);let c=qa(r.resolved);return c!==void 0&&(d.remote=c),r.jumpToRecordedAt!==void 0&&(d.jumpToRecordedAt=r.jumpToRecordedAt),d}if(r.forceNew)return await b$(n,t,r,o)!=="ok"?null:w$(r,i,e);if(r.resume){let d=MM();if(d){let f=(await Gs(t,{all:!0,includeNonInteractive:!0})).find(p=>p.sessionId===d);if(f)return{sessionId:f.sessionId,agentId:f.agentId??"",cwd:f.cwd??i,resolved:f}}let c=await Gs(t,{cwd:i,all:!0}),l=Yh(c,i);return l?{sessionId:l.sessionId,agentId:l.agentId??"",cwd:i,resolved:l}:(B(n,"cli-warn",`No sessions found for ${i}.
|
|
305
|
+
`),null)}let a=await yo();for(;;){let d=await Gs(t,{includeNonInteractive:!0}),c=[];try{c=await Aa(t)}catch{}let l=I=>ff({cwd:I,config:a,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},...r.agentId!==void 0?{fallbackAgentId:r.agentId}:{},availableAgents:c}),u=I=>ff({cwd:I,config:a,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},availableAgents:c}),{agentId:f,model:p}=await l(i),m=await nS(n,{cwd:i,sessions:d,config:e,target:t,prefs:s,...r.pickerSelect!==void 0?{currentSessionId:r.pickerSelect}:{},...f?{composerAgentId:f}:{},...p?{composerModel:p}:{},...c.length>0?{availableAgents:c}:{},onComposerAgentChange:(I,x)=>{mf(o,I,x)},onCwdChange:u,...r.initialPrompt!==void 0?{initialPrompt:r.initialPrompt}:{},...r.initialAttachments&&r.initialAttachments.length>0?{initialAttachments:r.initialAttachments}:{}});if(m.kind==="abort"||m.kind==="exit")return null;if(m.kind==="new"){m.agentId!==void 0&&(r.agentId=m.agentId,m.agentExplicit&&mf(o,m.agentId,m.model)),m.model!==void 0&&(r.model=m.model),m.prompt!==void 0&&(r.initialPrompt=m.prompt),m.attachments&&m.attachments.length>0&&(r.initialAttachments=m.attachments),m.cwd!==void 0&&(i=m.cwd,r.cwd=m.cwd);let I=m.installStatus,x=await b$(n,t,r,o,()=>{I&&(I.finalize(),I=void 0)});if(x==="cancel")return I&&I.finalize(),null;if(x==="back"){I&&I.finalize();continue}let A=w$(r,i,e);return I&&(A.installStatus=I),A}if(m.kind==="fork"){let I=await P$(n,t,m,d);if(I.kind==="cancel")return null;if(I.kind==="back")continue;return I.ctx}r.readonly=m.readonly===!0;let h=m.installStatus,g=()=>{h&&(h.finalize(),h=void 0)},w=d.find(I=>I.sessionId===m.sessionId);if(w!==void 0&&!!w.importedFromMachine&&!w.remote&&!w.upstreamSessionId&&!r.readonly){g();let I=await T$(n,t,w,m,r);if(I.kind==="cancel")return null;if(I.kind==="back")continue;return I.ctx}if(t.isLocal&&w&&!w.importedFromMachine&&!w.remote&&!r.readonly&&!(await Ju(w.cwd)).ok){g();let x=await Ja(n,w,{defaultCwd:mt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(x.kind==="cancel")return null;if(x.kind==="back")continue;let A=m.agentId??w.agentId??"",_={sessionId:m.sessionId,agentId:A,cwd:x.path,resumeHint:{agentId:A,cwd:x.path,upstreamSessionId:""}};return m.jumpToRecordedAt!==void 0&&(_.jumpToRecordedAt=m.jumpToRecordedAt),_}let k={sessionId:m.sessionId,agentId:m.agentId??"",cwd:i};h&&(k.installStatus=h),w!==void 0&&(k.resolved=w);let S=qa(w);return S!==void 0&&(k.remote=S),m.jumpToRecordedAt!==void 0&&(k.jumpToRecordedAt=m.jumpToRecordedAt),k}}async function T$(n,e,t,r,s){for(;;){let o=await u_(n,t);if(o==="cancel")return{kind:"cancel"};if(o==="back")return{kind:"back"};if(o==="view"){s.readonly=!0;let c=r.agentId??t.agentId??"",l={sessionId:r.sessionId,agentId:c,cwd:t.cwd},u=qa(t);return u!==void 0&&(l.remote=u),r.jumpToRecordedAt!==void 0&&(l.jumpToRecordedAt=r.jumpToRecordedAt),{kind:"ctx",ctx:l}}let i=await E$(n,e,r.agentId??t.agentId??"");if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let a=await Ja(n,t);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let d=i.agentId;return{kind:"ctx",ctx:{sessionId:r.sessionId,agentId:d,cwd:a.path,resumeHint:{agentId:d,cwd:a.path,upstreamSessionId:""}}}}}async function E$(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let r;try{r=await Aa(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(r.length===0||r.some(o=>o.id===t))return{kind:"ok",agentId:t,changed:!1};let s=await Yu(n,r,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 s.kind==="cancel"?{kind:"cancel"}:s.kind==="back"?{kind:"back"}:{kind:"ok",agentId:s.agentId,changed:!0}}async function P$(n,e,t,r){let s=r.find(u=>u.sessionId===t.sourceSessionId),o=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,i=t.sourceCwd,a=await E$(n,e,t.sourceAgentId??s?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let d=a.changed?a.agentId:void 0;if(o){if(!s)return{kind:"back"};let u=await Ja(n,s);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};i=u.path}let c=d??t.sourceAgentId??"",l;try{l=await Vh(e,t.sourceSessionId,{...o?{cwd:i}:{},...d?{agentId:d}:{}})}catch(u){return B(n,"notice-error",`
|
|
306
306
|
fork failed: ${u.message}
|
|
307
|
-
`),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:i,isFreshFork:!0,...o?{resumeHint:{agentId:c,cwd:i,upstreamSessionId:""}}:{}}}}function w$(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}function mf(n,e,t){if(n.lastChosenAgent=e,t===void 0){delete n.lastChosenModel;return}n.lastChosenModel=t}async function b$(n,e,t,r,s){if(t.agentId||await yy())return"ok";let o;try{o=await Aa(e)}catch{return"ok"}if(o.length===0)return"ok";s&&s();let i=await He(),a=r.lastChosenAgent??i.defaultAgent,d=await Yu(n,o,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";t.agentId=d.agentId;let c=o.find(l=>l.id===d.agentId);if(mf(r,d.agentId,xr(i.sessionDefaults,{id:d.agentId,extendsChain:c?.extendsChain})?.value.model),d.persist)try{await Jo(d.agentId)}catch{}return"ok"}function U4(n,e){ge({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Cg,hf,Rg,Qa,Fr,k$,v$,S$,x$,yS,m$,M4,$4,g$,D4,M$=q(()=>{"use strict";
|
|
307
|
+
`),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:i,isFreshFork:!0,...o?{resumeHint:{agentId:c,cwd:i,upstreamSessionId:""}}:{}}}}function w$(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}function mf(n,e,t){if(n.lastChosenAgent=e,t===void 0){delete n.lastChosenModel;return}n.lastChosenModel=t}async function b$(n,e,t,r,s){if(t.agentId||await yy())return"ok";let o;try{o=await Aa(e)}catch{return"ok"}if(o.length===0)return"ok";s&&s();let i=await He(),a=r.lastChosenAgent??i.defaultAgent,d=await Yu(n,o,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";t.agentId=d.agentId;let c=o.find(l=>l.id===d.agentId);if(mf(r,d.agentId,xr(i.sessionDefaults,{id:d.agentId,extendsChain:c?.extendsChain})?.value.model),d.persist)try{await Jo(d.agentId)}catch{}return"ok"}function U4(n,e){ge({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Cg,hf,Rg,Qa,Fr,k$,v$,S$,x$,yS,m$,M4,$4,g$,D4,M$=q(()=>{"use strict";ko();fn();xk();rt();jk();wo();Ra();Rc();Wd();xP();ir();Gl();ke();Os();Yp();na();dr();Cm();Ak();rh();Tu();RP();PP();_P();$P();C_();Zv();gm();Yv();Vv();Vk();A_();Sk();E_();Gv();Sb();Xm();M_();cv();Hm();O_();rS();ng();vv();zm();nv();Um();qm();Xv();Av();Wa();Ku();xv();L_();hg();Qv();U_();Io();To();Tn();Yd();e$();aS();sa();Fa();_v();Pv();n$();o$();fv();a$();f$();Cg=[],hf=[],Rg=[],Qa="terminal",v$=null,x$=null;yS="dismiss";m$=12e4,M4=12e3;$4=[["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"],["Alt+PgUp / Alt+PgDn","jump to previous / next prompt"],["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 $HYDRA_EDITOR/$VISUAL/$EDITOR \u2014 a $EDITOR takes over the terminal until you quit it)"],["Double-click bar","cwd opens \xB7 title renames \xB7 agent/model/mode pick \xB7 else copy"],["Click in a modal","row picks / cycles it \xB7 hint words act \xB7 wheel walks the list"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X ^E","edit prompt in $HYDRA_EDITOR/$VISUAL/$EDITOR"],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"]];g$=!1;D4=2});var _$={};Ji(_$,{runTui:()=>A$});var $$=q(()=>{"use strict";M$()});import{readFileSync as W4}from"fs";import{fileURLToPath as j4}from"url";import{dirname as q4,resolve as z4}from"path";var qS=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","files","fold","follow","force","foreground","help","include-cat","info","inactive","json","new","no-color","no-dangerously-skip-permissions","no-from-note","no-pager","no-terminal-host-launcher","no-wait","tools","raw","reattach","readonly","remove","replace","rotate-token","terminal-host-launcher","verbose","version","workspace"]),uO=new Set(["agent","args","columns","command","cwd","dir","drip-speed","env","extends","from","from-label","from-session","host","jump-to-recorded-at","last","message","into","model","name","out","prompt","session","since","stream-bytes","stream-threshold","tail","terminal-host","timeout","to"]);function zS(n){for(let e of Object.keys(n))if(!qS.has(e)&&!uO.has(e))return e}function ey(n){let e=[],t={},r=0;for(;r<n.length;){let s=n[r];if(s===void 0)break;if(s.startsWith("--")){let o=s.indexOf("=");if(o!==-1){let d=s.slice(2,o);t[d]=s.slice(o+1),r+=1;continue}let i=s.slice(2);if(qS.has(i)){t[i]=!0,r+=1;continue}let a=n[r+1];if(a!==void 0&&!a.startsWith("--")){t[i]=a,r+=2;continue}t[i]=!0,r+=1;continue}e.push(s),r+=1}return{positional:e,flags:t}}function fO(n,e){let t=n[e];if(typeof t=="string")return t}function Ed(n,e){return n[e]===!0||n[e]==="true"}var pO="HYDRA_ACP_";function hO(n){return pO+n.toUpperCase().replace(/-/g,"_")}function dt(n,e){let t=fO(n,e);return t!==void 0?t:process.env[hO(e)]}rt();wo();async function kx(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 o=Ml(t);return{target:await wx(o,{allowPrompt:e.allowPrompt}),sessionId:o.sessionId,fromUrl:!0}}let r=await He();return{target:await rn(r),sessionId:t,fromUrl:!1}}function _y(n){let e=n.session;if(typeof e=="string"&&e.length>0)return e;let t=process.env.HYDRA_ACP_TARGET_SESSION;if(typeof t=="string"&&t.length>0)return t}na();ke();rt();go();import*as Ix from"fs/promises";vr();async function Cx(n){if(await Ix.mkdir(D.home(),{recursive:!0}),await Ud(),!await _d()){let t=Md();await Yi(t),process.stdout.write(`Initialized ${D.authToken()}
|
|
308
308
|
Service token: ${t}
|
|
309
309
|
`);return}if(Ed(n,"rotate-token")){let t=Md();try{let r=await Pe("/v1/auth/rotate-token",{method:"POST",body:{token:t},rethrowNetworkError:!0});r.ok||(process.stderr.write(`Daemon rejected the token rotation (HTTP ${r.status}). Not writing the new token to disk \u2014 that would leave it out of sync with what the running daemon still accepts.
|
|
310
310
|
`),process.exit(1)),await Yi(t),process.stdout.write(`Rotated token in ${D.authToken()}
|
|
@@ -315,10 +315,10 @@ New token: ${t}
|
|
|
315
315
|
Couldn't reach the daemon (${r.message}) \u2014 it'll pick up the new token next time it starts.
|
|
316
316
|
`)}return}process.stdout.write(`Service token already exists at ${D.authToken()}.
|
|
317
317
|
`),process.stdout.write(`Pass --rotate-token to generate a new service token.
|
|
318
|
-
`)}Tn();sa();ke();jd();rt();
|
|
318
|
+
`)}Tn();sa();ke();jd();rt();go();import{setTimeout as mU}from"timers/promises";import*as wT from"fs";import*as Ks from"fs/promises";import*as bT from"net";import*as $c from"path";import*as kT from"tls";import QH from"fastify";import XH from"@fastify/websocket";var oI="acp.v1";function iI(n,e){return n.has(oI)?oI:!1}rt();nc();import gT from"pino";import ZH from"pino-roll";ke();import*as En from"fs/promises";import{createHash as KF}from"crypto";import{gzip as GF,gunzip as JF}from"zlib";import{promisify as cI}from"util";var lI=cI(GF),VF=cI(JF),uI=/^[A-Za-z0-9_-]+$/,YF=/^[a-f0-9]{64}$/,ew=!0;function fI(n){ew=n}function up(n,e){return uI.test(n)?e===void 0||YF.test(e):!1}function fp(n,e){return`${D.toolBlobFile(n,e)}.gz`}async function tw(n,e){if(!up(n))return null;let t=KF("sha256").update(e,"utf8").digest("hex"),r=fp(n,t),s=D.toolBlobFile(n,t);for(let a of[r,s])try{return await En.access(a),t}catch{}await En.mkdir(D.toolsDir(n),{recursive:!0});let o=ew?r:s,i=ew?await lI(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await En.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function Wl(n,e){if(!up(n,e))return null;try{let t=await En.readFile(fp(n,e));return(await VF(t)).toString("utf8")}catch{}try{return await En.readFile(D.toolBlobFile(n,e),"utf8")}catch{return null}}async function pI(n,e){if(!up(n,e))return null;try{return await En.readFile(fp(n,e))}catch{}try{let t=await En.readFile(D.toolBlobFile(n,e));return await lI(t)}catch{return null}}async function hI(n,e,t){if(!up(n,e))return;let r=fp(n,e);try{await En.access(r);return}catch{}await En.mkdir(D.toolsDir(n),{recursive:!0}),await En.writeFile(r,t,{mode:384,flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s})}async function mI(n){uI.test(n)&&await En.rm(D.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}Os();import{spawn as $L,spawnSync as OL}from"child_process";import*as vp from"fs";import*as QI from"path";fn();function kp(n,e){let t="",r=[],s=[],o=!1,i=a=>{if(!o){o=!0;for(let d of s)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
|
|
319
319
|
`);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 r)u(l)}catch(l){for(let u of r)u({jsonrpc:"2.0",id:null,error:{code:G.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}d=t.indexOf(`
|
|
320
320
|
`)}}),n.on("end",()=>i()),n.on("error",a=>i(a)),e.on("error",a=>i(a)),{async send(a){if(o)throw new Error("stream is closed");let d=JSON.stringify(a)+`
|
|
321
|
-
`;await new Promise((c,l)=>{e.write(d,u=>{if(u){l(u);return}c()})})},onMessage(a){r.push(a)},onClose(a){s.push(a)},async close(){e.end(),i()}}}
|
|
321
|
+
`;await new Promise((c,l)=>{e.write(d,u=>{if(u){l(u);return}c()})})},onMessage(a){r.push(a)},onClose(a){s.push(a)},async close(){e.end(),i()}}}ko();ke();nc();pp();var FL=4096,ni=class n{agentId;version;installId;cwd;connection;authMethods;steeringSupported;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.installId=e.plan.installId??e.agentId,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??FL,this.killEscalationMs=e.killEscalationMs??LL,this.logger=e.logger,this.fileLog=NL(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()} ---
|
|
322
322
|
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let r=kp(t.stdout,t.stdin);this.connection=new pn(r),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",s=>{if(this.stderrTail=(this.stderrTail+s).slice(-this.stderrTailBytes),this.writeLog(s),this.logger)for(let o of s.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${s}`)}),t.on("error",s=>{let o=this.formatFailure(s.message);this.writeLog(`--- spawn error: ${s.message} time=${new Date().toISOString()} ---
|
|
323
323
|
`),this.connection.fail(new Error(o))}),t.on("exit",(s,o)=>{if(this.exited=!0,this.writeLog(`--- exit code=${s} signal=${o} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
|
|
324
324
|
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${s} signal=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${s} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${s} signal=${o}`)}for(let i of this.exitHandlers)i(s,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
|
|
@@ -330,8 +330,8 @@ stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){l
|
|
|
330
330
|
`).filter(a=>a.trim().length>0).length:0}}async rematerialize(e){let t=e.vcs?.branch;if(t===void 0)return{ok:!1,reason:"workspace has no recorded branch to restore from"};let r=this.refRoot(e);if(!await nR(r))return{ok:!1,reason:`source repository ${r} no longer exists`};let s=await be(["rev-parse","--verify","--quiet",`refs/heads/${t}`],r,Ke);if(!s.ok||s.stdout.trim().length===0)return{ok:!1,reason:`branch ${t} no longer exists in ${r}`};await be(["worktree","unlock",e.path],r,Ke),await be(["worktree","prune"],r,Ke);let o=await be(["worktree","add",e.path,t],r,Sn);return o.ok?{ok:!0,workspace:{...e,line:t,vcs:{...e.vcs??{},kind:"git",branch:t,repoRoot:r}}}:{ok:!1,reason:`could not restore worktree: ${o.stderr.trim()||"unknown error"}`}}async createWorkspace(e){let t=bt.resolve(e.sourceCwd),r=await be(["rev-parse","--show-toplevel"],t,Ke);if(!r.ok)return{ok:!1,reason:`${t} is not a git repository (or git is unavailable)`};let s=ru(r.stdout.trim());if(s.length===0)return{ok:!1,reason:`could not resolve the repository root for ${t}`};let o=await be(["rev-parse","HEAD"],s,Ke);if(!o.ok)return{ok:!1,reason:`${s} has no commits yet, so there is nothing to branch from`};let i=e.from??o.stdout.trim(),a=Np(e.label),d=kc(t);try{await ss.mkdir(d,{recursive:!0})}catch(p){return{ok:!1,reason:`could not create workspace root: ${String(p)}`}}let c=await Lp(a,async p=>await ss.access(bt.join(d,p)).then(()=>!0).catch(()=>!1)?!1:!(await be(["rev-parse","--verify","--quiet",`refs/heads/${Xw}/${p}`],s,Ke)).ok);if(c===void 0)return{ok:!1,reason:`no free name available for "${a}"`};let l=bt.join(d,c),u=`${Xw}/${c}`,f=await be(["worktree","add","--no-track","-b",u,l,i],s,Sn);return f.ok?{ok:!0,workspace:{path:l,sourceCwd:t,label:c,provider:this.kind,snapshot:i,line:u,vcs:{kind:"git",branch:u,base:i,repoRoot:s}}}:{ok:!1,reason:`git worktree add failed: ${f.stderr.trim()||"unknown error"}`}}async removeWorkspace(e,t){if(!t.force){let o=await this.status(e);if(!o.clean)throw new Error(`workspace ${e.path} has ${o.changedPaths.length} changed path(s)${o.hasRecordedWork?" and unintegrated recorded work":""}; pass force to remove`)}let r=this.refRoot(e);await this.unlock(e).catch(()=>{});let s=await be(["worktree","remove","--force",e.path],r,Sn);t.discardLine===!0&&e.vcs?.branch!==void 0&&await be(["branch","-D",e.vcs.branch],r,Ke),s.ok||(await ss.rm(e.path,{recursive:!0,force:!0}),await be(["worktree","prune"],r,Ke))}async listWorkspaces(e){let t=bt.resolve(e),r=await be(["rev-parse","--show-toplevel"],t,Ke);if(!r.ok)return[];let s=ru(r.stdout.trim()),o=await be(["worktree","list","--porcelain"],s,Ke);if(!o.ok)return[];let i=kc(t),a=await kN(i),d=[];for(let c of ZC(o.stdout)){let l=ru(c.path),u=bt.dirname(l);if(u!==i&&u!==a)continue;let f=bt.join(i,bt.basename(l)),p={kind:"git",repoRoot:s},m=eR(c.branch);m!==void 0&&(p.branch=m),c.head!==void 0&&(p.head=c.head),c.lockedReason!==void 0&&(p.locked=c.lockedReason);let h=c.lockedReason?.startsWith(tR)===!0;d.push({path:f,sourceCwd:t,label:bt.basename(f),...h?{heldByUs:!0}:{},provider:this.kind,...m!==void 0?{line:m}:{},vcs:p})}return d}async status(e){let t=await be(["status","--porcelain","--untracked-files=all"],e.path,Ke);if(!t.ok)return{clean:!1,changedPaths:[],hasRecordedWork:!1};let r=eb(t.stdout),s=r.map(a=>a.path),o=r.some(({code:a})=>a!=="??"&&a[0]!==" "&&a[0]!=="?"),i=!1;if(e.snapshot!==void 0){let a=await be(["rev-list","--count",`${e.snapshot}..HEAD`],e.path,Ke);a.ok&&(i=Number.parseInt(a.stdout.trim(),10)>0)}return{clean:s.length===0&&!i,changedPaths:s,hasRecordedWork:i,hasStagedWork:o}}async lock(e,t){let r=this.refRoot(e);await be(["worktree","lock","--reason",`${tR}${t}`,e.path],r,Ke)}async unlock(e){let t=this.refRoot(e);await be(["worktree","unlock",e.path],t,Ke)}async environmentNotes(e){let t=[],r=e.vcs?.branch;return t.push(`This directory is a git worktree of ${e.sourceCwd}${r!==void 0?`, on branch ${r}`:""}. Do not read or write ${e.sourceCwd} directly; paths under it refer to the corresponding file here. Prefer repo-relative paths, which are identical in both.`),t.push("`.git` here is a file, not a directory. That is normal for a worktree and does not need repairing."),await ss.access(bt.join(e.path,".gitmodules")).then(()=>!0).catch(()=>!1)&&t.push("Submodules here are initialized and checked out at the commits this tree records, which means each sits on a detached HEAD. That is normal and does not need repairing. Never re-add a submodule's contents as ordinary tracked files in the superproject: that silently corrupts the integration back to the source branch."),t}async statusReport(e){let t=[],r=await be(["status","--porcelain","--untracked-files=all"],e.path,Ke);if(r.ok){let s=eb(r.stdout);if(s.length===0)t.push("no uncommitted changes");else{let o=0,i=0,a=0;for(let{code:c}of s){if(c==="??"){a+=1;continue}c[0]!==" "&&c[0]!=="?"&&(o+=1),c[1]!==" "&&c[1]!=="?"&&(i+=1)}let d=[];o>0&&d.push(`${o} staged`),i>0&&d.push(`${i} unstaged`),a>0&&d.push(`${a} untracked`),t.push(`${d.join(", ")}:`),t.push(...fa(s.map(c=>` ${c.code} ${c.path}`)))}}return t.push(...await this.syncLines(e)),t}async syncLines(e){if(e.vcs?.branch===void 0)return[];let[t,r]=await Promise.all([be(["rev-parse","HEAD"],e.sourceCwd,Ke),be(["rev-parse","HEAD"],e.path,Ke)]),s=t.stdout.trim(),o=r.stdout.trim();if(!t.ok||!r.ok||s.length===0||o.length===0)return[];let i=V(e.sourceCwd);if(s===o)return[`in sync with ${i}`];let a=await be(["rev-list","--left-right","--count",`${s}...${o}`],e.path,Ke),d=a.stdout.trim().split(/\s+/).map(f=>Number.parseInt(f,10)),c=d[0],l=d[1];if(!a.ok||c===void 0||l===void 0||!Number.isFinite(c)||!Number.isFinite(l))return[];let u=[];return c>0&&u.push(`${c} commit(s) behind ${i}. \`/hydra workspace sync\` brings them in; landing is fast-forward-only, so this also unblocks \`stop\`.`),l>0&&u.push(`${l} commit(s) recorded here and not landed yet.`),u}async captureWorkingState(e,t){let r=bt.join(oR.tmpdir(),`hydra-index-${process.pid}-${bN(6).toString("hex")}`),s={GIT_INDEX_FILE:r};try{let o=await be(["rev-parse","--verify","HEAD"],e,Ke),i=o.ok&&o.stdout.trim().length>0;if(i){let u=await be(["read-tree","HEAD"],e,Sn,s);if(!u.ok)throw new Error(`could not seed the snapshot index: ${u.stderr.trim()}`)}let a=await be(["add","-A"],e,Sn,s);if(!a.ok)throw new Error(`could not stage working state: ${a.stderr.trim()}`);let d=await be(["write-tree"],e,Sn,s);if(!d.ok||d.stdout.trim().length===0)throw new Error(`could not write tree: ${d.stderr.trim()}`);let c=["commit-tree",d.stdout.trim(),"-m",t];i&&c.push("-p",o.stdout.trim());let l=await be(c,e,Sn,s);if(!l.ok||l.stdout.trim().length===0)throw new Error(`could not create snapshot commit: ${l.stderr.trim()}`);return l.stdout.trim()}finally{await ss.rm(r,{force:!0}).catch(()=>{})}}async retainSnapshot(e,t,r){let s=this.refRoot(e);await be(["update-ref","--create-reflog",t,r],s,Ke)}async dropSnapshotRef(e,t){let r=this.refRoot(e);await be(["update-ref","-d",t],r,Ke)}async currentState(e){let t=await be(["rev-parse","HEAD"],e,Ke),r=t.stdout.trim();return t.ok&&r.length>0?r:void 0}async contentId(e,t){let r=await be(["rev-parse",`${t}^{tree}`],e,Ke),s=r.stdout.trim();return r.ok&&s.length>0?s:void 0}async currentLineName(e){let t=await be(["rev-parse","--abbrev-ref","HEAD"],e,Ke),r=t.stdout.trim();return t.ok&&r.length>0?r:void 0}async resolveRoot(e){let t=await be(["rev-parse","--show-toplevel"],e,Ke),r=ru(t.stdout.trim());return t.ok&&r.length>0?r:void 0}async resolveRetained(e,t){let r=await be(["rev-parse","--verify","--quiet",`${t}^{commit}`],this.refRoot(e),Ke),s=r.stdout.trim();return r.ok&&s.length>0?s:void 0}async contains(e,t){return(await be(["merge-base","--is-ancestor",t.state,t.within],e,Ke)).ok}async divergence(e,t,r){let s=await be(["rev-list","--left-right","--count",`${t}...${r}`],e,Ke);if(!s.ok)return;let o=s.stdout.trim().split(/\s+/).map(d=>Number.parseInt(d,10)),i=o[0],a=o[1];if(!(i===void 0||a===void 0||!Number.isFinite(i)||!Number.isFinite(a)))return{ahead:i,behind:a}}async changedPathsBetween(e,t,r){let s=await be(["diff","--name-only",t,r],e,Ke);return s.ok?s.stdout.split(`
|
|
331
331
|
`).map(o=>o.replace(/\r$/,"").trim()).filter(o=>o.length>0):[]}async captureDelta(e,t,r){let s=await be(["diff","--binary","--ignore-submodules=all",t,r],e,Sn);if(s.ok)return s.stdout}async applyDelta(e,t,r){if(t.trim().length===0)return{ok:!0,alreadyPresent:!0};let s=r?.stage===!0?["--index"]:[],o=await Zw(["apply",...s],e,t);if(o.ok)return{ok:!0};if(r?.tolerant!==!0)return{ok:!1,reason:o.stderr.trim()||"the change did not apply"};if((await Zw(["apply","--reverse","--check"],e,t)).ok)return{ok:!0,alreadyPresent:!0};let a=await Zw(["apply","--3way"],e,t);return a.ok?{ok:!0}:{ok:!1,reason:a.stderr.trim()||"the change overlaps what is already there"}}async resetTo(e,t,r){let s=await be(["reset","--hard",t],e,Sn);if(!s.ok)return{ok:!1,reason:s.stderr.trim()||"could not return to that state"};let o=await be(["clean",r?.purgeIgnored===!0?"-ffdx":"-fd"],e,Sn);if(!o.ok)return{ok:!1,reason:o.stderr.trim()||"returned to that state but could not remove extra files"};let i=await this.materializeNested({path:e,sourceCwd:e,label:"",provider:this.kind},{discardLocal:!0,...r?.purgeIgnored===!0?{purgeIgnored:!0}:{}});return i.ok?{ok:!0}:{ok:!1,reason:i.reason??"could not reset nested trees"}}async integrationInProgress(e){return(await be(["rev-parse","-q","--verify","MERGE_HEAD"],e,Ke)).ok}async abortIntegration(e){await be(["merge","--abort"],e,Sn)}async conflictedPaths(e){let t=await be(["diff","--name-only","--diff-filter=U"],e,Ke);return t.ok?t.stdout.split(`
|
|
332
332
|
`).map(r=>r.replace(/\r$/,"").trim()).filter(r=>r.length>0):[]}async record(e,t){let r=await be(["add","-A"],e.path,Sn);if(!r.ok)throw new Error(`could not stage ${e.path}: ${r.stderr.trim()||"unknown error"}`);let s=await this.status(e),o=await this.currentState(e.path);if(s.changedPaths.length===0){if(o===void 0)throw new Error(`could not read the state of ${e.path}`);return o}let i=await be(["commit","-m",t],e.path,Sn);if(!i.ok)throw new Error(`could not record ${e.path}: ${i.stderr.trim()||i.stdout.trim()||"unknown error"}`);let a=await this.currentState(e.path);if(a===void 0)throw new Error(`recorded ${e.path} but could not read the resulting state`);return a}async attributeOrphan(e){let t=await be(["rev-parse","--path-format=absolute","--git-common-dir"],e,Ke),r=ru(t.stdout.trim());if(!t.ok||r.length===0)return;let s=bt.dirname(r),o=await this.currentLineName(e);return{path:e,sourceCwd:s,label:bt.basename(e),provider:this.kind,...o!==void 0?{line:o}:{},vcs:{repoRoot:s,...o!==void 0?{branch:o}:{}}}}async discardLine(e,t){let r=this.refRoot(e),o=(await this.divergence(r,"HEAD",t))?.behind??0,i=await be(["branch","-D",t],r,Ke);return i.ok?{ok:!0,dropped:o}:{ok:!1,dropped:o,reason:i.stderr.trim()||"could not discard the line"}}async pruneStale(e){await be(["worktree","prune"],this.refRoot(e),Ke)}async changedPaths(){throw new rs(this.kind,"changedPaths")}async integrate(e){let{into:t,from:r}=e,s=await this.currentState(t);if(s===void 0)return{ok:!1,conflicts:[],declined:!0,reason:`cannot read the state of ${t}`};if(await this.contains(t,{state:r,within:s}))return{ok:!0,snapshot:s,alreadyUpToDate:!0};if(e.fastForwardOnly===!0&&!await this.contains(t,{state:s,within:r}))return{ok:!1,conflicts:[],declined:!0,reason:`${t} cannot simply advance to that state; it has moved on independently`};let o=e.fastForwardOnly===!0?["merge","--ff-only",r]:["merge","--no-edit","-m",e.message??"hydra: integrate",r],i=await be(o,t,Sn);if(i.ok){let c=await this.currentState(t);return c===void 0?{ok:!1,conflicts:[],reason:"integrated but could not read the resulting state"}:{ok:!0,snapshot:c}}let a=await this.conflictedPaths(t),d=await this.integrationInProgress(t);return a.length===0&&!d?{ok:!1,conflicts:[],declined:!0,reason:i.stderr.trim()||"the integration was refused"}:(e.onConflict==="abort"&&await this.abortIntegration(t),{ok:!1,conflicts:a})}async listNested(e){let t=await be(["submodule","status","--recursive"],e,Sn);if(!t.ok)return[];let r=[];for(let s of t.stdout.split(`
|
|
333
|
-
`)){let o=s.replace(/\r$/,"");if(o.trim().length===0||(o[0]??" ")==="-")continue;let a=o.slice(1),d=a.indexOf(" ");if(d<=0)continue;let c=a.slice(d+1).replace(/\s+\(.*\)\s*$/,"").trim();if(c.length===0||!vN(e,c))continue;let l=bt.join(e,c),[u,f,p]=await Promise.all([this.currentState(l),be(["rev-parse",`HEAD:${c}`],e,Ke),be(["status","--porcelain","--untracked-files=all"],l,Ke)]);if(u===void 0)continue;let m=f.ok?f.stdout.trim():"";r.push({relPath:c,actual:u,...m.length>0?{recorded:m}:{},changedPaths:p.ok?eb(p.stdout).map(h=>h.path):[]})}return r}async captureNested(e,t){let r=[];for(let s of t){if(!Vw(s))continue;if(s.changedPaths.length===0){r.push(s);continue}let o=bt.join(e,s.relPath),i=await this.captureWorkingState(o,"hydra: nested work carried into workspace").catch(()=>{});if(i===void 0){r.push(s);continue}let a=await this.captureDelta(o,s.actual,i);r.push(a===void 0?s:{...s,delta:a})}return r}async reproduceNested(e,t,r){let s=[],o=[];for(let i of r){let a=bt.join(e,i.relPath),d=bt.join(t,i.relPath),c=await this.alignNested(a,d,i.actual);if(c!==void 0){o.push({path:i.relPath,reason:c});continue}if(i.delta!==void 0){let l=await this.applyDelta(a,i.delta);if(!l.ok){o.push({path:i.relPath,reason:l.reason??"changes did not apply"});continue}}s.push(i.relPath)}return{applied:s,failed:o}}async integrateNested(e,t,r){let s=[],o=[],i=new Map(r.map(c=>[c.relPath,c])),a=await this.listNested(e),d=new Set([...a.map(c=>c.relPath),...i.keys()]);for(let c of[...d].sort()){let l=a.find(g=>g.relPath===c),u=i.get(c);if(l===void 0){o.push({path:c,reason:"not populated in the receiving tree"});continue}let f=l.recorded!==void 0&&l.recorded!==l.actual,p=u?.delta!==void 0;if(!f&&!p)continue;if(l.changedPaths.length>0){o.push({path:c,reason:`it has ${l.changedPaths.length} uncommitted change(s) of its own, and nothing can tell those apart from what was integrated`});continue}let m=bt.join(e,c),h=bt.join(t,c);if(f&&l.recorded!==void 0){let g=await this.alignNested(m,h,l.recorded);if(g!==void 0){o.push({path:c,reason:g});continue}}if(u?.delta!==void 0){let g=await this.applyDelta(m,u.delta);if(!g.ok){o.push({path:c,reason:g.reason??"the uncommitted changes there did not apply"});continue}}s.push(c)}return{applied:s,failed:o}}async alignNested(e,t,r){let s=await this.currentState(e);if(s===void 0)return"not populated here";if(s===r)return;if(!(await be(["cat-file","-e",`${r}^{commit}`],e,Ke)).ok&&!(await be(["fetch","--no-tags",t,r],e,Bp)).ok)return`could not transfer ${r.slice(0,8)} from the other copy`;if(!(await be(["checkout","--detach",r],e,Sn)).ok)return`could not move to ${r.slice(0,8)}`}};function vN(n,e){if(bt.isAbsolute(e))return!1;let t=bt.resolve(n),r=bt.resolve(t,e);return r!==t&&r.startsWith(t+bt.sep)}var SN=Up,iR=new Map([[Up,new Hp],[Qw,new Dp]]);function je(n){return iR.get(n??SN)}function aR(){return[...iR.keys()]}var Wp="refs/hydra";function Xn(n){let e=`${Wp}/workspaces/${n}`;return{autosave:`${e}/autosave`,start:`${e}/start`,baseline:`${e}/baseline`}}function su(n){return`${Wp}/landing/${n}`}function dR(n){return`${Wp}/sync/${n}`}function jp(n,e){return`${Wp}/retired/${n}-${e.slice(0,12)}`}function qp(n){let e=Xn(n);return[e.autosave,e.start,e.baseline]}async function ou(n){let{source:e,ws:t,startSnapshotRef:r,baselineRef:s,retainRef:o,provider:i}=n;if(i===void 0)throw new Error("no provider available to inspect the source tree");let a=await i.status({...t,path:e}).catch(()=>{}),d="";for(let u of[s,r]){if(u===void 0)continue;let f=await i.resolveRetained(t,u).catch(()=>{});if(f!==void 0){d=f;break}}let c=a===void 0||a.changedPaths.length>0;if(d.length===0){if(c)throw new Error(`${e} has uncommitted changes but this workspace has no start anchor, so its copy of your work cannot be told apart from edits you made since. Refusing rather than reporting a conflict that is not yours. Commit or stash the source, then retry.`);d=await i.currentState(e).catch(()=>{})??""}if(!c)return{clean:!0,base:d};if(i.capabilities().supports.captureWorkingState!==!0)throw new Error(`${e} has uncommitted changes and this provider cannot snapshot them, so they cannot be preserved across the landing. Commit or stash them first.`);let l=await i.captureWorkingState(e,"hydra: source state before landing").catch(()=>{});if(l===void 0)throw new Error(`could not snapshot the uncommitted changes in ${e}, so refusing to touch them`);return await i.retainSnapshot({...t,path:e},o,l),{clean:!1,snapshot:l,base:d,retainedRef:o}}async function vo(n){let{source:e,capture:t,provider:r}=n;if(t.clean||t.snapshot===void 0||r===void 0)return!0;let s=await r.captureDelta(e,t.base,t.snapshot).catch(()=>{});return s===void 0?!1:(await r.applyDelta(e,s,{tolerant:!0})).ok}async function ii(n){n.capture.retainedRef===void 0||n.provider===void 0||await n.provider.dropSnapshotRef({...n.ws,path:n.source},n.capture.retainedRef).catch(()=>{})}es();import{exec as xN}from"child_process";import*as
|
|
334
|
-
`)){let i=o.trim();i.length===0||i.startsWith("#")||i.startsWith("!")||i.includes("*")||i.includes("?")||t.add(i)}let s={};return t.size>0&&(s.carry=[...t]),typeof e.postCreate=="string"&&(s.postCreate=e.postCreate),typeof e.preRemove=="string"&&(s.preRemove=e.preRemove),typeof e.hookTimeoutSeconds=="number"&&(s.hookTimeoutSeconds=e.hookTimeoutSeconds),s}async function tb(n,e,t){let r=[],s=[],o=ar.resolve(n),i=ar.resolve(e);for(let a of t){let d=ar.resolve(o,a),c=ar.resolve(i,a);if(!d.startsWith(o+ar.sep)||!c.startsWith(i+ar.sep)){s.push(a);continue}if(await
|
|
333
|
+
`)){let o=s.replace(/\r$/,"");if(o.trim().length===0||(o[0]??" ")==="-")continue;let a=o.slice(1),d=a.indexOf(" ");if(d<=0)continue;let c=a.slice(d+1).replace(/\s+\(.*\)\s*$/,"").trim();if(c.length===0||!vN(e,c))continue;let l=bt.join(e,c),[u,f,p]=await Promise.all([this.currentState(l),be(["rev-parse",`HEAD:${c}`],e,Ke),be(["status","--porcelain","--untracked-files=all"],l,Ke)]);if(u===void 0)continue;let m=f.ok?f.stdout.trim():"";r.push({relPath:c,actual:u,...m.length>0?{recorded:m}:{},changedPaths:p.ok?eb(p.stdout).map(h=>h.path):[]})}return r}async captureNested(e,t){let r=[];for(let s of t){if(!Vw(s))continue;if(s.changedPaths.length===0){r.push(s);continue}let o=bt.join(e,s.relPath),i=await this.captureWorkingState(o,"hydra: nested work carried into workspace").catch(()=>{});if(i===void 0){r.push(s);continue}let a=await this.captureDelta(o,s.actual,i);r.push(a===void 0?s:{...s,delta:a})}return r}async reproduceNested(e,t,r){let s=[],o=[];for(let i of r){let a=bt.join(e,i.relPath),d=bt.join(t,i.relPath),c=await this.alignNested(a,d,i.actual);if(c!==void 0){o.push({path:i.relPath,reason:c});continue}if(i.delta!==void 0){let l=await this.applyDelta(a,i.delta);if(!l.ok){o.push({path:i.relPath,reason:l.reason??"changes did not apply"});continue}}s.push(i.relPath)}return{applied:s,failed:o}}async integrateNested(e,t,r){let s=[],o=[],i=new Map(r.map(c=>[c.relPath,c])),a=await this.listNested(e),d=new Set([...a.map(c=>c.relPath),...i.keys()]);for(let c of[...d].sort()){let l=a.find(g=>g.relPath===c),u=i.get(c);if(l===void 0){o.push({path:c,reason:"not populated in the receiving tree"});continue}let f=l.recorded!==void 0&&l.recorded!==l.actual,p=u?.delta!==void 0;if(!f&&!p)continue;if(l.changedPaths.length>0){o.push({path:c,reason:`it has ${l.changedPaths.length} uncommitted change(s) of its own, and nothing can tell those apart from what was integrated`});continue}let m=bt.join(e,c),h=bt.join(t,c);if(f&&l.recorded!==void 0){let g=await this.alignNested(m,h,l.recorded);if(g!==void 0){o.push({path:c,reason:g});continue}}if(u?.delta!==void 0){let g=await this.applyDelta(m,u.delta);if(!g.ok){o.push({path:c,reason:g.reason??"the uncommitted changes there did not apply"});continue}}s.push(c)}return{applied:s,failed:o}}async alignNested(e,t,r){let s=await this.currentState(e);if(s===void 0)return"not populated here";if(s===r)return;if(!(await be(["cat-file","-e",`${r}^{commit}`],e,Ke)).ok&&!(await be(["fetch","--no-tags",t,r],e,Bp)).ok)return`could not transfer ${r.slice(0,8)} from the other copy`;if(!(await be(["checkout","--detach",r],e,Sn)).ok)return`could not move to ${r.slice(0,8)}`}};function vN(n,e){if(bt.isAbsolute(e))return!1;let t=bt.resolve(n),r=bt.resolve(t,e);return r!==t&&r.startsWith(t+bt.sep)}var SN=Up,iR=new Map([[Up,new Hp],[Qw,new Dp]]);function je(n){return iR.get(n??SN)}function aR(){return[...iR.keys()]}var Wp="refs/hydra";function Xn(n){let e=`${Wp}/workspaces/${n}`;return{autosave:`${e}/autosave`,start:`${e}/start`,baseline:`${e}/baseline`}}function su(n){return`${Wp}/landing/${n}`}function dR(n){return`${Wp}/sync/${n}`}function jp(n,e){return`${Wp}/retired/${n}-${e.slice(0,12)}`}function qp(n){let e=Xn(n);return[e.autosave,e.start,e.baseline]}async function ou(n){let{source:e,ws:t,startSnapshotRef:r,baselineRef:s,retainRef:o,provider:i}=n;if(i===void 0)throw new Error("no provider available to inspect the source tree");let a=await i.status({...t,path:e}).catch(()=>{}),d="";for(let u of[s,r]){if(u===void 0)continue;let f=await i.resolveRetained(t,u).catch(()=>{});if(f!==void 0){d=f;break}}let c=a===void 0||a.changedPaths.length>0;if(d.length===0){if(c)throw new Error(`${e} has uncommitted changes but this workspace has no start anchor, so its copy of your work cannot be told apart from edits you made since. Refusing rather than reporting a conflict that is not yours. Commit or stash the source, then retry.`);d=await i.currentState(e).catch(()=>{})??""}if(!c)return{clean:!0,base:d};if(i.capabilities().supports.captureWorkingState!==!0)throw new Error(`${e} has uncommitted changes and this provider cannot snapshot them, so they cannot be preserved across the landing. Commit or stash them first.`);let l=await i.captureWorkingState(e,"hydra: source state before landing").catch(()=>{});if(l===void 0)throw new Error(`could not snapshot the uncommitted changes in ${e}, so refusing to touch them`);return await i.retainSnapshot({...t,path:e},o,l),{clean:!1,snapshot:l,base:d,retainedRef:o}}async function vo(n){let{source:e,capture:t,provider:r}=n;if(t.clean||t.snapshot===void 0||r===void 0)return!0;let s=await r.captureDelta(e,t.base,t.snapshot).catch(()=>{});return s===void 0?!1:(await r.applyDelta(e,s,{tolerant:!0})).ok}async function ii(n){n.capture.retainedRef===void 0||n.provider===void 0||await n.provider.dropSnapshotRef({...n.ws,path:n.source},n.capture.retainedRef).catch(()=>{})}es();import{exec as xN}from"child_process";import*as Ws from"fs/promises";import*as ar from"path";var IN=".hydra/worktree.json",CN=".worktreeinclude",RN=120;async function zp(n){let e=await jt(ar.join(n,IN))??{},t=new Set(Array.isArray(e.carry)?e.carry:[]),r=await Ws.readFile(ar.join(n,CN),"utf8").catch(()=>{});if(r!==void 0)for(let o of r.split(`
|
|
334
|
+
`)){let i=o.trim();i.length===0||i.startsWith("#")||i.startsWith("!")||i.includes("*")||i.includes("?")||t.add(i)}let s={};return t.size>0&&(s.carry=[...t]),typeof e.postCreate=="string"&&(s.postCreate=e.postCreate),typeof e.preRemove=="string"&&(s.preRemove=e.preRemove),typeof e.hookTimeoutSeconds=="number"&&(s.hookTimeoutSeconds=e.hookTimeoutSeconds),s}async function tb(n,e,t){let r=[],s=[],o=ar.resolve(n),i=ar.resolve(e);for(let a of t){let d=ar.resolve(o,a),c=ar.resolve(i,a);if(!d.startsWith(o+ar.sep)||!c.startsWith(i+ar.sep)){s.push(a);continue}if(await Ws.access(c).then(()=>!0).catch(()=>!1)){s.push(a);continue}let u=await Ws.stat(d).catch(()=>{});if(u===void 0){s.push(a);continue}try{await Ws.mkdir(ar.dirname(c),{recursive:!0}),await Ws.cp(d,c,{recursive:u.isDirectory(),dereference:!0}),r.push(a)}catch{s.push(a)}}return{copied:r,skipped:s}}async function Kp(n,e){let t=JSON.stringify({path:e.workspacePath,sourceCwd:e.sourceCwd,label:e.label,...e.sessionId!==void 0?{sessionId:e.sessionId}:{}}),r=(e.timeoutSeconds??RN)*1e3;return new Promise(s=>{let o=xN(n,{cwd:e.workspacePath,timeout:r,maxBuffer:8388608,windowsHide:!0,env:{...process.env,HYDRA_WORKSPACE_PATH:e.workspacePath,HYDRA_SOURCE_CWD:e.sourceCwd,HYDRA_WORKSPACE_LABEL:e.label,...e.sessionId!==void 0?{HYDRA_SESSION_ID:e.sessionId}:{}}},(i,a,d)=>{if(i){let c=(d||i.message||"").trim().slice(0,500);s({ok:!1,reason:c.length>0?c:"hook failed"});return}s({ok:!0})});o.stdin?.on("error",()=>{}),o.stdin?.end(t)})}ke();es();import*as So from"fs/promises";import{z as os}from"zod";var AN=os.object({version:os.literal(1),agentId:os.string(),upstreamSessionId:os.string(),sessionId:os.string().optional(),deletedAt:os.string(),upstreamUpdatedAt:os.string().optional(),cwd:os.string().optional(),title:os.string().optional(),reason:os.enum(["user","expired"]).optional(),interactive:os.boolean().optional()}),Gp=class{async add(e){let t={version:1,...e};await nn(D.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await So.access(D.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let r=D.tombstoneFile(e,t),s=await jt(r);if(s===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return AN.parse(s)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await So.unlink(D.tombstoneFile(e,t))}catch(r){if(r.code!=="ENOENT")throw r}try{await So.rmdir(D.tombstoneAgentDir(e))}catch(r){let s=r;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw r}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await So.readdir(D.tombstonesDir())}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[];for(let s of t){let o;try{o=decodeURIComponent(s)}catch{continue}r.push(...await this.listForAgent(o))}return r}async listForAgent(e){let t;try{t=await So.readdir(D.tombstoneAgentDir(e))}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[];for(let s of t){let o;try{o=decodeURIComponent(s)}catch{continue}let i=await this.read(e,o);i&&r.push(i)}return r}};function cR(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as vR from"fs/promises";import{customAlphabet as FN}from"nanoid";fn();dr();$p();Tp();Kl();var PN=12e4;async function uR(n,e,t){let r=n.timeoutMs??PN,s,o,i=!1;try{let a=(async()=>{s=ni.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let d=await s.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:Ue}}),c=await s.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,s.pid),n.modelId){let m=_N(c);if(m.size===0||m.has(n.modelId)){let h=s.connection;try{await si({request:(g,w)=>h.request(g,w),sessionId:l,modelId:n.modelId,verb:uc(c),logger:n.logger})}catch(g){n.logger?.warn(`synopsis: agent ${n.agentId} rejected model change to ${JSON.stringify(n.modelId)}: ${g.message}; continuing on default`)}}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let u=[];s.connection.onNotification("session/update",m=>{let h=MN(m);h.length>0&&u.push(h)}),await s.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=t(f);if(!p){let m=JSON.stringify(f.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${f.length} preview=${m})`);let h=f.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${f.length} chars): ${h}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((d,c)=>{o=setTimeout(()=>{i=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${r}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${r}ms`),d(void 0)},r),o.unref?.(),a.then(l=>{o&&clearTimeout(o),i||d(l)},l=>{o&&clearTimeout(o),i||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{o&&clearTimeout(o),s&&await s.kill().catch(()=>{})}}async function Vp(n){let e=gc(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",r=e.length>0?`${t}
|
|
335
335
|
|
|
336
336
|
${e}
|
|
337
337
|
|
|
@@ -353,7 +353,7 @@ ${Ww}`;return uR(n,r,VC)}function MN(n){if(!n||typeof n!="object")return"";let e
|
|
|
353
353
|
`)+`
|
|
354
354
|
`,s=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,s);let o=D.historyArchiveFile(e,s);await kt.mkdir(D.sessionDir(e),{recursive:!0}),await kt.appendFile(o,r,{encoding:"utf8",mode:384});let i=0;try{i=(await kt.stat(o)).size}catch{i=0}i>=this.archiveMaxBytes?(await this.sealArchive(e,s),this.nextArchiveIndex.set(e,s+1)):this.nextArchiveIndex.set(e,s),this.archiveLineCounts.delete(e)}async sealArchive(e,t){let r=D.historyArchiveFile(e,t),s;try{s=await kt.readFile(r)}catch(i){if(i.code==="ENOENT")return;throw i}let o=await VN(s);await kt.writeFile(r+".gz",o,{mode:384});try{await kt.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let r=await this.listArchiveIndices(e),s=r.length===0?0:r[r.length-1],o=s===0?1:s;if(s>0){let i=D.historyArchiveFile(e,s),a=i+".gz",d=!1;try{await kt.access(a),d=!0}catch{d=!1}if(d)o=s+1;else try{(await kt.stat(i)).size>=this.archiveMaxBytes&&(o=s+1)}catch{o=s}}return this.nextArchiveIndex.set(e,o),o}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let r=await this.listArchiveIndices(e),o=(r.includes(t)?r.length:r.length+1)-this.archiveTiers,i=0;for(;o>0&&i<r.length;){let a=r[i];a!==t&&(await this.unlinkArchive(e,a),o-=1),i+=1}}async unlinkArchive(e,t){let r=D.historyArchiveFile(e,t);for(let s of[r,r+".gz"])try{await kt.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await kt.readdir(D.sessionDir(e))}catch(s){if(s.code==="ENOENT")return[];throw s}let r=new Set;for(let s of t){let o=QN.exec(s);if(!o)continue;let i=Number.parseInt(o[1],10);Number.isFinite(i)&&i>0&&r.add(i)}return[...r].sort((s,o)=>s-o)}async listArchives(e){if(!is.test(e))return[];let t=await this.listArchiveIndices(e),r=[];for(let s of t){let o=D.historyArchiveFile(e,s),i=o+".gz",a=o;try{await kt.access(i),a=i}catch{a=o}r.push({index:s,path:a})}return r}async loadArchives(e){if(!is.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let r=await this.listArchives(e),s=[];for(let{path:o}of r){let i;try{if(o.endsWith(".gz")){let a=await kt.readFile(o);i=(await YN(a)).toString("utf8")}else i=await kt.readFile(o,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of i.split(`
|
|
355
355
|
`)){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"&&s.push({method:c.method,params:c.params,recordedAt:c.recordedAt,...typeof c.seq=="number"?{seq:c.seq}:{}})}}return s}async*streamFile(e){let t;try{t=qN(e)}catch(i){if(i.code==="ENOENT")return;throw i}if(await new Promise(i=>{let a=!1,d=c=>{a||(a=!0,i(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 s=e.endsWith(".gz")?t.pipe(zN()):t,o=JN({input:s,crlfDelay:1/0});try{for await(let i of o){if(i.length===0)continue;let a;try{a=JSON.parse(i)}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,...typeof d.seq=="number"?{seq:d.seq}:{}})}}finally{o.close(),t.destroy()}}async getArchiveLineCounts(e){if(!is.test(e))return[];let t=this.archiveLineCounts.get(e),r=await this.listArchives(e);if(t&&t.length===r.length&&t.every((o,i)=>o.index===r[i].index&&o.path===r[i].path))return t;let s=[];for(let{index:o,path:i}of r){let a=t?.find(c=>c.index===o&&c.path===i);if(a){s.push(a);continue}let d=0;for await(let c of this.streamFile(i))d+=1;s.push({index:o,path:i,lineCount:d})}return this.archiveLineCounts.set(e,s),s}async hydrateEntry(e,t,r){return db(t,async s=>{let o=r.get(s);if(o!==void 0)return o;let i=await Wl(e,s);return r.set(s,i),i})}async*iterRecallNewestFirst(e){if(!is.test(e))return;let t=this.writeQueues.get(e);t&&await t;let r=await this.getArchiveLineCounts(e),s=0;for(let c of r)s+=c.lineCount;let o=new Map,i=[];for await(let c of this.streamFile(D.historyFile(e)))i.push(c);for(let c=i.length-1;c>=0;c--){let l=await this.hydrateEntry(e,i[c],o);yield{entryId:s+c,entry:l}}let a=new Array(r.length),d=0;for(let c=0;c<r.length;c++)a[c]=d,d+=r[c].lineCount;for(let c=r.length-1;c>=0;c--){let l=r[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 m=await this.hydrateEntry(e,u[p],o);yield{entryId:f+p,entry:m}}}}async rangeSlice(e,t,r){if(!is.test(e))return[];if(r<t)return[];let s=this.writeQueues.get(e);s&&await s;let o=await this.getArchiveLineCounts(e),i=0;for(let l of o)i+=l.lineCount;let a=[],d=new Map,c=0;for(let l of o){let u=c,f=c+l.lineCount;if(c=f,f<=t)continue;if(u>r)break;let p=0;for await(let m of this.streamFile(l.path)){let h=u+p;if(p+=1,h<t)continue;if(h>r)break;let g=await this.hydrateEntry(e,m,d);a.push({entryId:h,entry:g})}}if(r>=i){let l=Math.max(t-i,0),u=r-i,f=0;for await(let p of this.streamFile(D.historyFile(e))){if(f>u)break;if(f>=l){let m=await this.hydrateEntry(e,p,d);a.push({entryId:i+f,entry:m})}f+=1}}return a}async getRecallTotalCount(e){if(!is.test(e))return 0;let t=await this.getArchiveLineCounts(e),r=0;for(let o of t)r+=o.lineCount;let s=0;for await(let o of this.streamFile(D.historyFile(e)))s+=1;return r+s}async load(e,t={}){if(!is.test(e))return[];let r=(t.tools??"inline")==="inline",s=this.writeQueues.get(e);s&&await s;let o;try{o=await kt.readFile(D.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let i=[];for(let f of o.split(`
|
|
356
|
-
`)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt,...typeof m.seq=="number"?{seq:m.seq}:{}})}let a=t.maxEntries??this.maxEntries,d=i.length>a?i.slice(-a):i;if(!r)return d;let c=new Map,l=async f=>{let p=c.get(f);if(p!==void 0)return p;let m=await Wl(e,f);return c.set(f,m),m},u=[];for(let f of d)u.push(await db(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(is.test(e))return this.enqueue(e,async()=>{try{await kt.unlink(D.historyFile(e))}catch(r){if(r.code!=="ENOENT")throw r}let t=await this.listArchiveIndices(e);for(let r of t)await this.unlinkArchive(e,r);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await mI(e);try{await kt.rmdir(D.sessionDir(e))}catch(r){let s=r;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw r}})}enqueue(e,t){let s=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=s.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),s}};Xp();ke();rt();rh();ma();Rp();Kl();fn();Sc();fn();bo();dr();$w();var MR=900*1e3,iD=12,aD="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ya=oD(aD,16);function dD(){let n,e,t=!1;return{send(r){if(t)return Promise.resolve();if("method"in r&&"id"in r){let s={jsonrpc:"2.0",id:r.id,error:{code:G.MethodNotFound,message:`no handler for ${r.method} (headless fork-prompt client)`}};queueMicrotask(()=>n?.(s))}return Promise.resolve()},onMessage(r){n=r},onClose(r){e=r},close(){return t||(t=!0,e?.()),Promise.resolve()}}}var sh=class n{constructor(e,t,r,s={}){this.registry=e;this.spawner=t??(a=>ni.spawn(a)),this.store=r??new Op,this.tombstones=s.tombstones??new Gp,this.sessionHistoryMaxEntries=s.sessionHistoryMaxEntries??1e3,this.histories=new th({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:s.sessionHistoryArchiveMaxBytes,archiveTiers:s.sessionHistoryArchiveTiers}),this.workspaceSnapshotsDisabled=s.disableWorkspaceSnapshots===!0,this.idleTimeoutMs=s.idleTimeoutMs??0,this.orphanTimeoutMs=s.orphanTimeoutMs??0,this.idleEventTimeoutMs=s.idleEventTimeoutMs??3e4,this.sessionDefaults=s.sessionDefaults??{},this.synopsisAgent=s.synopsisAgent,this.synopsisModel=s.synopsisModel,this.compactionAgent=s.compactionAgent,this.compactionModel=s.compactionModel,this.defaultTransformers=s.defaultTransformers??[],this.logger=s.logger,this.npmRegistry=s.npmRegistry,this.extensionCommands=s.extensionCommands,this.defaultCwd=s.defaultCwd??"~";let o=s.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new Zp({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.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,u)=>{await this.dispatchSynthesisSwap(a,d,c,l,u)},onSynthesisUnavailable:async(a,d,c)=>{let l=await this.store.read(a).catch(()=>{});if(l?.synopsis&&l.summarizedThroughEntry!==void 0){this.logger?.info(`agent switch: synthesis produced no new artifact for sessionId=${a} (${c}); swapping to ${d} on the persisted synopsis`),await this.dispatchSynthesisSwap(a,l.synopsis,l.summarizedThroughEntry,d);return}let u=(await this.histories.load(a).catch(()=>[])).length;this.logger?.warn(`agent switch: synthesis unavailable for sessionId=${a} (${c}); swapping to ${d} on verbatim tail`),await this.dispatchSynthesisSwap(a,void 0,u,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;snapshotInFlight=new Set;snapshotPending=new Set;workspaceSnapshotsDisabled=!1;driftNoticed=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;orphanTimeoutMs;sessionDefaults;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;workspaceQueues=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,r,s,o){let i=this.get(e);if(t===void 0&&s===void 0)return;if(!i){if(this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),t===void 0)return;await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r});return}let a=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,a,r,s,o);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,s,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(d){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${d instanceof Error?d.message:String(d)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let r=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):d?.pendingAgentSwap&&this.dispatchSynthesisSwap(e,void 0,(await this.histories.load(e).catch(()=>[])).length,d.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){if(o?.pendingAgentSwap){let d=(await this.histories.load(e).catch(()=>[])).length;this.logger?.info(`compaction: no artifact for sessionId=${e}, swapping to ${o.pendingAgentSwap} on verbatim tail`),await this.performSynthesisSwap(t,void 0,r,d,o.pendingAgentSwap);return}this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,r,o.summarizedThroughEntry,i,o.compactionState?.runId)}catch(s){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${s instanceof Error?s.message:String(s)}`)}}async recordSynopsisFor(e){let t=await this.store.read(e).catch(()=>{});return t?.synopsis?{synopsis:t.synopsis}:{}}async performSynthesisSwap(e,t,r,s,o,i){try{let a=o?Math.min(t===void 0?iD:5,r):0;await e.swapUpstream({...t!==void 0?{artifact:t}:{},tailK:r,tailFloor:a,summarizedThroughEntry:s,...o?{newAgentId:o}:{},...i!==void 0?{runId:i}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(a){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await dc(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async adoptWorkspace(e,t,r){let s=t.label;if(s===void 0)throw new Error("workspace.adopt requires workspace.label");let o=this.liveSessionsWithLabel(r.cwd,s)[0]?.workspace,i=o!==void 0?this.asWorkspace(o):(await e.listWorkspaces(r.cwd).catch(()=>[])).find(a=>a.label===s);if(i===void 0)throw new Error(`cannot adopt workspace "${s}": no workspace by that name derived from ${V(r.cwd)}`);return await this.enqueueKeyed(this.workspaceQueues,i.path,async()=>(e.capabilities().locking&&await e.lock(i,`session ${r.title??"live"}`).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},...o?.clean!==void 0?{clean:o.clean}:{}}}))}async resolveWorkspace(e){let t=e.workspace;if(t===void 0)return{cwd:e.cwd};let r=je(t.provider);if(r===void 0){let l=`unknown workspace provider "${t.provider}"`;if(t.required===!0)throw new Error(`isolation required but unavailable: ${l}`);return this.logger?.warn?.(`session workspace: ${l}; running in ${e.cwd}`),{cwd:e.cwd,isolationError:l}}if(t.adopt===!0)return await this.adoptWorkspace(r,t,e);let s=t.label??`s-${ya().slice(0,8)}`,o=await r.createWorkspace({sourceCwd:e.cwd,label:s,...t.from!==void 0?{from:t.from}:{}}).catch(l=>({ok:!1,reason:String(l)}));if(!o.ok){if(t.required===!0)throw new Error(`isolation required but unavailable: ${o.reason}`);return this.logger?.warn?.(`session workspace: ${o.reason}; falling back to ${e.cwd} (unisolated)`),{cwd:e.cwd,isolationError:o.reason}}let i=o.workspace;r.capabilities().locking&&await r.lock(i,`session ${e.title??"live"}`).catch(()=>{});let a=await zp(i.sourceCwd).catch(()=>({})),d,c=await this.materializeNestedTrees(i);if(c!==void 0&&this.logger?.info?.(`session workspace: ${c} in ${i.path}`),a.carry!==void 0&&a.carry.length>0){let l=await tb(i.sourceCwd,i.path,a.carry).catch(()=>{});l!==void 0&&l.copied.length>0&&this.logger?.info?.(`session workspace: carried ${l.copied.length} file(s) into ${i.path}`)}if(a.postCreate!==void 0){let l=await Kp(a.postCreate,{workspacePath:i.path,sourceCwd:i.sourceCwd,label:i.label,...a.hookTimeoutSeconds!==void 0?{timeoutSeconds:a.hookTimeoutSeconds}:{}});l.ok||(d=`postCreate failed: ${l.reason??"unknown"}`,this.logger?.warn?.(`session workspace: ${d} (${i.path})`))}return i.snapshot!==void 0&&await r.retainSnapshot(i,this.startRefFor(i.label),i.snapshot).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},clean:!0},...d!==void 0?{isolationError:d}:{}}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let r=`${sn}${ya()}`,s=await this.resolveWorkspace(e),o=s.cwd,i=await this.bootstrapAgent({agentId:e.agentId,cwd:o,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,configDefaults:e.configDefaults,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,selfSessionId:r});if(e.transformChain&&e.transformChain.length>0){let d={...i.agentCapabilities??{}};for(let c of e.transformChain)if(c.intercepts.has("agent:initialize"))try{let l=await c.connection.request("hydra-acp/transformer/message",{token:`t_${ya()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:d});l.action==="stop"&&l.payload&&(d=l.payload)}catch{}i.agentCapabilities=d}let a=new yc({sessionId:r,cwd:o,...s.workspace!==void 0?{workspace:s.workspace}:{},...s.isolationError!==void 0?{workspaceError:s.isolationError}:{},agentId:e.agentId,agent:i.agent,upstreamSessionId:i.upstreamSessionId,agentMeta:i.agentMeta,agentCapabilities:i.agentCapabilities,...i.modelVerb?{modelVerb:i.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??[],selfSessionId:r}),loadExistingAgentSession:(d,c)=>this.bootstrapAgentLoad(d,{...c,mcpServers:c.mcpServers??[],selfSessionId:r}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:i.initialModel,currentMode:i.initialMode,agentModes:i.initialModes,agentModels:i.initialModels,agentConfigOptions:i.initialConfigOptions,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(a.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(a),scheduleCompaction:d=>this.scheduleCompaction(a.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(a.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(a.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(a.sessionId),uncompactHook:()=>this.performUncompact(a.sessionId),forkHook:d=>this.forkSession(a.sessionId,d??{}),workspaceHook:(d,c,l)=>this.runWorkspaceAction(a.sessionId,d,c,l),onCompactionSwapHook:d=>{this.persistRollbackBreadcrumb(a.sessionId,d).catch(()=>{})},persistWatermarkHook:d=>{this.mutateRecord(a.sessionId,{summarizedThroughEntry:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(a.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});if(s.workspace!==void 0){let d=je(s.workspace.provider);d!==void 0&&d.capabilities().supports.environmentNotes&&(a.workspaceNotes=await d.environmentNotes({path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:s.workspace.vcs}:{}}).catch(()=>[]))}return await this.attachManagerHooks(a),a}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=G.AlreadyAttached,o}return t}let r=this.resurrectionInflight.get(e.hydraSessionId);if(r)return r;let s=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,s);try{return await s}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let r=await this.registry.getAgent(e.agentId);if(!r){let k=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw k.code=G.AgentNotInstalled,k}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let s=await Ir(r,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=lp(e.hydraSessionId,e.forwardedEnv),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...o?{extraEnv:o}:{}}),a;try{let k=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:lc,clientInfo:{name:"hydra",version:Ue}});a=k.agentCapabilities,i.authMethods=pu(k.authMethods),i.steeringSupported=fu(k)}catch(k){throw await i.kill().catch(()=>{}),di(k,i)}let d;try{let k=fb(r,{model:e.currentModel});d=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...k&&{_meta:k}})}catch(k){if(k&&typeof k=="object"&&k.code===G.AuthRequired)throw await i.kill().catch(()=>{}),di(k,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${k.message}); recovering via import-reseed
|
|
356
|
+
`)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt,...typeof m.seq=="number"?{seq:m.seq}:{}})}let a=t.maxEntries??this.maxEntries,d=i.length>a?i.slice(-a):i;if(!r)return d;let c=new Map,l=async f=>{let p=c.get(f);if(p!==void 0)return p;let m=await Wl(e,f);return c.set(f,m),m},u=[];for(let f of d)u.push(await db(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(is.test(e))return this.enqueue(e,async()=>{try{await kt.unlink(D.historyFile(e))}catch(r){if(r.code!=="ENOENT")throw r}let t=await this.listArchiveIndices(e);for(let r of t)await this.unlinkArchive(e,r);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await mI(e);try{await kt.rmdir(D.sessionDir(e))}catch(r){let s=r;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw r}})}enqueue(e,t){let s=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=s.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),s}};Xp();ke();rt();rh();ma();Rp();Kl();fn();Sc();fn();ko();dr();$w();var MR=900*1e3,iD=12,aD="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ya=oD(aD,16);function dD(){let n,e,t=!1;return{send(r){if(t)return Promise.resolve();if("method"in r&&"id"in r){let s={jsonrpc:"2.0",id:r.id,error:{code:G.MethodNotFound,message:`no handler for ${r.method} (headless fork-prompt client)`}};queueMicrotask(()=>n?.(s))}return Promise.resolve()},onMessage(r){n=r},onClose(r){e=r},close(){return t||(t=!0,e?.()),Promise.resolve()}}}var sh=class n{constructor(e,t,r,s={}){this.registry=e;this.spawner=t??(a=>ni.spawn(a)),this.store=r??new Op,this.tombstones=s.tombstones??new Gp,this.sessionHistoryMaxEntries=s.sessionHistoryMaxEntries??1e3,this.histories=new th({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:s.sessionHistoryArchiveMaxBytes,archiveTiers:s.sessionHistoryArchiveTiers}),this.workspaceSnapshotsDisabled=s.disableWorkspaceSnapshots===!0,this.idleTimeoutMs=s.idleTimeoutMs??0,this.orphanTimeoutMs=s.orphanTimeoutMs??0,this.idleEventTimeoutMs=s.idleEventTimeoutMs??3e4,this.sessionDefaults=s.sessionDefaults??{},this.synopsisAgent=s.synopsisAgent,this.synopsisModel=s.synopsisModel,this.compactionAgent=s.compactionAgent,this.compactionModel=s.compactionModel,this.defaultTransformers=s.defaultTransformers??[],this.logger=s.logger,this.npmRegistry=s.npmRegistry,this.extensionCommands=s.extensionCommands,this.defaultCwd=s.defaultCwd??"~";let o=s.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new Zp({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.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,u)=>{await this.dispatchSynthesisSwap(a,d,c,l,u)},onSynthesisUnavailable:async(a,d,c)=>{let l=await this.store.read(a).catch(()=>{});if(l?.synopsis&&l.summarizedThroughEntry!==void 0){this.logger?.info(`agent switch: synthesis produced no new artifact for sessionId=${a} (${c}); swapping to ${d} on the persisted synopsis`),await this.dispatchSynthesisSwap(a,l.synopsis,l.summarizedThroughEntry,d);return}let u=(await this.histories.load(a).catch(()=>[])).length;this.logger?.warn(`agent switch: synthesis unavailable for sessionId=${a} (${c}); swapping to ${d} on verbatim tail`),await this.dispatchSynthesisSwap(a,void 0,u,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;snapshotInFlight=new Set;snapshotPending=new Set;workspaceSnapshotsDisabled=!1;driftNoticed=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;orphanTimeoutMs;sessionDefaults;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;workspaceQueues=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,r,s,o){let i=this.get(e);if(t===void 0&&s===void 0)return;if(!i){if(this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),t===void 0)return;await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r});return}let a=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,a,r,s,o);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,s,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(d){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${d instanceof Error?d.message:String(d)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let r=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):d?.pendingAgentSwap&&this.dispatchSynthesisSwap(e,void 0,(await this.histories.load(e).catch(()=>[])).length,d.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){if(o?.pendingAgentSwap){let d=(await this.histories.load(e).catch(()=>[])).length;this.logger?.info(`compaction: no artifact for sessionId=${e}, swapping to ${o.pendingAgentSwap} on verbatim tail`),await this.performSynthesisSwap(t,void 0,r,d,o.pendingAgentSwap);return}this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,r,o.summarizedThroughEntry,i,o.compactionState?.runId)}catch(s){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${s instanceof Error?s.message:String(s)}`)}}async recordSynopsisFor(e){let t=await this.store.read(e).catch(()=>{});return t?.synopsis?{synopsis:t.synopsis}:{}}async performSynthesisSwap(e,t,r,s,o,i){try{let a=o?Math.min(t===void 0?iD:5,r):0;await e.swapUpstream({...t!==void 0?{artifact:t}:{},tailK:r,tailFloor:a,summarizedThroughEntry:s,...o?{newAgentId:o}:{},...i!==void 0?{runId:i}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(a){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await dc(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async adoptWorkspace(e,t,r){let s=t.label;if(s===void 0)throw new Error("workspace.adopt requires workspace.label");let o=this.liveSessionsWithLabel(r.cwd,s)[0]?.workspace,i=o!==void 0?this.asWorkspace(o):(await e.listWorkspaces(r.cwd).catch(()=>[])).find(a=>a.label===s);if(i===void 0)throw new Error(`cannot adopt workspace "${s}": no workspace by that name derived from ${V(r.cwd)}`);return await this.enqueueKeyed(this.workspaceQueues,i.path,async()=>(e.capabilities().locking&&await e.lock(i,`session ${r.title??"live"}`).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},...o?.clean!==void 0?{clean:o.clean}:{}}}))}async resolveWorkspace(e){let t=e.workspace;if(t===void 0)return{cwd:e.cwd};let r=je(t.provider);if(r===void 0){let l=`unknown workspace provider "${t.provider}"`;if(t.required===!0)throw new Error(`isolation required but unavailable: ${l}`);return this.logger?.warn?.(`session workspace: ${l}; running in ${e.cwd}`),{cwd:e.cwd,isolationError:l}}if(t.adopt===!0)return await this.adoptWorkspace(r,t,e);let s=t.label??`s-${ya().slice(0,8)}`,o=await r.createWorkspace({sourceCwd:e.cwd,label:s,...t.from!==void 0?{from:t.from}:{}}).catch(l=>({ok:!1,reason:String(l)}));if(!o.ok){if(t.required===!0)throw new Error(`isolation required but unavailable: ${o.reason}`);return this.logger?.warn?.(`session workspace: ${o.reason}; falling back to ${e.cwd} (unisolated)`),{cwd:e.cwd,isolationError:o.reason}}let i=o.workspace;r.capabilities().locking&&await r.lock(i,`session ${e.title??"live"}`).catch(()=>{});let a=await zp(i.sourceCwd).catch(()=>({})),d,c=await this.materializeNestedTrees(i);if(c!==void 0&&this.logger?.info?.(`session workspace: ${c} in ${i.path}`),a.carry!==void 0&&a.carry.length>0){let l=await tb(i.sourceCwd,i.path,a.carry).catch(()=>{});l!==void 0&&l.copied.length>0&&this.logger?.info?.(`session workspace: carried ${l.copied.length} file(s) into ${i.path}`)}if(a.postCreate!==void 0){let l=await Kp(a.postCreate,{workspacePath:i.path,sourceCwd:i.sourceCwd,label:i.label,...a.hookTimeoutSeconds!==void 0?{timeoutSeconds:a.hookTimeoutSeconds}:{}});l.ok||(d=`postCreate failed: ${l.reason??"unknown"}`,this.logger?.warn?.(`session workspace: ${d} (${i.path})`))}return i.snapshot!==void 0&&await r.retainSnapshot(i,this.startRefFor(i.label),i.snapshot).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},clean:!0},...d!==void 0?{isolationError:d}:{}}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let r=`${sn}${ya()}`,s=await this.resolveWorkspace(e),o=s.cwd,i=await this.bootstrapAgent({agentId:e.agentId,cwd:o,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,configDefaults:e.configDefaults,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,selfSessionId:r});if(e.transformChain&&e.transformChain.length>0){let d={...i.agentCapabilities??{}};for(let c of e.transformChain)if(c.intercepts.has("agent:initialize"))try{let l=await c.connection.request("hydra-acp/transformer/message",{token:`t_${ya()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:d});l.action==="stop"&&l.payload&&(d=l.payload)}catch{}i.agentCapabilities=d}let a=new yc({sessionId:r,cwd:o,...s.workspace!==void 0?{workspace:s.workspace}:{},...s.isolationError!==void 0?{workspaceError:s.isolationError}:{},agentId:e.agentId,agent:i.agent,upstreamSessionId:i.upstreamSessionId,agentMeta:i.agentMeta,agentCapabilities:i.agentCapabilities,...i.modelVerb?{modelVerb:i.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??[],selfSessionId:r}),loadExistingAgentSession:(d,c)=>this.bootstrapAgentLoad(d,{...c,mcpServers:c.mcpServers??[],selfSessionId:r}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:i.initialModel,currentMode:i.initialMode,agentModes:i.initialModes,agentModels:i.initialModels,agentConfigOptions:i.initialConfigOptions,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(a.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(a),scheduleCompaction:d=>this.scheduleCompaction(a.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(a.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(a.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(a.sessionId),uncompactHook:()=>this.performUncompact(a.sessionId),forkHook:d=>this.forkSession(a.sessionId,d??{}),workspaceHook:(d,c,l)=>this.runWorkspaceAction(a.sessionId,d,c,l),onCompactionSwapHook:d=>{this.persistRollbackBreadcrumb(a.sessionId,d).catch(()=>{})},persistWatermarkHook:d=>{this.mutateRecord(a.sessionId,{summarizedThroughEntry:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(a.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});if(s.workspace!==void 0){let d=je(s.workspace.provider);d!==void 0&&d.capabilities().supports.environmentNotes&&(a.workspaceNotes=await d.environmentNotes({path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:s.workspace.vcs}:{}}).catch(()=>[]))}return await this.attachManagerHooks(a),a}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=G.AlreadyAttached,o}return t}let r=this.resurrectionInflight.get(e.hydraSessionId);if(r)return r;let s=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,s);try{return await s}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let r=await this.registry.getAgent(e.agentId);if(!r){let k=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw k.code=G.AgentNotInstalled,k}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let s=await Ir(r,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=lp(e.hydraSessionId,e.forwardedEnv),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...o?{extraEnv:o}:{}}),a;try{let k=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:lc,clientInfo:{name:"hydra",version:Ue}});a=k.agentCapabilities,i.authMethods=pu(k.authMethods),i.steeringSupported=fu(k)}catch(k){throw await i.kill().catch(()=>{}),di(k,i)}let d;try{let k=fb(r,{model:e.currentModel});d=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...k&&{_meta:k}})}catch(k){if(k&&typeof k=="object"&&k.code===G.AuthRequired)throw await i.kill().catch(()=>{}),di(k,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${k.message}); recovering via import-reseed
|
|
357
357
|
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let k=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${k} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=gb(d??{}),l=e.agentModes??ai(mb(d??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(l?.map(k=>k.id))}`);let u=await ca({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:l,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(u)} for sessionId=${e.hydraSessionId}`);let f=pb(d??{}),p=ai(hb(d??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(p?.map(k=>k.modelId))}`),e.pendingHistorySync!==!0){let k=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${k} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=uc(d),h=await la({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,...m?{modelVerb:m}:{},logger:this.logger}),g=h.modelId,w=ai(ba(wa(h.result)?h.result:d??{}));if(w=ai(await this.restoreConfigOptionValues(i,e.upstreamSessionId,e.configOptionValues,w??[])),e.pendingHistorySync!==!0){let k=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${k} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let b=new yc({sessionId:e.hydraSessionId,cwd:e.cwd,...e.workspace!==void 0?{workspace:e.workspace}:{},agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:d?._meta,agentCapabilities:a,...m?{modelVerb:m}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,logger:this.logger,spawnReplacementAgent:k=>this.bootstrapAgent({...k,mcpServers:k.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(k,S)=>this.bootstrapAgentLoad(k,{...S,mcpServers:S.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:g,currentMode:u,currentUsage:e.currentUsage,reloadsUpstreamLedger:!0,agentCommands:e.agentCommands,agentModes:l,agentModels:p,agentConfigOptions:w,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,upstreamRespawned:!0,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(b.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(b),scheduleCompaction:k=>this.scheduleCompaction(b.sessionId,k),resolveAgentId:async k=>(await this.registry.getAgent(k))?.id,getCompactionState:()=>this.getCompactionState(b.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(b.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(b.sessionId),uncompactHook:()=>this.performUncompact(b.sessionId),forkHook:k=>this.forkSession(b.sessionId,k??{}),workspaceHook:(k,S,I)=>this.runWorkspaceAction(b.sessionId,k,S,I),onCompactionSwapHook:k=>{this.persistRollbackBreadcrumb(b.sessionId,k).catch(()=>{})},persistWatermarkHook:k=>{this.mutateRecord(b.sessionId,{summarizedThroughEntry:k}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(b.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(b),b}async doResurrectFromImport(e){let t=await this.resolveResurrectTarget(e.cwd,e.workspace),r=t.cwd,s=await this.bootstrapAgent({agentId:e.agentId,cwd:r,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),o=e.agentModes??s.initialModes,i=await ca({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:o,logger:this.logger}),a=e.agentModels??s.initialModels,d=await la({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,...s.modelVerb?{modelVerb:s.modelVerb}:{},logger:this.logger}),c=d.modelId,l=wa(d.result)?ai(ba(d.result)):void 0;l=ai(await this.restoreConfigOptionValues(s.agent,s.upstreamSessionId,e.configOptionValues,l??s.initialConfigOptions??[])),s.agent.connection.drainBuffered("session/update");let u=new yc({sessionId:e.hydraSessionId,cwd:r,...t.workspace!==void 0?{workspace:t.workspace}:{},agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,...s.modelVerb?{modelVerb:s.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,logger:this.logger,spawnReplacementAgent:f=>this.bootstrapAgent({...f,mcpServers:f.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(f,p)=>this.bootstrapAgentLoad(f,{...p,mcpServers:p.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:c,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:o,agentModels:a,agentConfigOptions:l??s.initialConfigOptions,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,upstreamRespawned:!0,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(u.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(u),scheduleCompaction:f=>this.scheduleCompaction(u.sessionId,f),resolveAgentId:async f=>(await this.registry.getAgent(f))?.id,getCompactionState:()=>this.getCompactionState(u.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(u.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(u.sessionId),uncompactHook:()=>this.performUncompact(u.sessionId),forkHook:f=>this.forkSession(u.sessionId,f??{}),workspaceHook:(f,p,m)=>this.runWorkspaceAction(u.sessionId,f,p,m),onCompactionSwapHook:f=>{this.persistRollbackBreadcrumb(u.sessionId,f).catch(()=>{})},persistWatermarkHook:f=>{this.mutateRecord(u.sessionId,{summarizedThroughEntry:f}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(u.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(u),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${u.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?u.seedFromFork(e.synopsis).catch(()=>{}):u.seedFromImport().catch(()=>{}),u}async dirExists(e){try{return(await ka.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);if(!(!t||t.attachedCount>0)&&t.interactive!==!0){if(t.hasWorkInFlight){this.logger?.info(`deferring reap of ${e}: work still in flight after detach`),t.onceIdle(r=>{this.reapIfOrphanedNonInteractive(r.sessionId).catch(()=>{})});return}this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}async resolveResurrectTarget(e,t){if(await this.dirExists(e))return t!==void 0?{cwd:e,workspace:t}:{cwd:e};if(t!==void 0){let r=await this.recoverWorkspace(t);if(r!==void 0)return{cwd:r.path,workspace:r}}return{cwd:mt(this.defaultCwd)}}async releaseWorkspace(e,t){let r=je(e.provider);if(r===void 0){this.logger?.warn?.(`session workspace: no provider "${e.provider}" to release ${e.path}; leaving it in place`);return}return this.enqueueKeyed(this.workspaceQueues,e.path,async()=>{let s=this.liveSessionsIn(e.path,t);if(s.length>0){this.logger?.info?.(`session workspace: keeping ${e.path} \u2014 ${s.length} live session(s) still in it`);return}await this.tearDownWorkspace(r,e,t)})}async syncWorkspaceFromSource(e,t,r){let s=this.liveSessionsIn(t.path,e.sessionId);if(s.length>0)throw new Error(`${V(t.path)} is shared with ${s.map(p=>st(p.sessionId)).join(", ")}, and a sync would move files under them. Sync it from a session that has it to itself.`);let o=await e.quiesceBlocker();if(o!==void 0)throw new Error(o);let i=je(t.provider);if(t.line===void 0||i?.capabilities().sharedHistory!==!0)throw new Error(`workspace ${t.label} uses the "${t.provider}" provider, which has no history to merge from \u2014 a sync needs a common base, and a copied directory has none. Land its work with \`/hydra workspace merge\` instead, or start a git-backed workspace if you need to track the source.`);let[a,d]=await Promise.all([i.currentState(t.sourceCwd),i.currentState(t.path)]);if(a===void 0||d===void 0)throw new Error("could not read the state of the source or the workspace");if(await i.contains(t.path,{state:a,within:d}))return{ok:!0,message:`Already up to date with ${V(t.sourceCwd)} (${a.slice(0,8)}).`};let c=await i.divergence(t.path,d,a),l=String(c?.behind??0),u=await i.integrate({into:t.path,from:a,message:`hydra: sync ${t.label} with the source`});if(!u.ok){let p=u.conflicts,m=await i.integrationInProgress(t.path);if(p.length===0&&!m){let g=await this.syncOverDirtyTree(t,{provider:i,before:d,sourceHead:a,incoming:l});if(g!==void 0)return g}let h=p.length>0?`
|
|
358
358
|
${p.map(g=>` ${g}`).join(`
|
|
359
359
|
`)}`:` (${u.reason??"the integration failed"})`;return p.length===0?{ok:!1,message:`the source could not be merged into ${V(t.path)}; nothing changed.${h}
|
|
@@ -393,20 +393,20 @@ ${A}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),th
|
|
|
393
393
|
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof g=="number"?g:void 0,e.processToken&&(this.tokenRegistry?.revoke(s.name),e.processToken=void 0);let b=e.exitWaiters.splice(0);for(let S of b)S();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let k=e.breaker.recordExit(g,s.name,this.adapter.kind);if(typeof k=="object"){e.failureReason=k.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${s.name} circuit breaker tripped: ${k.tripped}
|
|
394
394
|
`);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let r=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(s=>{e.failureReason=`spawn: ${s.message}`})},r),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function wb(n){try{return process.kill(n,0),!0}catch{return!1}}function gu(n,e){return n.code=e,n}ke();var vD={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:D.extensionsDir,logFile:D.extensionLogFile,pidFile:D.extensionPidFile}},fh=class extends Cc{constructor(e,t,r={}){super(e,vD,t,r)}};ke();var SD={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:D.transformersDir,logFile:D.transformerLogFile,pidFile:D.transformerPidFile}},ph=class extends Cc{connected=new Map;constructor(e,t,r={}){super(e,SD,t,r)}registerConnection(e,t,r){this.connected.set(e,{name:e,connection:t,intercepts:new Set(r)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let r of e){let s=this.connected.get(r);s&&t.push(s)}return t}interestedIn(e){let t=[];for(let r of this.connected.values())r.intercepts.has(e)&&t.push(r);return t}};var hh=class{entries=new Map;changeHandlers=[];register(e,t,r){this.entries.set(e,{connection:t,commands:[...r]}),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,r]of this.entries)for(let s of r.commands)e.push({name:t,command:s});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{}}};ke();ch();jd();oc();cw();ke();oc();import*as wu from"fs/promises";import*as mh from"path";var yu=n=>{process.stderr.write(n+`
|
|
395
395
|
`)};function bb(n){yu=n??(e=>process.stderr.write(e+`
|
|
396
|
-
`))}async function HR(n,e){let t=Sr();if(!t)return;let r=await n.load(),s=new Map;for(let d of r.agents)s.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=mh.join(D.agentsDir(),t),a;try{a=await wu.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;yu(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=s.get(c);if(l===void 0)continue;let u=o.get(c)??new Set,f=mh.join(i,c),p;try{p=await wu.readdir(f,{withFileTypes:!0})}catch(m){yu(`hydra-acp: prune: failed to read ${f}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||u.has(h)||h.includes(".partial-"))continue;let g=mh.join(f,h);try{await wu.rm(g,{recursive:!0,force:!0}),yu(`hydra-acp: pruned stale ${c} ${h} (${g})`)}catch(w){yu(`hydra-acp: prune: failed to remove ${g}: ${w.message}`)}}}}Os();function UR(n){let e,t=!1,r=0,s=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await pw(u)==="yes"&&a.push(u.id)}catch(l){return s("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=r%a.length;r=(r+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);s("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){s("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{s("warn",`tick crashed: ${d.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function kb(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},r=Date.now(),s=n.maxAgeMs>0?r-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(n.maxAgeMs>0&&h>s||i.push({sessionId:p.sessionId,lastUsedMs:h}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=i.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(m){l+=1,t("warn",`delete ${p} failed: ${m.message}`)}let u=i.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 ${xD(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:i.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function WR(n){let e,t=!1,r=!1,s=o=>{t||(e=setTimeout(()=>{(async()=>{if(!r){r=!0;try{await kb({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{r=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{s(n.intervalMs)})},o),e.unref())};return s(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function xD(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`}dr();Rc();rt();Rc();ke();import*as zR from"fs/promises";var CD=3e3;async function qR(){try{return(await zR.stat(D.config())).mtimeMs}catch{return}}function KR(n){let e=n.intervalMs??CD,t=!1,r,s,o=qR().then(d=>{s=d}),i=async()=>{await o;let d=await qR();if(d===s)return;s=d;let c;try{c=await
|
|
396
|
+
`))}async function HR(n,e){let t=Sr();if(!t)return;let r=await n.load(),s=new Map;for(let d of r.agents)s.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=mh.join(D.agentsDir(),t),a;try{a=await wu.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;yu(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=s.get(c);if(l===void 0)continue;let u=o.get(c)??new Set,f=mh.join(i,c),p;try{p=await wu.readdir(f,{withFileTypes:!0})}catch(m){yu(`hydra-acp: prune: failed to read ${f}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||u.has(h)||h.includes(".partial-"))continue;let g=mh.join(f,h);try{await wu.rm(g,{recursive:!0,force:!0}),yu(`hydra-acp: pruned stale ${c} ${h} (${g})`)}catch(w){yu(`hydra-acp: prune: failed to remove ${g}: ${w.message}`)}}}}Os();function UR(n){let e,t=!1,r=0,s=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await pw(u)==="yes"&&a.push(u.id)}catch(l){return s("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=r%a.length;r=(r+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);s("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){s("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{s("warn",`tick crashed: ${d.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function kb(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},r=Date.now(),s=n.maxAgeMs>0?r-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(n.maxAgeMs>0&&h>s||i.push({sessionId:p.sessionId,lastUsedMs:h}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=i.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(m){l+=1,t("warn",`delete ${p} failed: ${m.message}`)}let u=i.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 ${xD(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:i.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function WR(n){let e,t=!1,r=!1,s=o=>{t||(e=setTimeout(()=>{(async()=>{if(!r){r=!0;try{await kb({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{r=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{s(n.intervalMs)})},o),e.unref())};return s(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function xD(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`}dr();Rc();rt();Rc();ke();import*as zR from"fs/promises";var CD=3e3;async function qR(){try{return(await zR.stat(D.config())).mtimeMs}catch{return}}function KR(n){let e=n.intervalMs??CD,t=!1,r,s,o=qR().then(d=>{s=d}),i=async()=>{await o;let d=await qR();if(d===s)return;s=d;let c;try{c=await yo()}catch(u){n.logger?.warn(`config-reload: config.json changed but did not parse (${u.message}); keeping the loaded config`);return}try{n.apply(c)}catch(u){n.logger?.warn(`config-reload: applying live config failed: ${u.message}`)}let l=jR(n.bootConfig,c);n.onDrift?.(l),n.logger?.info(l.length>0?`config-reload: applied live config; restart-only keys differing from boot: ${l.join(", ")}`:"config-reload: applied live config")},a=()=>{t||(r=setTimeout(()=>{i().finally(a)},e),r.unref?.())};return a(),()=>{t=!0,r&&clearTimeout(r)}}ke();es();import*as VR from"path";import{createHash as RD,randomBytes as AD,timingSafeEqual as TD}from"crypto";var YR="hydra_session_",ED=3600*24*30,GR=12,PD=32,MD=50;function _D(){return VR.join(D.home(),"session-tokens.json")}function JR(n){return RD("sha256").update(n).digest("hex")}function QR(n){return AD(n).toString("hex")}function $D(){return QR(GR).slice(0,GR*2)}function OD(){return`${YR}${QR(PD)}`}var gh=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let r of e)this.records.set(r.hash,r)}static async load(){let e=[],t=_D(),r=await jt(t);r&&Array.isArray(r.records)&&(e=r.records.filter(FD));let s=new n(e,t);return s.sweepExpired(new Date)>0&&await s.flush(),s}async issue(e={}){let t=OD(),r=JR(t),s=$D(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:ED,a=new Date(o.getTime()+i*1e3),d={id:s,hash:r,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(r,d),this.scheduleWrite(),{id:s,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(YR))return;let t=JR(e),r=this.records.get(t);if(!r)return;let s=Buffer.from(r.hash,"hex"),o=Buffer.from(t,"hex");if(s.length!==o.length||!TD(s,o))return;let i=new Date;if(new Date(r.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return r.lastUsedAt=i.toISOString(),this.scheduleWrite(),r.id}async revoke(e){for(let[t,r]of this.records)if(r.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:r,expiresAt:s,lastUsedAt:o})=>({id:e,label:t,createdAt:r,expiresAt:s,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[r,s]of this.records)new Date(s.expiresAt).getTime()<=e.getTime()&&(this.records.delete(r),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(()=>{})},MD))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>nn(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function FD(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")}go();var XR="Bearer ",yh=class{constructor(e){this.token=e}token;async validate(e){return ND(e,this.token)?"service":void 0}rotate(e){this.token=e}},wh=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},bh=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let r=await t.validate(e);if(r!==void 0)return r}}};function ZR(n){return async function(t,r){let s=t.headers.authorization;if(!s||!s.startsWith(XR)){r.code(401).send({error:"Missing bearer token"});return}let o=s.slice(XR.length).trim(),i=await n.validator.validate(o);if(!i){r.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function eA(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let r of t.split(",")){let s=r.trim(),o="hydra-acp-token.";if(s.startsWith(o))return s.slice(o.length)}if(n.url)try{let s=new URL(n.url,"http://localhost").searchParams.get("token");if(s)return s}catch{return}}var kh=class{tokens=new Map;mint(e,t){let r=Md();return this.tokens.set(r,{name:e,kind:t}),r}revoke(e){for(let[t,r]of this.tokens)r.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}`}},LD=new Set(["GET /v1/sessions","GET /v1/sessions/:id","GET /v1/config"]);function tA(n,e){return e?LD.has(`${n} ${e}`):!1}function ND(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r+=1)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var vh=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(),r=this.entries.get(e);if(!r||t-r.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}r.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,r]of this.entries)e-r.windowStart>this.windowMs&&this.entries.delete(t)}};zl();ke();rt();Sb();ma();Ch();import*as Eb from"fs";import*as PA from"os";import*as _h from"path";import*as Pb from"readline";Io();ir();Sc();function Rh(n,e={}){let t=pB(n),{events:r,window:s}=fB(t,e),o=hB(r),i=[];mB(i,n),s&&(s.from>1||s.to<s.total)&&(i.push(`_Showing turns ${s.from}-${s.to} of ${s.total}._`),i.push("")),gB(i,r,o,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let a=i.join(`
|
|
397
397
|
`);return a.endsWith(`
|
|
398
398
|
`)||(a+=`
|
|
399
|
-
`),a}function Rb(n,e){let t=n<0?e+n+1:n;return t<1?1:t>e?e:t}function fB(n,e){if(!(e.from!==void 0||e.to!==void 0||e.last!==void 0)&&e.sinceMs===void 0)return{events:n};let r=[],s=0;for(let{event:p}of n)p.kind==="user-text"&&(s+=1),r.push(s===0?1:s);let o=Math.max(s,1),i=1,a=o;if(e.last!==void 0&&e.last>0?i=Rb(o-e.last+1,o):(e.from!==void 0&&(i=Rb(e.from,o)),e.to!==void 0&&(a=Rb(e.to,o))),i>a)return{events:[],window:{from:i,to:a,total:o}};let d=e.sinceMs,c=new Set;d!==void 0&&n.forEach((p,m)=>{p.recordedAt>=d&&c.add(r[m])});let l=[],u,f;return n.forEach((p,m)=>{let h=r[m];h<i||h>a||d!==void 0&&!c.has(h)||(l.push(p),u??=h,f=h)}),{events:l,window:{from:u??i,to:f??a,total:o}}}function pB(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let r=t.params;if(!r||typeof r!="object")continue;let s=
|
|
399
|
+
`),a}function Rb(n,e){let t=n<0?e+n+1:n;return t<1?1:t>e?e:t}function fB(n,e){if(!(e.from!==void 0||e.to!==void 0||e.last!==void 0)&&e.sinceMs===void 0)return{events:n};let r=[],s=0;for(let{event:p}of n)p.kind==="user-text"&&(s+=1),r.push(s===0?1:s);let o=Math.max(s,1),i=1,a=o;if(e.last!==void 0&&e.last>0?i=Rb(o-e.last+1,o):(e.from!==void 0&&(i=Rb(e.from,o)),e.to!==void 0&&(a=Rb(e.to,o))),i>a)return{events:[],window:{from:i,to:a,total:o}};let d=e.sinceMs,c=new Set;d!==void 0&&n.forEach((p,m)=>{p.recordedAt>=d&&c.add(r[m])});let l=[],u,f;return n.forEach((p,m)=>{let h=r[m];h<i||h>a||d!==void 0&&!c.has(h)||(l.push(p),u??=h,f=h)}),{events:l,window:{from:u??i,to:f??a,total:o}}}function pB(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let r=t.params;if(!r||typeof r!="object")continue;let s=js(r.update,{cwd:n.session.cwd});s!==null&&e.push({event:s,recordedAt:t.recordedAt})}return e}function hB(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let r=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??r?.status??"pending"});continue}if(t.kind==="tool-call-update"){let r=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??r.title,status:t.status??r.status})}}return e}function mB(n,e){let t=e.session,r=st(t.sessionId),s=t.title?.trim()||`Hydra session ${r}`;n.push(`# ${Su(s)}`),n.push("");let o=[];o.push(`- **Session:** \`${r}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.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||a.cumulativeCost!==void 0)){let d=[];if(a.used!==void 0){let l=a.size!==void 0?`${Ab(a.size)}`:void 0;d.push(l?`${Ab(a.used)} / ${l} tokens`:`${Ab(a.used)} tokens`)}let c=uu(a);if(c!==void 0){let l=a.costCurrency??"USD";d.push(`$${c.toFixed(2)} ${l}`)}o.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(o.join(`
|
|
400
400
|
`)),n.push("")}function gB(n,e,t,r){let{includeTools:s,includeThoughts:o}=r;if(!e.some(h=>yB(h.event,o))){n.push("_No conversation history recorded._"),n.push("");return}let i=0,a="",d="",c=[],l=new Set,u=!1,f=()=>{if(c.length!==0){for(let h of c)n.push(h);n.push(""),c=[]}},p=()=>{f(),d.length>0&&(mA(n,d.trimEnd(),"*"),n.push(""),d=""),a.length!==0&&(n.push(a.trimEnd()),n.push(""),a="")},m=()=>{u||(u=!0)};for(let{event:h}of e)switch(h.kind){case"user-text":{p(),n.push("---"),n.push(""),i+=1,mA(n,h.text,"**"),n.push(""),u=!0;break}case"agent-text":m(),a+=h.text;break;case"agent-thought":{if(!o)break;m(),a.length>0&&(n.push(a.trimEnd()),n.push(""),a=""),d+=h.text;break}case"tool-call":{if(!s||(m(),(a.length>0||d.length>0)&&p(),l.has(h.toolCallId)))break;l.add(h.toolCallId);let g=t.get(h.toolCallId)??{title:h.title,status:h.status??"pending"};c.push(`- ${bB(g.status)} ${wB(g)}`);break}case"tool-call-update":break;case"plan":{m(),p(),n.push("**Plan:**"),n.push("");for(let g of h.entries){let w=g.status==="completed"?"[x]":"[ ]";n.push(`- ${w} ${Su(g.content)}`)}n.push("");break}case"mode-changed":m(),p(),n.push(`_mode: ${Su(h.mode)}_`),n.push("");break;case"model-changed":m(),p(),n.push(`_model: ${Su(h.model)}_`),n.push("");break;case"turn-complete":p();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}p()}function yB(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 wB(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Su(n.title)}${t}`}function bB(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"}}var gA=String.raw`<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>`,kB=new RegExp(gA);function mA(n,e,t){if(kB.test(e)){vB(n,e);return}let r=e.split(/\n\s*\n/);for(let s=0;s<r.length;s++){let o=r[s];if(o.trim().length===0)continue;let i=o.split(`
|
|
401
401
|
`);for(let a=0;a<i.length;a++){let d=i[a];n.push(a===0&&a===i.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===i.length-1?`${d}${t}`:d)}s<r.length-1&&n.push("")}}function vB(n,e){let t=e.replace(/\s+$/,"");if(t.length===0)return;let r=0;for(let o of t.match(/`+/g)??[])r=Math.max(r,o.length);let s="`".repeat(Math.max(3,r+1));n.push(s);for(let o of t.split(`
|
|
402
|
-
`))n.push(o);n.push(s)}function Su(n){return n.replace(new RegExp(gA,"g"),e=>e.replace(/</g,"<").replace(/>/g,">"))}function Ab(n){return n.toLocaleString("en-US")}fn();dr();Ts();Eh();Od();import{randomBytes as CA}from"crypto";function IA(n){let e=CA(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 Tb(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async r=>{let s=[...n.baselineMcpServers??[]];n.stdinEnabled&&s.push(IA({name:"hydra-acp-stdin",session:r,tokenRegistry:e,getOrigin:t})),s.push(IA({name:"hydra-acp-recall",session:r,tokenRegistry:e,getOrigin:t}));let o=Pc(n.deps);return o!==void 0&&(o.bindToSession(r),s=[...s,...o.descriptors]),s}}function Pc(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=CA(32).toString("hex"),r=n.mcpTokenRegistry.reserve(t),s=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${s}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{r.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>r.abandon(a)}}rt();Ts();Gl();ir();var BB=new Set(["/v1/sessions/:id/history","/v1/sessions/:id/events"]);function RA(n,e){let t=e.fetchImpl??fetch;n.addHook("preHandler",async(r,s)=>{let o=r.routeOptions.url;if(!o||!o.startsWith("/v1/sessions/:id"))return;let i=r.params,a=i.id;if(typeof a!="string")return;let d=Ds(a);if(!d){if(!e.localMiss||await e.localMiss.resolvesLocally(a))return;let w=e.localMiss.cache.findByLocalId(a);if(w.length===0)return;if(w.length>1){s.code(404).send({error:`Session "${a}" exists on more than one remote (${w.map(b=>b.name).join(", ")}). Address it as "<remote>:${a}".`});return}d=w[0]}let c=e.store.get(d.name);if(!c){s.code(404).send({error:`No remote named "${d.name}". Run \`hydra remote add\` first.`});return}let l=r.query;if(BB.has(o)&&UB(l?.follow)){let w=c.port===An?"":`:${c.port}`;s.code(501).send({error:`Streaming a federated session isn't supported yet. Attach directly with hydra://${c.host}${w}/${d.localId} instead.`});return}let u=WB(o,i,d.localId,r.url),p=`${Vt(c.host)?"http":"https"}://${c.host}:${c.port}${u}`,m;try{m=await t(p,{method:r.method,headers:{Authorization:`Bearer ${c.token}`,...r.body!==void 0?{"Content-Type":"application/json"}:{}},...r.body!==void 0&&r.method!=="GET"?{body:JSON.stringify(r.body)}:{}})}catch(w){s.code(502).send({error:`Could not reach remote "${d.name}" (${c.host}:${c.port}): ${w.message}`});return}if(m.status===204){s.code(204).send();return}let h=await m.text(),g=m.headers.get("content-type");g&&s.header("content-type",g),s.code(m.status).send(h)})}var HB=5e3,Ph=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;perPeer=new Map;timer;start(){this.timer||(this.refreshNow(),this.timer=setInterval(()=>{this.refreshNow()},this.opts.intervalMs??HB),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async refreshNow(){let e=this.opts.fetchImpl??fetch,t=new Set(this.store.list().map(r=>r.name));for(let r of[...this.perPeer.keys()])t.has(r)||this.perPeer.delete(r);await Promise.allSettled(this.store.list().map(async r=>{let s=this.store.get(r.name);if(!s)return;let o=this.perPeer.get(r.name),i=Vt(s.host)?"http":"https",a=new URLSearchParams({includeNonInteractive:"1"}),d=o?.cursor!==void 0;d&&a.set("since",String(o.cursor));let c=`${i}://${s.host}:${s.port}/v1/sessions?${a.toString()}`,l;try{l=await e(c,{headers:{Authorization:`Bearer ${s.token}`}})}catch{return}if(!l.ok)return;let u=await l.json(),f=o?.sessions??new Map;if(d){for(let[p,m]of[...f])m.status!=="cold"&&f.delete(p);for(let p of u.removed??[])f.delete(ko({name:r.name,localId:p}))}else f.clear();for(let p of u.sessions??[]){let m=ko({name:r.name,localId:String(p.sessionId)});f.set(m,{...p,sessionId:m,remote:r.name})}this.perPeer.set(r.name,{cursor:u.cursor,sessions:f})}))}list(e){let t=[];for(let r of this.perPeer.values())t.push(...r.sessions.values());return t.filter(r=>!(e.status&&r.status!==e.status||!e.includeNonInteractive&&r.interactive!==!0))}findByLocalId(e){let t=e.startsWith(sn)?[e]:[e,sn+e],r=[];for(let[s,o]of this.perPeer)for(let i of t)if(o.sessions.has(ko({name:s,localId:i}))){r.push({name:s,localId:i});break}return r}};async function AA(n,e,t,r=fetch){let s=n.get(e);if(!s)return{status:404,body:{error:`No remote named "${e}". Run \`hydra remote add\` first.`}};let i=`${Vt(s.host)?"http":"https"}://${s.host}:${s.port}/v1/sessions`,a;try{a=await r(i,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(u){return{status:502,body:{error:`Could not reach remote "${e}" (${s.host}:${s.port}): ${u.message}`}}}let d=await a.text(),c=null;try{c=d.length>0?JSON.parse(d):null}catch{c=null}if(!a.ok)return{status:a.status,body:c};let l=c;return l&&typeof l.sessionId=="string"?{status:a.status,body:{...l,sessionId:ko({name:e,localId:l.sessionId})}}:{status:a.status,body:c}}async function TA(n,e,t=fetch){let r;if(e.sessionIds===void 0)r=n.list().map(a=>({name:a.name}));else{let a=new Map;for(let d of e.sessionIds){let c=Ds(d);if(!c)continue;let l=a.get(c.name)??[];l.push(c.localId),a.set(c.name,l)}r=[...a.entries()].map(([d,c])=>({name:d,sessionIds:c}))}if(r.length===0)return{query:e.q,truncated:!1,results:[]};let s=await Promise.all(r.map(async a=>{let d=n.get(a.name);if(!d)return null;let l=`${Vt(d.host)?"http":"https"}://${d.host}:${d.port}/v1/sessions/search`,u;try{u=await t(l,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({q:e.q,...a.sessionIds?{sessionIds:a.sessionIds}:{},...e.snippetWidth!==void 0?{snippetWidth:e.snippetWidth}:{}})})}catch{return null}if(!u.ok)return null;let f;try{f=await u.json()}catch{return null}let p=f;if(!p||!Array.isArray(p.results))return null;let m=p.results.map(h=>({...h,sessionId:ko({name:a.name,localId:h.sessionId})}));return{query:e.q,truncated:p.truncated===!0,results:m}})),o=[],i=!1;for(let a of s)a!==null&&(o.push(...a.results),i=i||a.truncated);return{query:e.q,truncated:i,results:o}}function UB(n){return n==="1"||n==="true"||n===!0}function WB(n,e,t,r){let s=n.replace(/:([A-Za-z_]+)/g,(i,a)=>encodeURIComponent(a==="id"?t:e[a]??"")),o=r.indexOf("?");return o===-1?s:s+r.slice(o)}var Mh=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function EA(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Vt(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function MA(n,e,t,r={},s,o){n.get("/v1/sessions",async(u,f)=>{let p=u.query,m=p?.includeNonInteractive==="1"||p?.includeNonInteractive==="true",h;if(p?.since!==void 0&&(h=Number(p.since),!Number.isFinite(h)||h<0))return f.code(400).send({error:`since must be a non-negative number, got ${JSON.stringify(p.since)}`});let g=p?.status==="warm"||p?.status==="cold"?p.status:void 0,w={cwd:p?.cwd,includeNonInteractive:m,...g?{status:g}:{}},b=o&&!w.cwd?o.list({includeNonInteractive:m,...g?{status:g}:{}}):[];if(h!==void 0){let S=await e.listSince(w,h);return{sessions:[...S.entries,...b],removed:S.removed,cursor:S.cursor}}let k=await e.listing(w);return{sessions:[...k.entries,...b],removed:[],cursor:k.cursor}}),n.get("/v1/sessions/:id",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=await e.getOne(m);return h||(f.code(404).send({error:"session not found"}),f)}),n.post("/v1/sessions/search",async(u,f)=>{let p=u.body??{},m=typeof p.q=="string"?p.q:"";if(m.trim().length===0)return f.code(400).send({error:"q is required"}),f;let h=Array.isArray(p.sessionIds)?p.sessionIds.filter(k=>typeof k=="string"&&k.length>0):void 0,g={sessionIds:h};typeof p.snippetWidth=="number"&&(g.snippetWidth=p.snippetWidth);let w=await xA(e,m,g);if(!s)return w;let b=await TA(s,{q:m,...h?{sessionIds:h}:{},...g.snippetWidth!==void 0?{snippetWidth:g.snippetWidth}:{}});return{query:m,truncated:w.truncated||b.truncated,results:[...w.results,...b.results]}}),n.post("/v1/sessions",async(u,f)=>{let p=u.body??{};if(p.remote){if(!s)return f.code(404).send({error:`No remote named "${p.remote}". Run \`hydra remote add\` first.`});let k=await AA(s,p.remote,{cwd:p.cwd,agentId:p.agentId,mcpServers:p.mcpServers,workspace:p.workspace});return f.code(k.status).send(k.body)}let m=mt(p.cwd??t.cwd),h=await $d(m),g=p.agentId??h.agentId??t.agentId,w=Pc(r),b=w!==void 0?[...p.mcpServers??[],...w.descriptors]:p.mcpServers;try{let k=await e.create({cwd:m,agentId:g,mcpServers:b,...p.workspace!==void 0?{workspace:p.workspace}:{}});w!==void 0&&w.bindToSession(k),f.code(201).send({sessionId:k.sessionId,agentId:k.agentId,cwd:k.cwd,...k.workspace!==void 0?{workspace:k.workspace}:{},...k.workspaceError!==void 0?{workspaceError:k.workspaceError}:{}})}catch(k){w!==void 0&&w.abandon(k instanceof Error?k:void 0),f.code(500).send({error:k.message})}}),n.post("/v1/sessions/collect",async(u,f)=>{let p=u.body??{},m=typeof p.maxAgeDays=="number"&&p.maxAgeDays>0?p.maxAgeDays*24*60*60*1e3:0,h=typeof p.limit=="number"&&p.limit>0?p.limit:1e3,g=p.selection==="explicit"||p.selection==="unpromoted"?p.selection:"unpromoted";try{let w=await kb({manager:e,maxAgeMs:m,maxDeletions:h,selection:g,verbose:!1});f.code(200).send(w)}catch(w){f.code(500).send({error:w.message})}}),n.post("/v1/sessions/:id/kill",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(h){h.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),f.code(202).send();return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}f.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(!h)return f.code(404).send({error:"session not found"}),f;let g=u.body??{},w={};(g.mode==="memory"||g.mode==="file")&&(w.mode=g.mode),typeof g.capacityBytes=="number"&&(w.capacityBytes=g.capacityBytes),typeof g.fileCapBytes=="number"&&(w.fileCapBytes=g.fileCapBytes),(w.mode??"memory")==="file"&&(w.filePathFor=b=>_h.join(PA.tmpdir(),`hydra-acp-stdin-${b}.log`));try{return h.openStream(w)}catch(b){return f.code(409).send({error:b.message}),f}}),n.post("/v1/sessions/:id/stdin",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(!h)return f.code(404).send({error:"session not found"}),f;let g=u.body??{},w=typeof g.chunk=="string"?g.chunk:"",b=g.eof===!0;try{return h.streamWrite(w,b)}catch(k){return f.code(409).send({error:k.message}),f}}),n.patch("/v1/sessions/:id",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.body??{};if(h.cwd!==void 0){if(typeof h.cwd!="string"||!_h.isAbsolute(h.cwd)){f.code(400).send({error:"cwd must be an absolute path"});return}let w=await e.setCwd(m,h.cwd);if(w==="missing"){f.code(404).send({error:"session not found"});return}if(w==="not-a-directory"){f.code(400).send({error:`${h.cwd} is not a directory`});return}if(w==="live"){f.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(w==="bound"){f.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}f.code(204).send();return}if("workspace"in h){if(h.workspace!==null){f.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let w=await e.clearWorkspaceBinding(m);if(w==="missing"){f.code(404).send({error:"session not found"});return}if(w==="live"){f.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}f.code(204).send();return}if(h.priority!==void 0){let w=h.priority,b;if(w===null||w===0)b=void 0;else if(typeof w=="number"&&Number.isInteger(w)&&w>0)b=w;else{f.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(m,b)){f.code(404).send({error:"session not found"});return}f.code(204).send();return}if(h.regen===!0){if(!(e.get(m)!==void 0||await e.hasRecord(m))){f.code(404).send({error:"session not found"});return}e.scheduleSynopsis(m),f.code(202).send();return}if(typeof h.title!="string"||h.title.trim().length===0){f.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(m,h.title)){f.code(404).send({error:"session not found"});return}f.code(204).send()}),n.delete("/v1/sessions/:id",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(h){await h.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(m),await e.hasRecord(m)&&await e.deleteRecord(m),f.code(204).send();return}if(!await e.deleteRecord(m)){f.code(404).send({error:"session not found"});return}f.code(204).send()}),n.get("/v1/sessions/:id/export",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.query?.tools,g=h==="references"?"references":SR(h),w=await e.exportBundle(m,g==="references"?{tools:"references"}:{});if(!w){f.code(404).send({error:"session not found"});return}let b=lu({record:w.record,history:g==="summary"?xR(w.history,"summary"):w.history,promptHistory:w.promptHistory.length>0?w.promptHistory:void 0,...w.toolBlobs!==void 0?{toolBlobs:w.toolBlobs}:{},hydraVersion:Ue,machine:ri(),hydraHost:EA(t)}),k=new Date().toISOString().replace(/[:.]/g,"-");f.header("Content-Disposition",`attachment; filename="${m}-${k}.hydra"`),f.code(200).send(b)}),n.get("/v1/sessions/:id/diff",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=await e.exportBundle(m);if(!h){f.code(404).send({error:"session not found"});return}let g=u.query??{},w=g.fold==="true"||g.fold==="1",b=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(S=>S.trim()).filter(S=>S.length>0)):void 0,k=Ac(h.history);b&&(k=k.filter(S=>b.has(S.path))),w&&(k=k.map(S=>({...S,hunks:Tc(S.hunks)}))),f.code(200).send(k)}),n.get("/v1/sessions/:id/tools/:hash",async(u,f)=>{let p=u.params,m=await e.resolveCanonicalId(p.id)??p.id,h=await e.loadToolBlob(m,p.hash);if(h===null){f.code(404).send({error:"tool blob not found"});return}f.header("Content-Type","text/plain; charset=utf-8"),f.code(200).send(h)}),n.get("/v1/sessions/:id/transcript",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=await e.exportBundle(m);if(!h){f.code(404).send({error:"session not found"});return}let g=lu({record:h.record,history:h.history,promptHistory:h.promptHistory.length>0?h.promptHistory:void 0,hydraVersion:Ue,machine:ri(),hydraHost:EA(t)}),w=u.query,b=I=>I==="1"||I==="true"||I==="yes",k=I=>{let x=w?.[I];if(x===void 0||x==="")return;let A=Number(x);return Number.isFinite(A)?A:"bad"},S={};for(let I of["from","to","last","since"]){let x=k(I);if(x==="bad"){f.code(400).send({error:`${I} must be a number`});return}x!==void 0&&(S[I==="since"?"sinceMs":I]=x)}f.header("Content-Type","text/markdown; charset=utf-8"),f.code(200).send(Rh(g,{includeTools:b(w?.tools),includeThoughts:b(w?.thoughts),...S}))}),n.post("/v1/sessions/:id/fork",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.body??{},g={};if(h.forkAt!==void 0){if(typeof h.forkAt!="string"||h.forkAt.length===0){f.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=h.forkAt}if(h.cwd!==void 0){if(typeof h.cwd!="string"||h.cwd.length===0){f.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=mt(h.cwd)}if(h.agentId!==void 0){if(typeof h.agentId!="string"||h.agentId.length===0){f.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=h.agentId}if(h.title!==void 0){if(typeof h.title!="string"){f.code(400).send({error:"title must be a string"});return}g.title=h.title}if(h.mode!==void 0){if(h.mode!=="verbatim"&&h.mode!=="synthesis"){f.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=h.mode}if(h.model!==void 0){if(typeof h.model!="string"||h.model.length===0){f.code(400).send({error:"model must be a non-empty string"});return}g.model=h.model}try{let w=await e.forkSession(m,g);f.code(201).send(w)}catch(w){let b=w;if(b.code===G.SessionNotFound){f.code(404).send({error:b.message});return}if(b.code===G.InvalidParams||b.code===G.AgentNotInstalled){f.code(400).send({error:b.message});return}f.code(500).send({error:b.message})}}),n.post("/v1/sessions/import",async(u,f)=>{let p=u.body??{};if(p.bundle===void 0){f.code(400).send({error:"missing bundle"});return}let m;if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){f.code(400).send({error:"cwd must be a non-empty string"});return}m=p.cwd}let h;try{h=as(p.bundle)}catch(g){f.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(h,{replace:p.replace===!0,...m!==void 0?{cwd:m}:{}});f.code(201).send(g)}catch(g){let w=g;if(w.code===G.BundleAlreadyImported){f.code(409).send({error:"bundle already imported",existingSessionId:w.existingSessionId});return}f.code(500).send({error:w.message})}}),n.get("/v1/sessions/:id/compact/status",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m),g;if(h?g=h.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(m),g===void 0&&!await e.hasRecord(m))return f.code(404).send({error:"session not found"}),f;let w=await e.getCompactionState(m),b=await e.getRollbackBreadcrumb(m),k=await e.getPendingAgentSwap(m),S=!1,I,x=h?.currentUsage,A=typeof x?.used=="number"&&typeof x?.size=="number"&&x.size>0?{used:x.used,size:x.size}:void 0,_=await e.loadHistory(m,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(_.length>0&&t.compaction){let P=g??0,$=_.length,F=P<=_.length?P:0,J=_.slice(F),Y=nA(J);I=vb(Y);let W=h?.currentModel,Z=_.at(-1).recordedAt;S=rA({summarizedThroughEntry:P,totalEntries:$,unsummarizedChars:Y,compactionInFlight:e.getCompactionInFlight(),currentModel:W,lastActivityMs:Z,nowMs:Date.now(),config:t.compaction,...typeof x?.used=="number"?{agentReportedUsed:x.used}:{},...typeof x?.size=="number"?{agentReportedSize:x.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:S,...I!=null?{approxTokens:I}:{},...A!=null?{currentUsage:A}:{},...w!=null?{compactionState:w}:{},...b!=null?{rollbackBreadcrumb:b}:{},...k!=null?{pendingAgentSwap:k}:{}}}),n.post("/v1/sessions/:id/compact",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p;if(e.get(m)){e.scheduleCompaction(m),f.code(202).send({scheduled:!0});return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}e.scheduleCompaction(m),f.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p;if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}try{await e.performUncompact(m),f.code(202).send({rolledBack:!0})}catch(h){let g=h instanceof Error?h.message:String(h);f.code(409).send({error:g})}}),n.post("/v1/sessions/:id/workspace/clean",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.body??{};if(h.deep!==void 0&&typeof h.deep!="boolean"){f.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}if(e.get(m)===void 0){f.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let g=await e.runWorkspaceAction(m,"clean",void 0,{deep:h.deep===!0});f.code(202).send({report:g})}catch(g){f.code(409).send({error:g instanceof Error?g.message:String(g)})}}),n.get("/v1/sessions/:id/history",async(u,f)=>{let p=u.params.id,m=u.query,h=m?.follow==="1"||m?.follow==="true",g=await e.resolveCanonicalId(p)??p,w=e.get(g),b,k,S=!1,I=1e4,x=[];if(w){h&&(k=w.onBroadcast(_=>{f.raw.writableEnded||(S?f.raw.write(JSON.stringify(_)+`
|
|
402
|
+
`))n.push(o);n.push(s)}function Su(n){return n.replace(new RegExp(gA,"g"),e=>e.replace(/</g,"<").replace(/>/g,">"))}function Ab(n){return n.toLocaleString("en-US")}fn();dr();Ts();Eh();Od();import{randomBytes as CA}from"crypto";function IA(n){let e=CA(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 Tb(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async r=>{let s=[...n.baselineMcpServers??[]];n.stdinEnabled&&s.push(IA({name:"hydra-acp-stdin",session:r,tokenRegistry:e,getOrigin:t})),s.push(IA({name:"hydra-acp-recall",session:r,tokenRegistry:e,getOrigin:t}));let o=Pc(n.deps);return o!==void 0&&(o.bindToSession(r),s=[...s,...o.descriptors]),s}}function Pc(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=CA(32).toString("hex"),r=n.mcpTokenRegistry.reserve(t),s=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${s}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{r.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>r.abandon(a)}}rt();Ts();Gl();ir();var BB=new Set(["/v1/sessions/:id/history","/v1/sessions/:id/events"]);function RA(n,e){let t=e.fetchImpl??fetch;n.addHook("preHandler",async(r,s)=>{let o=r.routeOptions.url;if(!o||!o.startsWith("/v1/sessions/:id"))return;let i=r.params,a=i.id;if(typeof a!="string")return;let d=Bs(a);if(!d){if(!e.localMiss||await e.localMiss.resolvesLocally(a))return;let w=e.localMiss.cache.findByLocalId(a);if(w.length===0)return;if(w.length>1){s.code(404).send({error:`Session "${a}" exists on more than one remote (${w.map(b=>b.name).join(", ")}). Address it as "<remote>:${a}".`});return}d=w[0]}let c=e.store.get(d.name);if(!c){s.code(404).send({error:`No remote named "${d.name}". Run \`hydra remote add\` first.`});return}let l=r.query;if(BB.has(o)&&UB(l?.follow)){let w=c.port===An?"":`:${c.port}`;s.code(501).send({error:`Streaming a federated session isn't supported yet. Attach directly with hydra://${c.host}${w}/${d.localId} instead.`});return}let u=WB(o,i,d.localId,r.url),p=`${Vt(c.host)?"http":"https"}://${c.host}:${c.port}${u}`,m;try{m=await t(p,{method:r.method,headers:{Authorization:`Bearer ${c.token}`,...r.body!==void 0?{"Content-Type":"application/json"}:{}},...r.body!==void 0&&r.method!=="GET"?{body:JSON.stringify(r.body)}:{}})}catch(w){s.code(502).send({error:`Could not reach remote "${d.name}" (${c.host}:${c.port}): ${w.message}`});return}if(r.method==="DELETE"&&o==="/v1/sessions/:id"&&(m.ok||m.status===404)&&e.localMiss?.cache.evict(d.name,d.localId),m.status===204){s.code(204).send();return}let h=await m.text(),g=m.headers.get("content-type");g&&s.header("content-type",g),s.code(m.status).send(h)})}var HB=5e3,Ph=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;perPeer=new Map;timer;start(){this.timer||(this.refreshNow(),this.timer=setInterval(()=>{this.refreshNow()},this.opts.intervalMs??HB),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async refreshNow(){let e=this.opts.fetchImpl??fetch,t=new Set(this.store.list().map(r=>r.name));for(let r of[...this.perPeer.keys()])t.has(r)||this.perPeer.delete(r);await Promise.allSettled(this.store.list().map(async r=>{let s=this.store.get(r.name);if(!s)return;let o=this.perPeer.get(r.name),i=Vt(s.host)?"http":"https",a=new URLSearchParams({includeNonInteractive:"1"}),d=o?.cursor!==void 0;d&&a.set("since",String(o.cursor));let c=`${i}://${s.host}:${s.port}/v1/sessions?${a.toString()}`,l;try{l=await e(c,{headers:{Authorization:`Bearer ${s.token}`}})}catch{return}if(!l.ok)return;let u=await l.json(),f=o?.sessions??new Map;if(d){for(let[p,m]of[...f])m.status!=="cold"&&f.delete(p);for(let p of u.removed??[])f.delete(Ds({name:r.name,localId:p}))}else f.clear();for(let p of u.sessions??[]){let m=Ds({name:r.name,localId:String(p.sessionId)});f.set(m,{...p,sessionId:m,remote:r.name})}this.perPeer.set(r.name,{cursor:u.cursor,sessions:f})}))}list(e){let t=[];for(let r of this.perPeer.values())t.push(...r.sessions.values());return t.filter(r=>!(e.status&&r.status!==e.status||!e.includeNonInteractive&&r.interactive!==!0))}evict(e,t){this.perPeer.get(e)?.sessions.delete(Ds({name:e,localId:t}))}findByLocalId(e){let t=e.startsWith(sn)?[e]:[e,sn+e],r=[];for(let[s,o]of this.perPeer)for(let i of t)if(o.sessions.has(Ds({name:s,localId:i}))){r.push({name:s,localId:i});break}return r}};async function AA(n,e,t,r=fetch){let s=n.get(e);if(!s)return{status:404,body:{error:`No remote named "${e}". Run \`hydra remote add\` first.`}};let i=`${Vt(s.host)?"http":"https"}://${s.host}:${s.port}/v1/sessions`,a;try{a=await r(i,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(u){return{status:502,body:{error:`Could not reach remote "${e}" (${s.host}:${s.port}): ${u.message}`}}}let d=await a.text(),c=null;try{c=d.length>0?JSON.parse(d):null}catch{c=null}if(!a.ok)return{status:a.status,body:c};let l=c;return l&&typeof l.sessionId=="string"?{status:a.status,body:{...l,sessionId:Ds({name:e,localId:l.sessionId})}}:{status:a.status,body:c}}async function TA(n,e,t=fetch){let r;if(e.sessionIds===void 0)r=n.list().map(a=>({name:a.name}));else{let a=new Map;for(let d of e.sessionIds){let c=Bs(d);if(!c)continue;let l=a.get(c.name)??[];l.push(c.localId),a.set(c.name,l)}r=[...a.entries()].map(([d,c])=>({name:d,sessionIds:c}))}if(r.length===0)return{query:e.q,truncated:!1,results:[]};let s=await Promise.all(r.map(async a=>{let d=n.get(a.name);if(!d)return null;let l=`${Vt(d.host)?"http":"https"}://${d.host}:${d.port}/v1/sessions/search`,u;try{u=await t(l,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({q:e.q,...a.sessionIds?{sessionIds:a.sessionIds}:{},...e.snippetWidth!==void 0?{snippetWidth:e.snippetWidth}:{}})})}catch{return null}if(!u.ok)return null;let f;try{f=await u.json()}catch{return null}let p=f;if(!p||!Array.isArray(p.results))return null;let m=p.results.map(h=>({...h,sessionId:Ds({name:a.name,localId:h.sessionId})}));return{query:e.q,truncated:p.truncated===!0,results:m}})),o=[],i=!1;for(let a of s)a!==null&&(o.push(...a.results),i=i||a.truncated);return{query:e.q,truncated:i,results:o}}function UB(n){return n==="1"||n==="true"||n===!0}function WB(n,e,t,r){let s=n.replace(/:([A-Za-z_]+)/g,(i,a)=>encodeURIComponent(a==="id"?t:e[a]??"")),o=r.indexOf("?");return o===-1?s:s+r.slice(o)}var Mh=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function EA(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Vt(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function MA(n,e,t,r={},s,o){n.get("/v1/sessions",async(u,f)=>{let p=u.query,m=p?.includeNonInteractive==="1"||p?.includeNonInteractive==="true",h;if(p?.since!==void 0&&(h=Number(p.since),!Number.isFinite(h)||h<0))return f.code(400).send({error:`since must be a non-negative number, got ${JSON.stringify(p.since)}`});let g=p?.status==="warm"||p?.status==="cold"?p.status:void 0,w={cwd:p?.cwd,includeNonInteractive:m,...g?{status:g}:{}},b=o&&!w.cwd?o.list({includeNonInteractive:m,...g?{status:g}:{}}):[];if(h!==void 0){let S=await e.listSince(w,h);return{sessions:[...S.entries,...b],removed:S.removed,cursor:S.cursor}}let k=await e.listing(w);return{sessions:[...k.entries,...b],removed:[],cursor:k.cursor}}),n.get("/v1/sessions/:id",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=await e.getOne(m);return h||(f.code(404).send({error:"session not found"}),f)}),n.post("/v1/sessions/search",async(u,f)=>{let p=u.body??{},m=typeof p.q=="string"?p.q:"";if(m.trim().length===0)return f.code(400).send({error:"q is required"}),f;let h=Array.isArray(p.sessionIds)?p.sessionIds.filter(k=>typeof k=="string"&&k.length>0):void 0,g={sessionIds:h};typeof p.snippetWidth=="number"&&(g.snippetWidth=p.snippetWidth);let w=await xA(e,m,g);if(!s)return w;let b=await TA(s,{q:m,...h?{sessionIds:h}:{},...g.snippetWidth!==void 0?{snippetWidth:g.snippetWidth}:{}});return{query:m,truncated:w.truncated||b.truncated,results:[...w.results,...b.results]}}),n.post("/v1/sessions",async(u,f)=>{let p=u.body??{};if(p.remote){if(!s)return f.code(404).send({error:`No remote named "${p.remote}". Run \`hydra remote add\` first.`});let k=await AA(s,p.remote,{cwd:p.cwd,agentId:p.agentId,mcpServers:p.mcpServers,workspace:p.workspace});return f.code(k.status).send(k.body)}let m=mt(p.cwd??t.cwd),h=await $d(m),g=p.agentId??h.agentId??t.agentId,w=Pc(r),b=w!==void 0?[...p.mcpServers??[],...w.descriptors]:p.mcpServers;try{let k=await e.create({cwd:m,agentId:g,mcpServers:b,...p.workspace!==void 0?{workspace:p.workspace}:{}});w!==void 0&&w.bindToSession(k),f.code(201).send({sessionId:k.sessionId,agentId:k.agentId,cwd:k.cwd,...k.workspace!==void 0?{workspace:k.workspace}:{},...k.workspaceError!==void 0?{workspaceError:k.workspaceError}:{}})}catch(k){w!==void 0&&w.abandon(k instanceof Error?k:void 0),f.code(500).send({error:k.message})}}),n.post("/v1/sessions/collect",async(u,f)=>{let p=u.body??{},m=typeof p.maxAgeDays=="number"&&p.maxAgeDays>0?p.maxAgeDays*24*60*60*1e3:0,h=typeof p.limit=="number"&&p.limit>0?p.limit:1e3,g=p.selection==="explicit"||p.selection==="unpromoted"?p.selection:"unpromoted";try{let w=await kb({manager:e,maxAgeMs:m,maxDeletions:h,selection:g,verbose:!1});f.code(200).send(w)}catch(w){f.code(500).send({error:w.message})}}),n.post("/v1/sessions/:id/kill",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(h){h.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),f.code(202).send();return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}f.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(!h)return f.code(404).send({error:"session not found"}),f;let g=u.body??{},w={};(g.mode==="memory"||g.mode==="file")&&(w.mode=g.mode),typeof g.capacityBytes=="number"&&(w.capacityBytes=g.capacityBytes),typeof g.fileCapBytes=="number"&&(w.fileCapBytes=g.fileCapBytes),(w.mode??"memory")==="file"&&(w.filePathFor=b=>_h.join(PA.tmpdir(),`hydra-acp-stdin-${b}.log`));try{return h.openStream(w)}catch(b){return f.code(409).send({error:b.message}),f}}),n.post("/v1/sessions/:id/stdin",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(!h)return f.code(404).send({error:"session not found"}),f;let g=u.body??{},w=typeof g.chunk=="string"?g.chunk:"",b=g.eof===!0;try{return h.streamWrite(w,b)}catch(k){return f.code(409).send({error:k.message}),f}}),n.patch("/v1/sessions/:id",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.body??{};if(h.cwd!==void 0){if(typeof h.cwd!="string"||!_h.isAbsolute(h.cwd)){f.code(400).send({error:"cwd must be an absolute path"});return}let w=await e.setCwd(m,h.cwd);if(w==="missing"){f.code(404).send({error:"session not found"});return}if(w==="not-a-directory"){f.code(400).send({error:`${h.cwd} is not a directory`});return}if(w==="live"){f.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(w==="bound"){f.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}f.code(204).send();return}if("workspace"in h){if(h.workspace!==null){f.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let w=await e.clearWorkspaceBinding(m);if(w==="missing"){f.code(404).send({error:"session not found"});return}if(w==="live"){f.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}f.code(204).send();return}if(h.priority!==void 0){let w=h.priority,b;if(w===null||w===0)b=void 0;else if(typeof w=="number"&&Number.isInteger(w)&&w>0)b=w;else{f.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(m,b)){f.code(404).send({error:"session not found"});return}f.code(204).send();return}if(h.regen===!0){if(!(e.get(m)!==void 0||await e.hasRecord(m))){f.code(404).send({error:"session not found"});return}e.scheduleSynopsis(m),f.code(202).send();return}if(typeof h.title!="string"||h.title.trim().length===0){f.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(m,h.title)){f.code(404).send({error:"session not found"});return}f.code(204).send()}),n.delete("/v1/sessions/:id",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);if(h){await h.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(m),await e.hasRecord(m)&&await e.deleteRecord(m),f.code(204).send();return}if(!await e.deleteRecord(m)){f.code(404).send({error:"session not found"});return}f.code(204).send()}),n.get("/v1/sessions/:id/export",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.query?.tools,g=h==="references"?"references":SR(h),w=await e.exportBundle(m,g==="references"?{tools:"references"}:{});if(!w){f.code(404).send({error:"session not found"});return}let b=lu({record:w.record,history:g==="summary"?xR(w.history,"summary"):w.history,promptHistory:w.promptHistory.length>0?w.promptHistory:void 0,...w.toolBlobs!==void 0?{toolBlobs:w.toolBlobs}:{},hydraVersion:Ue,machine:ri(),hydraHost:EA(t)}),k=new Date().toISOString().replace(/[:.]/g,"-");f.header("Content-Disposition",`attachment; filename="${m}-${k}.hydra"`),f.code(200).send(b)}),n.get("/v1/sessions/:id/diff",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=await e.exportBundle(m);if(!h){f.code(404).send({error:"session not found"});return}let g=u.query??{},w=g.fold==="true"||g.fold==="1",b=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(S=>S.trim()).filter(S=>S.length>0)):void 0,k=Ac(h.history);b&&(k=k.filter(S=>b.has(S.path))),w&&(k=k.map(S=>({...S,hunks:Tc(S.hunks)}))),f.code(200).send(k)}),n.get("/v1/sessions/:id/tools/:hash",async(u,f)=>{let p=u.params,m=await e.resolveCanonicalId(p.id)??p.id,h=await e.loadToolBlob(m,p.hash);if(h===null){f.code(404).send({error:"tool blob not found"});return}f.header("Content-Type","text/plain; charset=utf-8"),f.code(200).send(h)}),n.get("/v1/sessions/:id/transcript",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=await e.exportBundle(m);if(!h){f.code(404).send({error:"session not found"});return}let g=lu({record:h.record,history:h.history,promptHistory:h.promptHistory.length>0?h.promptHistory:void 0,hydraVersion:Ue,machine:ri(),hydraHost:EA(t)}),w=u.query,b=I=>I==="1"||I==="true"||I==="yes",k=I=>{let x=w?.[I];if(x===void 0||x==="")return;let A=Number(x);return Number.isFinite(A)?A:"bad"},S={};for(let I of["from","to","last","since"]){let x=k(I);if(x==="bad"){f.code(400).send({error:`${I} must be a number`});return}x!==void 0&&(S[I==="since"?"sinceMs":I]=x)}f.header("Content-Type","text/markdown; charset=utf-8"),f.code(200).send(Rh(g,{includeTools:b(w?.tools),includeThoughts:b(w?.thoughts),...S}))}),n.post("/v1/sessions/:id/fork",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.body??{},g={};if(h.forkAt!==void 0){if(typeof h.forkAt!="string"||h.forkAt.length===0){f.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=h.forkAt}if(h.cwd!==void 0){if(typeof h.cwd!="string"||h.cwd.length===0){f.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=mt(h.cwd)}if(h.agentId!==void 0){if(typeof h.agentId!="string"||h.agentId.length===0){f.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=h.agentId}if(h.title!==void 0){if(typeof h.title!="string"){f.code(400).send({error:"title must be a string"});return}g.title=h.title}if(h.mode!==void 0){if(h.mode!=="verbatim"&&h.mode!=="synthesis"){f.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=h.mode}if(h.model!==void 0){if(typeof h.model!="string"||h.model.length===0){f.code(400).send({error:"model must be a non-empty string"});return}g.model=h.model}try{let w=await e.forkSession(m,g);f.code(201).send(w)}catch(w){let b=w;if(b.code===G.SessionNotFound){f.code(404).send({error:b.message});return}if(b.code===G.InvalidParams||b.code===G.AgentNotInstalled){f.code(400).send({error:b.message});return}f.code(500).send({error:b.message})}}),n.post("/v1/sessions/import",async(u,f)=>{let p=u.body??{};if(p.bundle===void 0){f.code(400).send({error:"missing bundle"});return}let m;if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){f.code(400).send({error:"cwd must be a non-empty string"});return}m=p.cwd}let h;try{h=as(p.bundle)}catch(g){f.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(h,{replace:p.replace===!0,...m!==void 0?{cwd:m}:{}});f.code(201).send(g)}catch(g){let w=g;if(w.code===G.BundleAlreadyImported){f.code(409).send({error:"bundle already imported",existingSessionId:w.existingSessionId});return}f.code(500).send({error:w.message})}}),n.get("/v1/sessions/:id/compact/status",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m),g;if(h?g=h.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(m),g===void 0&&!await e.hasRecord(m))return f.code(404).send({error:"session not found"}),f;let w=await e.getCompactionState(m),b=await e.getRollbackBreadcrumb(m),k=await e.getPendingAgentSwap(m),S=!1,I,x=h?.currentUsage,A=typeof x?.used=="number"&&typeof x?.size=="number"&&x.size>0?{used:x.used,size:x.size}:void 0,_=await e.loadHistory(m,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(_.length>0&&t.compaction){let P=g??0,$=_.length,F=P<=_.length?P:0,J=_.slice(F),Y=nA(J);I=vb(Y);let W=h?.currentModel,Z=_.at(-1).recordedAt;S=rA({summarizedThroughEntry:P,totalEntries:$,unsummarizedChars:Y,compactionInFlight:e.getCompactionInFlight(),currentModel:W,lastActivityMs:Z,nowMs:Date.now(),config:t.compaction,...typeof x?.used=="number"?{agentReportedUsed:x.used}:{},...typeof x?.size=="number"?{agentReportedSize:x.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:S,...I!=null?{approxTokens:I}:{},...A!=null?{currentUsage:A}:{},...w!=null?{compactionState:w}:{},...b!=null?{rollbackBreadcrumb:b}:{},...k!=null?{pendingAgentSwap:k}:{}}}),n.post("/v1/sessions/:id/compact",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p;if(e.get(m)){e.scheduleCompaction(m),f.code(202).send({scheduled:!0});return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}e.scheduleCompaction(m),f.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p;if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}try{await e.performUncompact(m),f.code(202).send({rolledBack:!0})}catch(h){let g=h instanceof Error?h.message:String(h);f.code(409).send({error:g})}}),n.post("/v1/sessions/:id/workspace/clean",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=u.body??{};if(h.deep!==void 0&&typeof h.deep!="boolean"){f.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}if(e.get(m)===void 0){f.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let g=await e.runWorkspaceAction(m,"clean",void 0,{deep:h.deep===!0});f.code(202).send({report:g})}catch(g){f.code(409).send({error:g instanceof Error?g.message:String(g)})}}),n.get("/v1/sessions/:id/history",async(u,f)=>{let p=u.params.id,m=u.query,h=m?.follow==="1"||m?.follow==="true",g=await e.resolveCanonicalId(p)??p,w=e.get(g),b,k,S=!1,I=1e4,x=[];if(w){h&&(k=w.onBroadcast(_=>{f.raw.writableEnded||(S?f.raw.write(JSON.stringify(_)+`
|
|
403
403
|
`):(x.push(_),x.length>I&&x.shift()))})),u.raw.on("close",()=>{k?.(),f.raw.writableEnded||f.raw.end()});try{b=await w.getHistorySnapshot()}catch(_){throw k?.(),_}}else{let _=await e.getHistory(g);if(_===void 0)return f.code(404).send({error:"session not found"}),f;b=_}f.raw.setHeader("Content-Type","application/x-ndjson"),f.raw.setHeader("Cache-Control","no-cache"),f.raw.statusCode=200;let A=new Set;for(let _ of b??[]){f.raw.write(JSON.stringify(_)+`
|
|
404
404
|
`);let P=_;typeof P.recordedAt=="number"&&A.add(String(P.recordedAt))}for(;x.length>0;){let _=x.splice(0,x.length);for(let P of _){let $=P,F=typeof $.recordedAt=="number"?String($.recordedAt):"";F&&A.has(F)||f.raw.write(JSON.stringify(P)+`
|
|
405
405
|
`)}}return S=!0,k||f.raw.end(),f});function i(u,f,p){let m=typeof u=="string"?u.trim():"";if(m.length===0)return null;let h;try{h=JSON.parse(m)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!h||typeof h!="object"||Array.isArray(h))return console.debug("events endpoint: skipping non-object JSONL line"),null;let g=h;if(typeof g.recordedAt!="number"||p!==void 0&&g.recordedAt<p||typeof g.params!="object"||g.params===null||Array.isArray(g.params))return null;let w=g.params;if(typeof w.update!="object"||w.update===null||Array.isArray(w.update))return null;let k=w.update.sessionUpdate;return typeof k!="string"||!f.has(k)?null:{recordedAt:g.recordedAt,entry:h}}function a(u,f,p){let h=f.params.update,g={sessionId:u,ts:new Date(f.recordedAt).toISOString(),kind:p,update:h};return h.messageId!==void 0&&h.messageId!==null&&(g.messageId=h.messageId),g}async function*d(u,f,p,m){for await(let h of f){let g=i(h,p,m);if(g){let w=g.entry.params.update.sessionUpdate;yield{ts:g.recordedAt,row:a(u,g.entry,w)}}}}async function c(u,f,p,m){let h=Pb.createInterface({input:Eb.createReadStream(f),crlfDelay:1/0}),g=d(u,h,p,m),w=await g.next(),b=w.done?null:w.value;return{sessionId:u,rl:h,gen:g,current:b,exhausted:b===null}}async function l(u){let f=await u.gen.next();f.done?(u.exhausted=!0,u.current=null):u.current=f.value}n.get("/v1/sessions/events",async(u,f)=>{let p=u.query,m=p.kinds;if(!m||m.trim().length===0)return f.code(400).send({error:"kinds parameter is required"}),f;let h=m.split(",").map(I=>I.trim());if(h.length===0)return f.code(400).send({error:"kinds parameter is required"}),f;for(let I of h)if(!Mh.has(I))return f.code(400).send({error:`kind "${I}" is not queryable; allowed kinds: ${[...Mh].join(", ")}`}),f;let g=new Set(h),w;if(p.since!==void 0&&p.since.trim().length>0){let I=new Date(p.since);if(isNaN(I.getTime()))return f.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),f;w=I.getTime()}let b=await e.list({includeNonInteractive:!0}),k=w!==void 0?b.filter(I=>new Date(I.updatedAt).getTime()>=w):b;f.raw.setHeader("content-type","application/x-ndjson"),f.raw.statusCode=200;let S=[];for(let I of k)try{let x=D.historyFile(I.sessionId),A=await c(I.sessionId,x,g,w);A.exhausted||S.push(A)}catch(x){if(x.code==="ENOENT")continue;throw x}u.raw.on("close",()=>{for(let I of S)try{I.rl.close()}catch{}f.raw.writableEnded||f.raw.end()});try{for(;S.length>0;){let I=-1,x=1/0;for(let _=0;_<S.length;_++){let P=S[_];P.current!==null&&P.current.ts<x&&(x=P.current.ts,I=_)}if(I===-1)break;let A=S[I];if(f.raw.write(JSON.stringify(A.current.row)+`
|
|
406
406
|
`),await l(A),A.exhausted){try{A.rl.close()}catch{}S.splice(I,1)}}}catch(I){for(let x of S)try{x.rl.close()}catch{}throw I}return f.raw.end(),f}),n.get("/v1/sessions/:id/events",async(u,f)=>{let p=u.params.id,m=u.query,h=await e.resolveCanonicalId(p)??p;if(!e.get(h)&&!await e.hasRecord(h))return f.code(404).send({error:"session not found"}),f;let w=m.kinds;if(!w||w.trim().length===0)return f.code(400).send({error:"kinds parameter is required"}),f;let b=w.split(",").map(_=>_.trim());if(b.length===0)return f.code(400).send({error:"kinds parameter is required"}),f;for(let _ of b)if(!Mh.has(_))return f.code(400).send({error:`kind "${_}" is not queryable; allowed kinds: ${[...Mh].join(", ")}`}),f;let k=new Set(b),S;if(m.since!==void 0&&m.since.trim().length>0){let _=new Date(m.since);if(isNaN(_.getTime()))return f.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),f;S=_.getTime()}let I=D.historyFile(h),x=Eb.createReadStream(I),A=Pb.createInterface({input:x,crlfDelay:1/0});f.raw.setHeader("content-type","application/x-ndjson"),f.raw.statusCode=200;try{for await(let _ of A){let P=typeof _=="string"?_.trim():"";if(P.length===0)continue;let $;try{$=JSON.parse(P)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",I);continue}if(!$||typeof $!="object"||Array.isArray($)){console.debug("events endpoint: skipping non-object JSONL line in %s",I);continue}let F=$;if(typeof F.recordedAt!="number"||typeof F.params!="object"||F.params===null||Array.isArray(F.params))continue;let J=F.params;if(typeof J.update!="object"||J.update===null||Array.isArray(J.update))continue;let Y=J.update,W=Y.sessionUpdate;if(typeof W!="string"||!k.has(W)||S!==void 0&&F.recordedAt<S)continue;let Z={ts:new Date(F.recordedAt).toISOString(),kind:W,update:Y};Y.messageId!==void 0&&Y.messageId!==null&&(Z.messageId=Y.messageId),f.raw.write(JSON.stringify(Z)+`
|
|
407
407
|
`)}}catch(_){if(_.code==="ENOENT")return f.raw.end(),f;throw _}return f.raw.end(),f}),n.post("/v1/sessions/:id/prompt/:messageId/notify",async(u,f)=>{let p=u.params,m=p.id,h=await e.resolveCanonicalId(m)??m,g=p.messageId,w=u.body,b=typeof w?.callbackUrl=="string"?w.callbackUrl:"",k=typeof w?.secret=="string"?w.secret:"";if(!g||!b||!k){f.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let S;try{S=new URL(b)}catch{f.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(S.protocol!=="https:"&&S.protocol!=="http:"){f.code(400).send({error:"callbackUrl must be http or https"});return}let I=e.get(h);if(!I){f.code(404).send({error:"session not found or not warm"});return}let x=I.registerTurnNotify(g,b,k);if(x.alreadyTerminal){f.code(200).send({status:"already_terminal",stopReason:x.stopReason});return}f.code(202).send({status:"registered"})}),n.get("/v1/sessions/:id/attention",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,h=e.get(m);return!h&&!await e.hasRecord(m)?(f.code(404).send({error:"session not found"}),f):h?{flags:h.listAttentionFlags()}:{flags:(await e.store.read(m))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(u,f)=>{let p=u.query;if(!p.source||p.source.trim().length===0)return f.code(400).send({error:"source query parameter is required"}),f;let m=await e.list({includeNonInteractive:!0}),h=[];for(let g of m){let w=e.get(g.sessionId),b;w?b=w.listAttentionFlags():b=(await e.store.read(g.sessionId))?.attentionFlags??[];for(let k of b)k.source===p.source&&h.push({...k,sessionId:g.sessionId})}return{flags:h}}),n.post("/v1/sessions/:id/attention/clear",async(u,f)=>{let p=u.params.id,m=await e.resolveCanonicalId(p)??p,g=u.body??{},w=typeof g.source=="string"?g.source:"",b=typeof g.reason=="string"?g.reason:"";if((w.length>0||b.length>0)&&!(w.length>0&&b.length>0)){f.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}w.length===0&&b.length;let k=e.get(m);if(k){if(w.length>0&&b.length>0)k.clearAttentionFlag(w,b);else{let _=Array.from(k.listAttentionFlags()).map(P=>`${P.source}::${P.reason}`);for(let P of _)k.clearAttentionFlag(P.split("::")[0],P.split("::").slice(1).join("::"))}f.code(204).send();return}if(!await e.hasRecord(m)){f.code(404).send({error:"session not found"});return}let S=e.store,I=await S.read(m);if(!I){f.code(404).send({error:"session not found"});return}let x=I.attentionFlags??[],A;if(w.length>0&&b.length>0){let _=`${w}::${b}`;A=x.filter(P=>`${P.source}::${P.reason}`!==_)}else A=[];if(A.length===x.length&&A.every((_,P)=>_.source===x[P].source&&_.reason===x[P].reason)){f.code(204).send();return}await S.write({...I,attentionFlags:A}),f.code(204).send()})}Os();fn();function _A(n,e,t,r={}){n.get("/v1/agents",async()=>dc(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let s=await e.refresh();return{version:s.version,agentCount:s.agents.length}}),n.post("/v1/agents/:id/install",async(s,o)=>{let i=s.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.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 Ir(a,[],{npmRegistry:r.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(s,o)=>{let i=s.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);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===G.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}ke();function $A(n,e,t,r=()=>[]){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:D.home(),driftedKeys:r()}))}var jB=/^[A-Za-z0-9._-]+$/;function $h(n,e,t){let r=e==="extension"?"extensions":"transformers",s=`/v1/${r}`;n.get(s,async()=>({[r]:t.list()})),n.get(`${s}/:name`,async(o,i)=>{let a=o.params.name,d=t.get(a);if(!d){i.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(s,async(o,i)=>{let a=o.body??{},d=qB(a);if("error"in d){i.code(400).send({error:d.error});return}try{let c=t.register(d.config);i.code(201).send(c)}catch(c){xu(i,c)}}),n.delete(`${s}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(d){xu(i,d)}}),n.post(`${s}/:name/start`,async(o,i)=>{let a=o.params.name;try{let d=await t.startByName(a);i.code(200).send(d)}catch(d){xu(i,d)}}),n.post(`${s}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let d=await t.stopByName(a);i.code(200).send(d)}catch(d){xu(i,d)}}),n.post(`${s}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let d=await t.restartByName(a);i.code(200).send(d)}catch(d){xu(i,d)}})}function xu(n,e){let t=e.code,r=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:r});return}if(t==="CONFLICT"){n.code(409).send({error:r});return}n.code(500).send({error:r})}function qB(n){let e=n.name;if(typeof e!="string"||!jB.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let r=n.args;if(r!==void 0&&(!Array.isArray(r)||r.some(i=>typeof i!="string")))return{error:"args must be string[]"};let s=n.env;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))return{error:"env must be an object of string\u2192string"};if(s&&Object.values(s).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:r??[],env:s??{},enabled:o===void 0?!0:o}}}function OA(n,e){$h(n,"extension",e)}function FA(n,e){$h(n,"transformer",e)}function LA(n,e){n.get("/v1/config",async()=>e())}import{z as ui}from"zod";ke();import*as li from"fs/promises";import*as HA from"path";import{randomBytes as zB,scrypt as KB,timingSafeEqual as GB}from"crypto";import{promisify as JB}from"util";var UA=JB(KB);function Mb(){return HA.join(D.home(),"password-hash")}var NA=32768,DA=8,BA=1,VB=64,YB=16,WA=128*1024*1024;async function jA(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=zB(YB),t=await UA(n,e,VB,{N:NA,r:DA,p:BA,maxmem:WA}),r=`scrypt$${NA}$${DA}$${BA}$${e.toString("hex")}$${t.toString("hex")}
|
|
408
|
-
`;await li.mkdir(D.home(),{recursive:!0}),await li.writeFile(Mb(),r,{encoding:"utf8",mode:384})}async function Oh(){try{return(await li.readFile(Mb(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Fh(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await li.readFile(Mb(),"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 r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await UA(n,i,a.length,{N:r,r:s,p:o,maxmem:WA});return d.length!==a.length?!1:GB(d,a)}var QB=ui.object({password:ui.string().min(1),label:ui.string().min(1).max(256).optional(),ttlSec:ui.number().int().positive().optional()}),XB=ui.object({id:ui.string().optional()}).optional(),ZB=ui.object({token:ui.string().min(32)});function qA(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,r)=>{let s=eH(t);if(e.rateLimiter.isBlocked(s))return r.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=QB.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}if(!await Oh())return r.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Fh(o.password))return e.rateLimiter.recordFailure(s),r.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(s);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return r.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,r)=>{let s;try{s=XB.parse(t.body??void 0)}catch{return r.code(400).send({error:"Invalid request body"})}let o=s?.id??t.authIdentity;if(!o||o==="service")return r.code(200).send({revoked:!1});let i=await e.store.revoke(o);return r.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,r)=>r.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,r)=>r.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions",async(t,r)=>{let s=await e.store.revokeAll();return r.code(200).send({revoked:s})}),n.delete("/v1/auth/sessions/:id",async(t,r)=>{let s=t.params.id;return await e.store.revoke(s)?r.code(204).send():r.code(404).send({error:"Not found"})}),n.post("/v1/auth/rotate-token",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=ZB.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(s.token),r.code(200).send({rotated:!0})})}function eH(n){return n.ip||"unknown"}rt();import{z as fi}from"zod";ke();es();var _b=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,Lh=class n{data;constructor(e){this.data=e}static async load(){let e=await jt(D.peers());return new n(tH(e))}get(e){return this.data.entries[e]}async set(e){this.data.entries[e.name]=e,await zA(this.data)}async delete(e){return e in this.data.entries?(delete this.data.entries[e],await zA(this.data),!0):!1}list(){return Object.values(this.data.entries).map(({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})=>({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})).sort((e,t)=>e.addedAt.localeCompare(t.addedAt))}};function tH(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},r={};for(let[s,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||typeof i.host!="string"||typeof i.port!="number"||typeof i.token!="string"||typeof i.expiresAt!="string"||typeof i.addedAt!="string")continue;let a={name:i.name,host:i.host,port:i.port,token:i.token,expiresAt:i.expiresAt,addedAt:i.addedAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),r[s]=a}return{version:1,entries:r}}async function zA(n){await nn(D.peers(),n,{mode:384})}Ts();var nH=3600*24*365,js=class extends Error{status;constructor(e,t){super(e),this.name="PeerLoginError",this.status=t}};function KA(n,e){return`${Vt(n)?"http":"https"}://${n}:${e}`}async function GA(n){let e=n.fetchImpl??fetch,t=`${n.host}:${n.port}`,r=KA(n.host,n.port),s;try{s=await e(`${r}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n.password,label:n.label,ttlSec:n.ttlSec??nH})})}catch(i){throw new js(`Could not reach ${t}: ${i.message}`,502)}if(s.status===401)throw new js(`Wrong password for ${t}.`,401);if(s.status===403)throw new js(`No password is configured on ${t}. Run \`hydra-acp auth password\` on that daemon first.`,502);if(s.status===429)throw new js(`Too many failed login attempts on ${t}; try again later.`,429);if(!s.ok)throw new js(`Login to ${t} failed: HTTP ${s.status}`,502);let o=await s.json();if(!o.session_token||!o.expires_at)throw new js(`Login to ${t} returned a malformed response.`,502);return{token:o.session_token,expiresAt:o.expires_at}}async function JA(n){let e=n.fetchImpl??fetch,t=KA(n.host,n.port);try{await e(`${t}/v1/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch{}}Xo();var rH=fi.object({name:fi.string().min(1).max(64).regex(_b),host:fi.string().min(1),port:fi.number().int().positive().optional(),password:fi.string().min(1),label:fi.string().min(1).max(256).optional(),ttlSec:fi.number().int().positive().optional(),pinnedFingerprint:fi.string().min(1).optional()});function VA(n,e){n.post("/v1/remotes",async(t,r)=>{let s;try{s=rH.parse(t.body)}catch{return r.code(400).send({error:`Invalid request body (name must match ${_b} and the rest is a normal login request)`})}let o=s.port??An;s.pinnedFingerprint&&Yo(s.host,o,s.pinnedFingerprint);let i;try{i=await GA({host:s.host,port:o,password:s.password,label:s.label,ttlSec:s.ttlSec})}catch(c){if(c instanceof js)return r.code(c.status).send({error:c.message});throw c}let a=new Date().toISOString(),d={name:s.name,host:s.host,port:o,token:i.token,expiresAt:i.expiresAt,addedAt:a,...s.label!==void 0?{label:s.label}:{},...s.pinnedFingerprint!==void 0?{pinnedFingerprint:s.pinnedFingerprint,pinnedAt:a}:{}};return await e.store.set(d),e.health?.markOk(d.name),r.code(201).send({name:d.name,host:d.host,port:d.port,expiresAt:d.expiresAt,label:d.label,addedAt:d.addedAt,pinnedFingerprint:d.pinnedFingerprint,status:e.health?.get(d.name)?.status??"unknown"})}),n.get("/v1/remotes",async(t,r)=>{let s=e.store.list().map(o=>{let i=e.health?.get(o.name);return{...o,status:i?.status??"unknown",...i?.checkedAt?{lastCheckedAt:i.checkedAt}:{}}});return r.code(200).send({remotes:s})}),n.delete("/v1/remotes/:name",async(t,r)=>{let s=t.params.name,o=e.store.get(s);return o?(await JA({host:o.host,port:o.port,token:o.token}),await e.store.delete(s),e.health?.forget(s),e.store.list().some(a=>a.host===o.host&&a.port===o.port)||xy(o.host,o.port),r.code(204).send()):r.code(404).send({error:"Not found"})})}bo();Sa();qd();Ts();Gl();fn();var sH=new Set(["session/attach","session/detach","session/prompt","session/cancel","session/close","session/delete","hydra-acp/session/delete","session/set_model","session/set_mode","session/set_config_option","_session/steering","hydra-acp/prompt/cancel","hydra-acp/prompt/update","hydra-acp/prompt/amend","hydra-acp/session/tool_content","hydra-acp/session/force_cancel"]);function oH(n){return sH.has(n)}function QA(n,e,t,r){let s=[],o=a=>{for(let d of s)d(a)},i=(a,d)=>{e.handleLocalMessage(a,d,{connection:t.connection,clientId:r}).then(c=>c?n.send(c):void 0).catch(()=>{})};return n.onMessage(a=>{if("method"in a&&oH(a.method)){let d=a.params,c=typeof d?.sessionId=="string"?d.sessionId:void 0;if(c){if(Ds(c)){i(a,c);return}if(a.method==="session/attach"){let l="id"in a;e.resolveLocalMiss(c).then(u=>{if(u.ok){i(a,u.foreignId);return}if(u.ambiguous&&l){n.send(Iu(a.id,G.SessionNotFound,`Session "${c}" exists on more than one remote (${u.ambiguous.join(", ")}). Address it as "<remote>:${c}".`));return}o(a)});return}}}o(a)}),{send:a=>n.send(a),onMessage:a=>s.push(a),onClose:a=>n.onClose(a),close:()=>n.close()}}var Nh=class{constructor(e,t=aH,r){this.store=e;this.dial=t;this.localMiss=r}store;dial;localMiss;attachments=new Map;async resolveLocalMiss(e){if(!this.localMiss)return{ok:!1};if(await this.localMiss.resolvesLocally(e))return{ok:!1};let t=this.localMiss.cache.findByLocalId(e);return t.length===0?{ok:!1}:t.length>1?{ok:!1,ambiguous:t.map(r=>r.name)}:{ok:!0,foreignId:ko(t[0])}}async handleLocalMessage(e,t,r){let s="id"in e,o=s?e.id:void 0,i=Ds(t);if(!i)return s?Iu(o,G.SessionNotFound,`not a federated session id: ${t}`):void 0;let a=YA(r.clientId,t),d={...e.params,sessionId:i.localId};if(e.method==="session/attach"){let l=this.store.get(i.name);if(!l)return s?Iu(o,G.SessionNotFound,`No remote named "${i.name}". Run \`hydra remote add\` first.`):void 0;let u=this.attachments.get(a);u&&(this.attachments.delete(a),u.peerConnection.close().catch(()=>{}));let f;try{f=await this.dial(l)}catch(g){return s?Iu(o,G.InternalError,`Could not reach remote "${i.name}": ${g.message}`):void 0}let p={peerConnection:f,localId:i.localId,target:r};this.wireAttachment(i.name,p);let m;try{m=await f.request("session/attach",d)}catch(g){return f.close().catch(()=>{}),s?$b(o,g):void 0}this.attachments.set(a,p);let h=m&&typeof m.sessionId=="string"?{...m,sessionId:t}:m;return s?{jsonrpc:"2.0",id:o,result:h}:void 0}let c=this.attachments.get(a);if(!c)return s?Iu(o,G.SessionNotFound,`"${t}" is not attached through this daemon.`):void 0;if(e.method==="session/detach"){let l,u;try{l=await c.peerConnection.request("session/detach",d)}catch(f){u=f}return this.attachments.delete(a),c.peerConnection.close().catch(()=>{}),u?s?$b(o,u):void 0:s?{jsonrpc:"2.0",id:o,result:l??{}}:void 0}if(s)try{let l=await c.peerConnection.request(e.method,d);return{jsonrpc:"2.0",id:o,result:l}}catch(l){return $b(o,l)}await c.peerConnection.notify(e.method,d).catch(()=>{})}detachClient(e){for(let[t,r]of[...this.attachments.entries()])r.target.clientId===e&&(this.attachments.delete(t),r.peerConnection.request("session/detach",{sessionId:r.localId}).catch(()=>{}),r.peerConnection.close().catch(()=>{}))}wireAttachment(e,t){let{peerConnection:r,localId:s,target:o}=t,i=ko({name:e,localId:s}),a=()=>{this.attachments.delete(YA(o.clientId,i))};r.onAnyNotification((d,c)=>{let l=d;!l||l.sessionId!==s||(c==="hydra-acp/session/closed"&&a(),o.connection.notify(c,{...l,sessionId:i}).catch(()=>{}))}),r.onRequest("hydra-acp/session/request_permission",async d=>{let c=d;if(!c||c.sessionId!==s)throw{code:G.MethodNotFound,message:"unexpected sessionId"};return o.connection.request("hydra-acp/session/request_permission",{...c,sessionId:i})}),r.onClose(()=>{a(),o.connection.notify("hydra-acp/session/closed",{sessionId:i}).catch(()=>{})})}};function YA(n,e){return`${n} ${e}`}function Iu(n,e,t){return{jsonrpc:"2.0",id:n,error:{code:e,message:t}}}function $b(n,e){let t=e,r=typeof t?.code=="number"?t.code:G.InternalError,s=typeof t?.message=="string"?t.message:String(e??"forward failed");return{jsonrpc:"2.0",id:n,error:{code:r,message:s,...t?.data!==void 0?{data:t.data}:{}}}}var iH=1e4;async function aH(n){let t=`${Vt(n.host)?"ws":"wss"}://${n.host}:${n.port}/acp`,r=await wo(t,["acp.v1",`hydra-acp-token.${n.token}`],iH);return new pn(Rr(r))}Ts();var dH=3e4,cH=5e3,Dh=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;snapshots=new Map;timer;start(){this.timer||(this.checkAll(),this.timer=setInterval(()=>{this.checkAll()},this.opts.intervalMs??dH),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get(e){return this.snapshots.get(e)}markOk(e){this.snapshots.set(e,{status:"ok",checkedAt:new Date().toISOString()})}forget(e){this.snapshots.delete(e)}async checkAll(){let e=this.opts.fetchImpl??fetch;await Promise.allSettled(this.store.list().map(async t=>{let r=this.store.get(t.name);if(!r)return;let o=`${Vt(r.host)?"http":"https"}://${r.host}:${r.port}/v1/auth/verify`,i=new AbortController,a=setTimeout(()=>i.abort(),cH);try{let d=await e(o,{headers:{Authorization:`Bearer ${r.token}`},signal:i.signal});this.snapshots.set(t.name,{status:d.ok?"ok":"unauthorized",checkedAt:new Date().toISOString()})}catch(d){this.snapshots.set(t.name,{status:"unreachable",checkedAt:new Date().toISOString(),error:d.message})}finally{clearTimeout(a)}}))}};Xo();import{z as XA}from"zod";var lH=XA.object({sessionLabel:XA.string().min(1).max(256)});function ZA(n,e){n.post("/v1/process-tokens",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=lH.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}let o=e.processRegistry.mint(s.sessionLabel,"script");return r.code(201).send({token:o})}),n.delete("/v1/process-tokens/:sessionLabel",async(t,r)=>t.authIdentity!=="service"?r.code(403).send({error:"Requires the service token"}):(e.processRegistry.revoke(t.params.sessionLabel),r.code(204).send()))}bo();Sc();Sa();import{nanoid as Ob}from"nanoid";Rp();fn();Os();Od();dr();import{randomBytes as sT}from"crypto";import*as oT from"os";import*as iT from"path";cc();var uH=200;function fH(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[ut];if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.sentBy;if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o={};if(typeof s.sessionId=="string"&&s.sessionId.length>0&&(o.sessionId=s.sessionId),typeof s.label=="string"&&s.label.length>0&&(o.label=s.label.slice(0,uH)),s.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function eT(n,e,t){let r=fH(n);if(!r)return;let s={};if(r.label!==void 0&&(s.fromLabel=r.label),r.awaiting===!0&&(s.awaiting=!0),r.sessionId!==void 0){let o=await e.resolveCanonicalId(r.sessionId)??r.sessionId,i=await e.getOne(o);if(i){s.fromSession=o,i.title&&(s.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;s.depth=(a??0)+1}else t?.(r.sessionId)}if(!(s.fromSession===void 0&&s.fromLabel===void 0))return s}var Cu=new Map;function tT(n,e){let t=Cu.get(n);t||(t=new Set,Cu.set(n,t)),t.add(e);let r=!1;return()=>{if(r)return;r=!0;let s=Cu.get(n);s&&(s.delete(e),s.size===0&&Cu.delete(n))}}function nT(n,e){if(n===e)return!0;let t=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(t.has(s))continue;t.add(s);let o=Cu.get(s);if(o){if(o.has(n))return!0;for(let i of o)r.push(i)}}return!1}function he(n,e,t){let r=new Error(e);return r.code=n,t!==void 0&&(r.data=t),r}function yH(n){if(!n||typeof n!="object")return 512;let r=n.params?.update;if(!r)return 512;let s=512,o=r.content;if(typeof o=="string")s+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(s+=a.text.length),typeof a.data=="string"&&(s+=a.data.length)}let i=r.toolCall;if(i&&(typeof i.rawInput=="string"?s+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(s+=256),typeof i.rawOutput=="string"?s+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(s+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(s+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(s+=c.text.length)}}return s}function cr(n,e,t){let r=n.get(e);if(!r)throw he(G.SessionNotFound,t??`session ${e} not found`);return r}async function xa(n,e){let t=Pc(n),r,s,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(r=sT(32).toString("hex"),s=n.mcpTokenRegistry.reserve(r),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${r}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=Tb({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),s!==void 0&&s.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(c),r!==void 0&&s!==void 0&&n.mcpTokenRegistry!==void 0){let l=r,u=n.mcpTokenRegistry;s.complete(c),c.onClose(()=>{u.unbind(l)})}return AH(c,n),dT(c.sessionId,n),c}function aT(n,e){n.get("/acp",{websocket:!0},async(t,r)=>{let s=eA({headers:r.headers,url:r.url});if(!s||!await e.validator.validate(s)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(s),i=`hydra_client_${Ob(12)}`,a=Rr(t),d={},c=e.foreignSessions?QA(a,e.foreignSessions,d,i):a,l=new pn(c);d.connection=l;let u={clientId:i,processIdentity:o,attached:new Map};l.onClose(()=>{for(let m of u.attached.values())e.manager.get(m.sessionId)?.detach(m.clientId);u.attached.clear(),e.foreignSessions?.detachClient(i)});let f=(m,h)=>{if(u.attached.get(m)?.readonly)throw he(G.PermissionDenied,`${h} not permitted on a read-only attachment`)};if(l.onRequest("initialize",async m=>{let h=$I.parse(m??{});h.clientInfo?.name&&(u.clientInfo={name:h.clientInfo.name,...h.clientInfo.version!==void 0?{version:h.clientInfo.version}:{}});let g=h.clientInfo?.version;return g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g)),RH()}),o&&e.extensionCommands){let m=e.extensionCommands;l.onRequest("hydra-acp/commands/register",async h=>{let g=h??{},w=Array.isArray(g.commands)?g.commands.map(b=>{if(!b||typeof b!="object")return;let k=b;if(typeof k.verb!="string")return;let S={verb:k.verb};return typeof k.argsHint=="string"&&(S.argsHint=k.argsHint),typeof k.description=="string"&&(S.description=k.description),S}).filter(b=>b!==void 0):[];return m.register(o.name,l,w),{ok:!0,registered:w.length}}),l.onClose(()=>{m.clear(o.name)})}if(o&&e.extensionMcp){let m=e.extensionMcp;l.onRequest("hydra-acp/mcp_tools/register",async g=>{let w=g??{},b=typeof w.instructions=="string"?w.instructions:void 0,k=Array.isArray(w.tools)?w.tools.map(S=>{if(!S||typeof S!="object")return;let I=S;if(typeof I.name!="string"||I.name.length===0||typeof I.description!="string"||I.inputSchema===null||typeof I.inputSchema!="object")return;let x={name:I.name,description:I.description,inputSchema:I.inputSchema};return I.outputSchema!==null&&typeof I.outputSchema=="object"&&(x.outputSchema=I.outputSchema),x}).filter(S=>S!==void 0):[];if(k.length===0)throw new Error("register_mcp_tools requires at least one tool");return m.register(o.name,l,b,k),{ok:!0,registered:k.length}});let h=g=>{let w=g??{};if(typeof w.sessionId!="string"||w.sessionId.length===0)throw he(G.InvalidParams,"sessionId is required");return w.sessionId};if(l.onRequest("hydra-acp/session/extension_state/get",async g=>{let w=h(g),b=g??{};if(typeof b.key!="string"||b.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(w,o.name,b.key)??null}}),l.onRequest("hydra-acp/session/extension_state/list",async g=>{let w=h(g);if(!e.manager)throw he(G.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(w,o.name)}}),l.onRequest("hydra-acp/session/extension_state/set",async g=>{let w=h(g),b=g??{};if(typeof b.key!="string"||b.key.length===0)throw he(G.InvalidParams,"key is required");if(b.value===void 0)throw he(G.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw he(G.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(w,o.name,b.key,b.value)}catch(k){throw he(G.InvalidParams,k.message)}return{ok:!0}}),l.onRequest("hydra-acp/session/extension_state/delete",async g=>{let w=h(g),b=g??{};if(typeof b.key!="string"||b.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(w,o.name,b.key),{ok:!0}}),e.extensionMcpControls){let g=e.extensionMcpControls;l.onRequest("hydra-acp/mcp_tools/refresh_session",async w=>{let b=w??{};if(typeof b.sessionId!="string"||b.sessionId.length===0)throw he(G.InvalidParams,"refresh_session requires sessionId");return await g.notifyToolListChanged(b.sessionId,o.name),{ok:!0}})}l.onClose(()=>{m.clear(o.name)})}if(o?.kind==="transformer"){l.onRequest("hydra-acp/transformer/initialize",async h=>{let g=h??{},w=Array.isArray(g.intercepts)?g.intercepts.filter(b=>typeof b=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,l,w),e.manager?.defaultTransformers.includes(o.name))){let b=e.transformers.resolveChain([o.name])[0];if(b)for(let k of e.manager.liveSessions())k.addTransformer(b)}return{ack:!0}}),l.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),l.onRequest("hydra-acp/message/emit",async h=>{let g=h??{},w=typeof g.sessionId=="string"?g.sessionId:void 0,b=typeof g.method=="string"?g.method:void 0,k=g.envelope,S=g.route;if(!w)throw he(-32602,"emit_message requires sessionId");if(!b&&S!=="client_broadcast")throw he(-32602,"emit_message requires method");let I=cr(e.manager,w),x=typeof g.respondsTo=="string"?g.respondsTo:void 0;if(x)return I.dischargeClaim(x,k),{ok:!0};if(S==="chain")return{ok:!0,response:await I.emitToChain(o.name,b,k)};if(S==="queue"){if(b!=="session/prompt")throw he(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await I.emitToQueue(o.name,k)}}if(S==="daemon")return{ok:!0,response:await I.emitToChain(o.name,b,k)};if(S==="client_broadcast"){if(!k||typeof k!="object")throw he(-32602,"client_broadcast requires an envelope object");return I.broadcastClientUpdate(k),{ok:!0}}throw he(-32602,`unsupported route: ${JSON.stringify(S)}`)}),l.onRequest("hydra-acp/session/request_permission",async h=>{let g=h??{},w=typeof g.sessionId=="string"?g.sessionId:void 0;if(!w)throw he(-32602,"hydra-acp/session/request_permission requires sessionId");return cr(e.manager,w).requestPermissionFromClients(g)}),l.onRequest("hydra-acp/transformer/attach",async h=>SH(h,o.name,e)),l.onRequest("hydra-acp/child_session/spawn",async h=>{let g=h??{},w=typeof g.agentId=="string"?g.agentId:void 0,b=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.parentSessionId=="string"?g.parentSessionId:void 0,S=Pn(g._meta??void 0),I=S.title,x=S.model,A=S.workspace;if(!b&&k){let Z=e.manager.get(k);Z&&(b=Z.cwd)}if(!b)throw he(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let _=await $d(b),P=w??_.agentId??e.defaultAgent,$=await e.registry?.getAgent(P),F=xr(_.configDefaults,$??{id:P})?.value,J=x??F?.model,Y=typeof g.interactive=="boolean"?g.interactive:!1,W=await e.manager.create({agentId:P,cwd:b,parentSessionId:k,interactive:Y,transformChain:[],title:I,model:J,configDefaults:F,...A!==void 0?{workspace:A}:{}});return{childSessionId:W.sessionId,...W.workspace!==void 0||W.workspaceError!==void 0?{_meta:{[ut]:{...W.workspace!==void 0?{workspaceInfo:W.workspace}:{},...W.workspaceError!==void 0?{workspaceError:W.workspaceError}:{}}}}:{}}}),l.onRequest("hydra-acp/session/fork",async h=>{let g=h??{};if(typeof g.sessionId!="string")throw he(G.InvalidParams,"fork_session requires sessionId");let w=typeof g.forkAt=="string"?g.forkAt:void 0,b=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.agentId=="string"?g.agentId:void 0,S=typeof g.mode=="string"&&(g.mode==="verbatim"||g.mode==="synthesis")?g.mode:void 0,I=typeof g.model=="string"&&g.model.length>0?g.model:void 0,x=await e.manager.forkSession(g.sessionId,{...w!==void 0?{forkAt:w}:{},...b!==void 0?{cwd:b}:{},...k!==void 0?{agentId:k}:{},...S!==void 0?{mode:S}:{},...I!==void 0?{model:I}:{}}),A=e.manager.get(x.sessionId);if(!A){let $=await e.manager.loadFromDisk(x.sessionId);if(!$)throw he(G.InternalError,`fork ${x.sessionId} vanished before it could be attached`);A=await xa(e,{...$,onInstallProgress:Bh(l)})}Mc(u,A,A.sessionId);let _=pi(l,A,u),{entries:P}=await A.attach(_,"full");u.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:_.clientId,readonly:!1});for(let $ of P){if(l.isClosed())break;await l.notify($.method,Ls(Fs($.params,$.recordedAt),$.seq)).catch(()=>{})}return{...x,sessionId:A.sessionId}}),l.onRequest("session/fork",async h=>{let g=h??{};if(typeof g.sessionId!="string")throw he(G.InvalidParams,"session/fork requires sessionId");let w=typeof g.cwd=="string"?g.cwd:void 0,b=await e.manager.forkSession(g.sessionId,{...w!==void 0?{cwd:w}:{},mode:"verbatim"}),k=e.manager.get(b.sessionId);if(!k){let x=await e.manager.loadFromDisk(b.sessionId);if(!x)throw he(G.InternalError,`fork ${b.sessionId} vanished before it could be attached`);k=await xa(e,{...x,onInstallProgress:Bh(l)})}Mc(u,k,k.sessionId);let S=pi(l,k,u),{entries:I}=await k.attach(S,"full");u.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:S.clientId,readonly:!1});for(let x of I){if(l.isClosed())break;await l.notify(x.method,Ls(Fs(x.params,x.recordedAt),x.seq)).catch(()=>{})}return{sessionId:k.sessionId}});let m=async(h,g)=>{let w=h??{};if(typeof w.sessionId!="string")throw he(G.InvalidParams,`${g} requires sessionId`);let b=await e.manager.resolveCanonicalId(w.sessionId)??w.sessionId,k=e.manager.get(b);if(k)return await k.close({deleteRecord:!0,by:`session/delete ${u.clientId}`}),await e.manager.waitForDeletion(b),await e.manager.hasRecord(b)&&await e.manager.deleteRecord(b),{id:b,existed:!0};let S=await e.manager.deleteRecord(b);return{id:b,existed:S}};l.onRequest("session/delete",async h=>(await m(h,"session/delete"),{})),l.onRequest("session/close",async h=>{let g=h??{};if(typeof g.sessionId!="string")throw he(G.InvalidParams,"session/close requires sessionId");f(g.sessionId,"session/close");let w=await e.manager.resolveCanonicalId(g.sessionId)??g.sessionId,b=e.manager.get(w);if(b)return await b.close({deleteRecord:!1,by:`session/close ${u.clientId}`+(u.processIdentity?` (${u.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(w))return{};throw he(G.SessionNotFound,`session ${w} not found`)}),l.onRequest("hydra-acp/session/delete",async h=>{let{id:g,existed:w}=await m(h,"hydra-acp/session/delete");if(!w)throw he(G.SessionNotFound,`session ${g} not found`);return{deleted:!0,sessionId:g}}),l.onRequest("hydra-acp/child_session/await",async h=>{let g=h??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0,b=g.until==="idle"?"idle":"turn_complete",k=typeof g.timeoutMs=="number"?Math.min(g.timeoutMs,18e5):3e5;if(!w)throw he(-32602,"await_child requires childSessionId");let S=cr(e.manager,w,`child session ${w} not found`);return new Promise(I=>{let _=[],P=[],$=0,F=!1,J,Y,W=!1,Z=()=>{W||(W=!0,clearTimeout(ne),J?.(),Y?.(),I(F?{entries:_,truncated:!0}:{entries:_}))};J=S.onBroadcast(ve=>{let Ne=yH(ve);for(_.push(ve),P.push(Ne),$+=Ne;_.length>0&&(_.length>1e3||$>1048576);)_.shift(),$-=P.shift()??0,F=!0;b==="turn_complete"&&ve.params?.update?.sessionUpdate==="turn_complete"&&Z()});let ne=setTimeout(Z,k);typeof ne.unref=="function"&&ne.unref(),Y=S.onClose(()=>Z())})}),l.onRequest("hydra-acp/child_session/close",async h=>{let g=h??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0;if(!w)throw he(-32602,"close_child_session requires childSessionId");let b=e.manager.get(w);return b&&await b.close({deleteRecord:!1,by:`child_session/close ${u.clientId}`}),{ok:!0}}),l.onRequest("hydra-acp/attention/set",async h=>xH(h,o.name,e)),l.onRequest("hydra-acp/attention/clear",async h=>IH(h,o.name,e)),l.onRequest("hydra-acp/connection/keep_alive",async h=>{let g=h??{},w=typeof g.token=="string"?g.token:void 0,b=typeof g.sessionId=="string"?g.sessionId:void 0,k=typeof g.estimatedRemainingMs=="number"?g.estimatedRemainingMs:void 0;return w&&b&&e.manager.get(b)?.keepAliveClaim(w,k),{ok:!0}})}l.onRequest("hydra-acp/session/tool_content",async m=>{let h=m??{};if(typeof h.sessionId!="string"||typeof h.hash!="string")throw he(G.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let g=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,w=await e.manager.loadToolBlob(g,h.hash);if(w===null)throw he(G.SessionNotFound,"tool content not found");return{content:w}}),l.onRequest("authenticate",async m=>wH(m,e)),l.onRequest("logout",async m=>bH(m,e)),l.onRequest("session/new",async m=>{let h=OI.parse(m),g=Pn(m?._meta),w=Array.isArray(g.transformers)&&g.transformers.every(Re=>typeof Re=="string")?g.transformers:e.manager.defaultTransformers??[],b=e.transformers?.resolveChain(w)??[],k=await $d(h.cwd),S=g.agentId??k.agentId??e.defaultAgent,I=await e.registry?.getAgent(S),x=xr(k.configDefaults,I??{id:S})?.value,A,_,P=h.mcpServers;if(g.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){A=sT(32).toString("hex"),_=e.mcpTokenRegistry.reserve(A);let Ge={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${A}`}]};P=[...h.mcpServers??[],Ge]}let $,F,J=Pc(e);J!==void 0&&(P=[...P??[],...J.descriptors]);let Y=Tb({baselineMcpServers:h.mcpServers,stdinEnabled:g.mcpStdin===!0,deps:e}),W;try{W=await e.manager.create({cwd:h.cwd,agentId:S,mcpServers:P,title:g.title,agentArgs:g.agentArgs,model:g.model??x?.model,configDefaults:x,onInstallProgress:Bh(l),transformChain:b,originatingClient:u.clientInfo,...g.interactive!==void 0?{interactive:g.interactive}:{},...g.env!==void 0?{forwardedEnv:g.env}:{},...g.workspace!==void 0?{workspace:g.workspace}:{},...Y?{mintMcpServersForSwap:Y}:{}})}catch(Re){throw _!==void 0&&_.abandon(Re instanceof Error?Re:void 0),F!==void 0&&F.abandon(Re instanceof Error?Re:void 0),J!==void 0&&J.abandon(Re instanceof Error?Re:void 0),Re}if(A!==void 0&&_!==void 0&&e.mcpTokenRegistry!==void 0){let Re=A,Ge=e.mcpTokenRegistry;_.complete(W),W.onClose(()=>{Ge.unbind(Re)})}if($!==void 0&&F!==void 0&&e.mcpTokenRegistry!==void 0){let Re=$,Ge=e.mcpTokenRegistry;F.complete(W),W.onClose(()=>{Ge.unbind(Re)})}J!==void 0&&J.bindToSession(W),dT(W.sessionId,e);let Z,ne;try{Mc(u,W,W.sessionId),Z=pi(l,W,u),{entries:ne}=await W.attach(Z,"full")}catch(Re){throw await W.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),Re}u.attached.set(W.sessionId,{sessionId:W.sessionId,clientId:Z.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let Re of ne){if(l.isClosed())break;await l.notify(Re.method,Ls(Fs(Re.params,Re.recordedAt),Re.seq)).catch(()=>{})}})()});let ve=Hh(W),Ne=Uh(W);return{sessionId:W.sessionId,...ve?{modes:ve}:{},...Ne?{models:Ne}:{},configOptions:W.buildConfigOptions(),_meta:Wh(e.manager,W,{clientId:Z.clientId})}}),l.onRequest("session/attach",async m=>{let h=LI.parse(m),g=h.clientInfo?.version;g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g));let w=Pn(h._meta),b=w.resume,k=w.readonly===!0,S=w.env;n.log.info(`session/attach sessionId=${h.sessionId} hasResumeHints=${!!b} readonly=${k}`);let I=b?h.sessionId:await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,x=e.manager.get(I);if(!x&&k){let W=await e.manager.loadFromDisk(I);if(!W)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);let Z=await e.manager.loadHistory(I,{...w.historyLimit!==void 0?{maxEntries:w.historyLimit}:{}}),ne=h.clientId??`cli_${Ob(8)}`;u.attached.set(W.hydraSessionId,{sessionId:W.hydraSessionId,clientId:ne,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${W.hydraSessionId} clientId=${ne} attachedCount=${u.attached.size} replayed=${Z.length}`);for(let ve of Z)await l.notify(ve.method,Ls(Fs(ve.params,ve.recordedAt),ve.seq)).catch(()=>{});return{sessionId:W.hydraSessionId,clientId:ne,connectedClients:[ne],historyPolicy:"full",replayed:Z.length,_meta:CH(W)}}let A=!x;if(!x){let W=await e.manager.loadFromDisk(I),Z=await kH(I,b,W?.upstreamSessionId,e.manager);Z.kind==="ignore"&&n.log.warn(Z.logMessage);let ne=W;if(b&&Z.kind==="honor"&&(ne={...W,hydraSessionId:h.sessionId,upstreamSessionId:b.upstreamSessionId,agentId:b.agentId,cwd:W?.workspace?.path??b.cwd,...b.title!==void 0?{title:b.title}:{},...b.agentArgs!==void 0?{agentArgs:b.agentArgs}:{}}),!ne)throw he(G.SessionNotFound,`session ${h.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(ne.agentId,ne.upstreamSessionId))throw he(G.SessionNotFound,`session ${h.sessionId} was deleted`);let ve=ne.originatingClient?ne:{...ne,originatingClient:u.clientInfo},Ne=S!==void 0?{...ve,forwardedEnv:S}:ve;x=await xa(e,{...Ne,onInstallProgress:Bh(l)})}Mc(u,x,x.sessionId);let _=pi(l,x,u,h.clientInfo,h.clientId),P=w.replayMode==="drip",{entries:$,appliedPolicy:F}=await x.attach(_,h.historyPolicy,{afterMessageId:h.afterMessageId,afterSeq:h.afterSeq,raw:P,...w.historyLimit!==void 0?{historyLimit:w.historyLimit}:{},...w.toolContent!==void 0?{toolContent:w.toolContent}:{}});if(u.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:_.clientId,readonly:k}),S!==void 0&&await e.manager.setForwardedEnv(x.sessionId,S).catch(()=>{}),n.log.info(`session/attach OK sessionId=${x.sessionId} clientId=${_.clientId} attachedCount=${u.attached.size} requestedPolicy=${h.historyPolicy} appliedPolicy=${F} replayed=${$.length} readonly=${k}${P?" replayMode=drip":""}`),P){let W=w.dripSpeed&&w.dripSpeed>0?w.dripSpeed:1,Z=750;(async()=>{let ne=null;for(let ve of $){let Ne=typeof ve.recordedAt=="number"?ve.recordedAt:null;if(ne!==null&&Ne!==null){let Re=Math.min(Z,Math.max(0,(Ne-ne)/W));Re>0&&await new Promise(Ge=>setTimeout(Ge,Re))}Ne!==null&&(ne=Ne);try{await l.notify(ve.method,Ls(Fs(ve.params,Ne??void 0),ve.seq))}catch{return}}})()}else for(let W=0;W<$.length&&!l.isClosed();W++){let Z=$[W],ne=l.notify(Z.method,Ls(Fs(Z.params,Z.recordedAt),Z.seq)).catch(()=>{});(W+1)%200===0&&await ne}x.replayPendingPermissions(_);let J=Hh(x),Y=Uh(x);return{sessionId:x.sessionId,clientId:_.clientId,connectedClients:x.connectedClients(_.clientId),historyPolicy:F,replayed:$.length,...J?{modes:J}:{},...Y?{models:Y}:{},configOptions:x.buildConfigOptions(),_meta:Wh(e.manager,x,{resurrected:A})}}),l.onRequest("session/detach",async m=>{let h=NI.parse(m),g=u.attached.get(h.sessionId);if(!g)throw he(G.SessionNotFound,"client not attached to that session");let w=e.manager.get(h.sessionId);return w?.detach(g.clientId),u.attached.delete(h.sessionId),w&&e.manager.reapIfOrphanedNonInteractive(h.sessionId),{sessionId:h.sessionId,_meta:{[ut]:{detachStatus:"detached"}}}}),l.onRequest("session/list",async m=>{let h=DI.parse(m??{});return{sessions:(await e.manager.list({cwd:h.cwd})).filter(k=>k.originatingClient?.name!==pa).map(BI)}}),l.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw he(G.InternalError,"agent registry unavailable");return dc(e.registry)}),l.onRequest("hydra-acp/agents/auth_methods",async m=>{let h=m??{};if(typeof h.agentId!="string"||h.agentId.length===0)throw he(G.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(h.agentId)).authMethods??[]}}),l.onRequest("session/prompt",async m=>{let h=UI.parse(m);f(h.sessionId,"session/prompt");let g=await eT(h,e.manager,S=>{n.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${S} sessionId=${h.sessionId}`)});if(g?.fromSession!==void 0){if((g.depth??0)>3)throw n.log.warn(`session/prompt: refusing depth ${g.depth} chain from ${g.fromSession} to ${h.sessionId}`),he(G.InvalidRequest,`message chain too deep (${g.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(g.awaiting===!0&&nT(g.fromSession,h.sessionId))throw n.log.warn(`session/prompt: refusing deadlock ${g.fromSession} -> ${h.sessionId}`),he(G.InvalidRequest,`would deadlock: ${h.sessionId} is already blocked waiting on ${g.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let w=u.attached.get(h.sessionId);if(!w)throw n.log.warn(`session/prompt rejected: not attached sessionId=${h.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),he(G.SessionNotFound,"not attached to session");let b=e.manager.get(h.sessionId);if(!b){let S=await e.manager.loadFromDisk(h.sessionId);if(!S)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${h.sessionId}`),b=await xa(e,S);let I=pi(l,b,u,void 0,w.clientId);await b.attach(I,"none")}let k=g?.awaiting===!0&&g.fromSession!==void 0?tT(g.fromSession,h.sessionId):void 0;try{return await b.prompt(w.clientId,h,g)}finally{k?.()}});let p=m=>{let h;try{h=wp.parse(m)}catch(b){n.log.warn(`session/cancel: invalid params: ${b.message}`);return}let g=u.attached.get(h.sessionId);if(!g)return;if(g.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${h.sessionId}`);return}let w=e.manager.get(h.sessionId);w&&w.cancel(g.clientId).catch(b=>{n.log.warn(`session/cancel for ${h.sessionId}: ${b.message}`)})};l.onNotification("session/cancel",p),l.onRequest("session/cancel",async m=>{let h=wp.parse(m);return f(h.sessionId,"session/cancel"),p(m),null}),l.onRequest("hydra-acp/prompt/cancel",async m=>{let h=jI.parse(m);return f(h.sessionId,"hydra-acp/prompt/cancel"),cr(e.manager,h.sessionId).cancelQueuedPrompt(h.messageId)}),l.onRequest("hydra-acp/session/force_cancel",async m=>{let h=wp.parse(m);return f(h.sessionId,"hydra-acp/session/force_cancel"),cr(e.manager,h.sessionId).forceCancel()}),l.onRequest("hydra-acp/prompt/update",async m=>{let h=qI.parse(m);return f(h.sessionId,"hydra-acp/prompt/update"),cr(e.manager,h.sessionId).updateQueuedPrompt(h.messageId,h.prompt)}),l.onRequest("hydra-acp/prompt/amend",async m=>{let h=zI.parse(m);f(h.sessionId,"hydra-acp/prompt/amend");let g=u.attached.get(h.sessionId);if(!g)throw he(G.SessionNotFound,"not attached to session");return cr(e.manager,h.sessionId).amendPrompt(g.clientId,h)}),l.onRequest("_session/steering",async m=>{let h=KI.parse(m);f(h.sessionId,"_session/steering");let g=u.attached.get(h.sessionId);if(!g)throw he(G.SessionNotFound,"not attached to session");let w=e.manager.get(h.sessionId);if(!w){let b=await e.manager.loadFromDisk(h.sessionId);if(!b)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);w=await xa(e,b);let k=pi(l,w,u,void 0,g.clientId);await w.attach(k,"none")}return w.steer(g.clientId,h)}),l.onRequest("session/resume",async m=>{let h=m??{},g=typeof h.sessionId=="string"?h.sessionId:void 0;if(!g)throw he(G.InvalidParams,"session/resume requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,b=e.manager.get(w);if(!b){let x=await e.manager.loadFromDisk(w);if(!x)throw he(G.SessionNotFound,`session ${g} not found in memory or on disk`);b=await xa(e,x)}Mc(u,b,b.sessionId);let k=pi(l,b,u);await b.attach(k,"pending_only"),u.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:k.clientId,readonly:!1}),b.replayPendingPermissions(k);let S=Hh(b),I=Uh(b);return{sessionId:b.sessionId,...S?{modes:S}:{},...I?{models:I}:{},configOptions:b.buildConfigOptions(),_meta:Wh(e.manager,b,{clientId:k.clientId})}}),l.onRequest("session/load",async m=>{let h=m??{},g=typeof h.sessionId=="string"?h.sessionId:void 0;if(!g)throw he(G.InvalidParams,"session/load requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,b=e.manager.get(w);if(!b){let A=await e.manager.loadFromDisk(w);if(!A)throw he(G.SessionNotFound,`session ${g} not found in memory or on disk`);b=await xa(e,A)}Mc(u,b,b.sessionId);let k=pi(l,b,u),{entries:S}=await b.attach(k,"full");u.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:k.clientId,readonly:!1});for(let A of S){if(l.isClosed())break;await l.notify(A.method,Ls(Fs(A.params,A.recordedAt),A.seq)).catch(()=>{})}b.replayPendingPermissions(k);let I=Hh(b),x=Uh(b);return{sessionId:b.sessionId,...I?{modes:I}:{},...x?{models:x}:{},configOptions:b.buildConfigOptions(),_meta:Wh(e.manager,b,{clientId:k.clientId})}}),l.onRequest("session/set_model",async m=>{let h=m?.sessionId;typeof h=="string"&&f(h,"session/set_model");let g=vH(m,e.manager);if(g.kind==="error")throw n.log.warn(g.logMessage),he(g.code,g.message);if(g.kind==="no_op")return n.log.warn(g.logMessage),await l.notify("session/update",{sessionId:g.sessionId,update:{sessionUpdate:"_hydra_current_model_update",currentModel:g.currentModel}}).catch(()=>{}),null;n.log.info(g.logMessage);let{modelId:w}=g,b=await g.session.forwardModelChange(w,m);return g.session.applyAgentConfigOptionResponse(b,"model"),g.session.applyModelChange(w),b}),l.onRequest("session/set_mode",async m=>{let h=m,g=h?.sessionId;if(typeof g=="string"&&f(g,"session/set_mode"),!h||typeof h.sessionId!="string")throw he(G.InvalidParams,"session/set_mode requires string sessionId");if(typeof h.modeId!="string")throw he(G.InvalidParams,"session/set_mode requires string modeId");let w=cr(e.manager,h.sessionId),b=await w.forwardRequest("session/set_mode",m);return w.applyModeChange(h.modeId),b}),l.onRequest("session/set_config_option",async m=>{let h=m,g=S=>he(G.InvalidParams,S),w=h?.sessionId;if(typeof w=="string"&&f(w,"session/set_config_option"),!h||typeof h.sessionId!="string")throw g("session/set_config_option requires string sessionId");if(typeof h.configId!="string")throw g("session/set_config_option requires string configId");if(typeof h.value!="string")throw g("session/set_config_option requires string value");let b=cr(e.manager,h.sessionId),k=b.buildConfigOptions().find(S=>S.id===h.configId);if(!k)throw g(`unknown configId ${JSON.stringify(h.configId)} for this session`);if(!k.options.some(S=>S.value===h.value))throw g(`value ${JSON.stringify(h.value)} is not valid for configId ${JSON.stringify(h.configId)}`);switch(h.configId){case"model":{if(h.value!==b.currentModel){let S=await b.forwardModelChange(h.value);b.applyAgentConfigOptionResponse(S,"model")}b.applyModelChange(h.value);break}case"mode":{h.value!==b.currentMode&&await b.forwardRequest("session/set_mode",{sessionId:h.sessionId,modeId:h.value}),b.applyModeChange(h.value);break}case"agent":{h.value!==b.agentId&&await b.setAgent(h.value);break}default:{let S=await b.forwardRequest("session/set_config_option",{sessionId:h.sessionId,configId:h.configId,value:h.value});b.applyAgentConfigOptionResponse(S,h.configId)&&b.broadcastConfigOptions()}}return{configOptions:b.buildConfigOptions()}}),l.setDefaultHandler(async(m,h)=>{let g=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),w=h.startsWith("session/"),b=h.startsWith("hydra-acp/");if(!w&&!b||m===null||typeof m!="object"||g.has(h))throw he(G.MethodNotFound,`Method not found: ${h}`);let k=m.sessionId;if(typeof k!="string")throw he(G.MethodNotFound,`Method not found: ${h}`);return f(k,h),cr(e.manager,k).forwardRequest(h,m)})})}async function wH(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw he(G.InvalidParams,"authenticate requires a non-empty methodId string");let r=t.methodId,s=t._meta?.["hydra-acp"],o=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===r);if(!c){let p=d.map(m=>m.id);throw he(G.InvalidParams,`authenticate: methodId ${JSON.stringify(r)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).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=(k,S)=>{if(!Array.isArray(k))throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be a string[]; got ${k===null?"null":typeof k}`);for(let I of k)if(typeof I!="string")throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be string[]; got non-string entry ${JSON.stringify(I)}`);return k},m=await e.manager.planSpawnForAgent(a.agentId),h,g;if(u?.args!==void 0){let k=typeof u.command=="string"?u.command:void 0;h=k!==void 0&&iT.isAbsolute(k)?k:m.command,g=p(u.args,'_meta["terminal-auth"].args')}else{let k=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=k!==void 0?p(k.raw,k.label):[];h=m.command,g=[...m.args,...S]}let w={};for(let[k,S]of Object.entries(process.env))typeof S=="string"&&(w[k]=S);Object.assign(w,m.env);let b=oT.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${r}`),{kind:"terminal",command:h,args:g,env:w,cwd:b}}try{return await a.connection.request("authenticate",{methodId:r})}catch(p){throw di(p,a)}}async function bH(n,e){let r=(n??{})._meta?.["hydra-acp"],s=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,i=s!==void 0?e.manager.getAgentForSession(s):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function Bh(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(bp,t).catch(()=>{})}}function Hh(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(s=>{let o={id:s.id,name:s.name??s.id};return s.description!==void 0&&(o.description=s.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Uh(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(s=>{let o={modelId:s.modelId};return s.name!==void 0&&(o.name=s.name),s.description!==void 0&&(o.description=s.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}async function kH(n,e,t,r){return e?await r.isRetiredGeneration(n,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${n} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function vH(n,e){if(!n||typeof n!="object")return{kind:"error",code:G.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:G.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:G.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let r=e.get(t.sessionId);if(!r)return{kind:"error",code:G.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let s=r.availableModels(),o=hc(t.modelId,s);if(o.kind==="none")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:r,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=s.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return r.currentModel!==void 0&&r.currentModel.length>0?{kind:"no_op",session:r,sessionId:t.sessionId,currentModel:r.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(r.currentModel)} agentId=${r.agentId} known=[${i}]`}:{kind:"error",code:G.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${r.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${r.agentId} known=[${i}] (no current model to fall back to)`}}async function SH(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)throw he(G.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw he(G.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw he(G.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return cr(t.manager,s).addTransformer(o),{ok:!0}}async function xH(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/set requires string reason");return cr(t.manager,s).setAttentionFlag(e,o,r.payload),{ok:!0}}async function IH(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string reason");return cr(t.manager,s).clearAttentionFlag(e,o),{ok:!0}}function CH(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,workspace:n.workspace,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:ga(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,armedTasks:0,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels,armedTaskList:[]};return{[ut]:gp(e,t)}}function Wh(n,e,t={}){let r=n.liveListEntry(e),s={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(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return ql(e.agentMeta,gp(r,s))}function RH(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Ue},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:{...ql(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}}}),steering:{supported:!0}}}}function AH(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let r=e.transformers.resolveChain([t])[0];r&&n.addTransformer(r)}}function dT(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let r of t)r.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function pi(n,e,t,r,s){return{clientId:s??`cli_${Ob(8)}`,connection:n,clientInfo:r}}function Mc(n,e,t){let r=n.attached.get(t);r&&(e.detach(r.clientId),n.attached.delete(t))}var jh=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,r,s=new Promise((i,a)=>{t=i,r=a});s.catch(()=>{});let o={session:void 0,sessionReady:s,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),r(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:r}=this.reserve(e);r(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let r=this.byToken.get(e);r!==void 0&&r.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let r of t.disposers)try{await r()}catch{}}}size(){return this.byToken.size}};import{randomUUID as TH}from"crypto";import{McpServer as EH}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as PH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Mn}from"zod";function Fb(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 Zn(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var cT="Bearer ";function _c(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(cT))return;let t=e.slice(cT.length).trim();return t.length>0?t:void 0}function MH(n){let e=new EH({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:Mn.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let r=n.streamTail(t);return Zn(r)}),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:Mn.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let r=n.streamHead(t);return Zn(r)}),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:Mn.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:Mn.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Mn.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:r,wait_ms:s})=>{let o=await n.streamRead(t,r,s);return Zn(o)}),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:Mn.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Mn.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:r})=>{let s=await n.streamWaitFor(t,r),o=n.streamInfo();return Zn({outcome:s,writeCursor:o.writeCursor,closed:o.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:Mn.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Mn.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Mn.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Mn.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Mn.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Mn.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Mn.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Mn.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Mn.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 r={pattern:t.pattern};t.regex!==void 0&&(r.regex=t.regex),t.case_insensitive!==void 0&&(r.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(r.invert=t.invert),t.max_matches!==void 0&&(r.maxMatches=t.max_matches),t.max_bytes!==void 0&&(r.maxBytes=t.max_bytes),t.context_before!==void 0&&(r.contextBefore=t.context_before),t.context_after!==void 0&&(r.contextAfter=t.context_after),t.cursor!==void 0&&(r.cursor=t.cursor);let s=n.streamGrep(r);return Zn(s)}),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 Zn(t)}),e}var _H=1e4;function lT(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=MH(a),l=new PH({sessionIdGenerator:()=>TH()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=_c(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(h=>{f=setTimeout(()=>h(void 0),_H)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let u=await r(d,l);a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)})}Tp();import{randomUUID as $H}from"crypto";import{McpServer as OH}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as FH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as qs}from"zod";function LH(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var uT=2e3,fT=2e4;function NH(n,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return gc([n]);let r=[],s=Vl(t);s!==void 0?r.push(`Tool: ${s}`):typeof t.title=="string"&&t.title.length>0&&r.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&r.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&r.push(a.path);let i=Ap(t);return i!==void 0&&r.push(i),r.join(`
|
|
409
|
-
`)}function DH(n,e){if(n.length<=148)return n;let s=Math.floor(148/2),o=e-s;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function BH(n){let e=new OH({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. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. 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:qs.string().min(1).describe("Case-insensitive substring to search for."),limit:qs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:qs.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:r=10,include_tool_calls:s=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return Zn({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 i=[],a=t.toLowerCase();for await(let{entryId:c,entry:l}of o.iterRecallNewestFirst()){let u=Fb(l);if(!u)continue;let{kind:f,update:p}=u;if((f==="tool_call"||f==="tool_call_update")&&!s)continue;let m=NH(l,f,p),h=m.toLowerCase().indexOf(a);if(h<0)continue;let g=LH(f),w=DH(m,h),b=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(i.push({entryId:c,speaker:g,snippet:w,timestamp:b}),i.length>=r)break}i.sort((c,l)=>c.entryId-l.entryId);let d=i.length>=r;return Zn({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:qs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:qs.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:r})=>{let s=await n();if(!s.summarizedThroughEntry||s.summarizedThroughEntry===0)return Zn({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(r<t)throw new Error(`range: to_entry (${r}) must be >= from_entry (${t})`);let o=r-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await s.getRecallTotalCount();if(i===0)return Zn({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(r,i-1),c=a>t||d<r;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await s.sliceRecallHistory(a,d),u=gc(l,{toolOutput:{maxPerCall:uT,maxTotal:fT}});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, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:qs.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:qs.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:qs.string().optional(),limit:qs.number().int().min(1).max(100).optional(),include_output:qs.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:r,file_path:s,limit:o=20,include_output:i=!0})=>{let a=await n();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return Zn({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 d=typeof t=="string"&&t.length>0,c=typeof r=="string"&&r.length>0,l=typeof s=="string"&&s.length>0;if(!d&&!c&&!l)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let u=new Map,f=Math.max(o*4,200);for await(let{entryId:b,entry:k}of a.iterRecallNewestFirst()){let S=Fb(k);if(!S)continue;let{kind:I,update:x}=S;if(I!=="tool_call"&&I!=="tool_call_update")continue;let A=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:`__noid_${b}`,_=u.get(A);if(_||(_={entryId:b,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},u.set(A,_)),b<_.entryId&&(_.entryId=b),!_.nameAuthoritative){let $=Vl(x);$!==void 0?(_.toolName=$,_.nameAuthoritative=!0):typeof x.name=="string"&&x.name.length>0?(_.toolName=x.name,_.nameAuthoritative=!0):I==="tool_call"&&typeof x.title=="string"&&x.title.length>0&&(_.toolName=x.title,_.nameAuthoritative=!0)}if(_.kind===void 0&&typeof x.kind=="string"&&x.kind.length>0&&(_.kind=x.kind),_.output===void 0){let $=Ap(x);$!==void 0&&(_.output=$)}let P=x.rawInput;if(P&&typeof P=="object"&&!Array.isArray(P)&&Object.keys(P).length>0)for(let[$,F]of Object.entries(P))_.rawInput[$]===void 0&&(_.rawInput[$]=F);if(Array.isArray(x.locations))for(let $ of x.locations){let F=$?.path;typeof F=="string"&&F.length>0&&!_.locations.includes(F)&&_.locations.push(F)}if(typeof x.status=="string"&&_.status==="in_progress"&&(_.status=x.status),k.recordedAt!==void 0&&_.timestamp===void 0&&(_.timestamp=String(k.recordedAt)),u.size>=f)break}let p=[...u.keys()].sort((b,k)=>u.get(b).entryId-u.get(k).entryId),m=[],h=fT,g=!1;for(let b of p){let k=u.get(b);if(k.toolName=Cw({name:k.toolName,rawInput:k.rawInput,...k.kind!==void 0?{kind:k.kind}:{}}),d&&!k.toolName.toLowerCase().includes(t.toLowerCase())||c&&(k.kind??"").toLowerCase()!==r.toLowerCase())continue;if(l){let x=s.toLowerCase(),A=["file_path","filePath","path"],_=!1;for(let P of A){let $=k.rawInput[P];if(typeof $=="string"&&$.toLowerCase().includes(x)){_=!0;break}}if(!_){for(let P of k.locations)if(P.toLowerCase().includes(x)){_=!0;break}}if(!_)continue}let S={};for(let[x,A]of Object.entries(k.rawInput))typeof A=="string"?S[x]=A.length>500?A.slice(0,497)+"\u2026":A:(typeof A=="number"||typeof A=="boolean")&&(S[x]=A);k.locations.length>0&&S.locations===void 0&&(S.locations=k.locations);let I={entryId:k.entryId,tool:k.toolName,args:S,status:k.status,timestamp:k.timestamp};if(k.kind!==void 0&&(I.kind=k.kind),i&&k.output!==void 0){let x=k.output,A=Math.min(uT,h);if(A<=0)g=!0;else{let _=x.length<=A?x:x.slice(0,A-1)+"\u2026";I.output=_,I.outputBytes=x.length,I.outputTruncated=_.length<x.length,h-=_.length}}if(m.push(I),m.length>=o)break}let w=m.length>=o;return Zn({calls:m,truncated:w,...g?{outputBudgetExhausted:g}:{}})}),e}var HH=1e4;function pT(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=BH(a),l=new FH({sessionIdGenerator:()=>$H()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=_c(i);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 r(d,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(h=>{f=setTimeout(()=>h(void 0),HH)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)})}var qh=class{byName=new Map;changeHandlers=[];register(e,t,r,s){this.byName.set(e,{connection:t,instructions:r,tools:[...s]}),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 r of this.changeHandlers)try{r(e,t)}catch{}}};import{StreamableHTTPServerTransport as JH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as VH}from"crypto";import{Server as UH}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as WH,ListToolsRequestSchema as jH}from"@modelcontextprotocol/sdk/types.js";function hT(n,e,t,r){let s=typeof t=="function"?async()=>t():async()=>t,o=new UH({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(jH,async()=>{let a=r?.peekSessionId?.();if(a!==void 0&&r?.fetchSessionTools!==void 0)try{let d=await r.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(WH,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,u=zH(l,d.sendNotification);try{let f=await s(),p=await KH(e.connection,n,c,a.params.arguments??{},f);return GH(p,c)}catch(f){return Lb(f instanceof Error?f.message:String(f))}finally{u()}}),o}var qH=15e3;function zH(n,e,t=qH){if(n===void 0)return()=>{};let r=0,s=setInterval(()=>{r+=1,e({method:"notifications/progress",params:{progressToken:n,progress:r}}).catch(()=>{})},t);return s.unref?.(),()=>clearInterval(s)}async function KH(n,e,t,r,s){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:r,sessionId:s})}function GH(n,e){if(n===null||typeof n!="object")return Lb(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Lb(`extension ${e} omitted content array`)}function Lb(n){return{content:[{type:"text",text:n}],isError:!0}}var YH=1e4;function mT(n,e,t){let r=new Map;async function s(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),s(f))}}async function i(l,u){for(let[f,p]of r){if(e.lookup(f)?.session?.sessionId!==l)continue;let h=p.get(u);if(h!==void 0)try{await h.server.sendToolListChanged()}catch{}}}t.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let S=r.get(l);if(S!==void 0){r.delete(l);for(let I of S.values())await s(I)}}));let p=f.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let b=hT(u,m,async()=>{let S=e.lookup(l);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let I,x=new Promise(_=>{I=setTimeout(()=>_(void 0),YH)}),A=await Promise.race([S.sessionReady.catch(()=>{}),x]);if(I!==void 0&&clearTimeout(I),A===void 0)throw new Error("session not ready");return A.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async S=>{let I=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:S});if(!I||typeof I!="object")return;let x=I.tools;if(!Array.isArray(x))return;let A=[];for(let _ of x){if(!_||typeof _!="object")continue;let P=_;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),A.push($)}return A}}),k=new JH({sessionIdGenerator:()=>VH()});return await b.connect(k),f.set(u,{server:b,transport:k}),k}async function d(l,u){let f=_c(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 m=l.params.name,h=await a(f,m);if(h===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await h.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:i}}async function vT(n,e){rU(n),Ul(n.daemon.scrubEnv);let t=n,r=n.daemon.tls?await zs.readFile(mt(n.daemon.tls.key)):void 0,s=n.daemon.tls?await zs.readFile(mt(n.daemon.tls.cert)):void 0;await zs.mkdir(D.home(),{recursive:!0});let{stream:o,fileStream:i}=await tU(n.daemon.logLevel),a=QH({logger:{level:n.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(XH,{options:{handleProtocols:iI}}),ow(ce=>{a.log.info(ce)}),dw(ce=>{a.log.info(ce)});let d=await gh.load(),c=await Lh.load();_l(),Ry(c);let l=new Dh(c);l.start();let u=new Ph(c);u.start();let f=new vh,p=new kh,m=new yh(e),h=new bh([m,new wh(d),p]),g=ZR({validator:h});a.addHook("onRequest",async(ce,Je)=>{ce.routeOptions.config?.skipAuth||ce.url==="/acp"||ce.url?.startsWith("/acp?")||(await g(ce,Je),!Je.sent&&ce.authIdentity?.startsWith("script:")&&!tA(ce.method,ce.routeOptions.url)&&Je.code(403).send({error:"script tokens may only access read-only session data"}))});let w=setInterval(()=>{d.sweepExpired()},300*1e3);w.unref();let b=setInterval(()=>{f.sweepExpired()},300*1e3);b.unref();let k=new hp(n,{onFetched:()=>{HR(k,A)},onStaleFallback:(ce,Je)=>{let xe=Math.round(Je/36e5),an=xe>=48?`${Math.round(xe/24)}d`:`${xe}h`;a.log.warn(`registry fetch failed (${ce.message}); serving stale cache last synced ${an} ago; agent versions may be outdated ('hydra registry refresh' to retry)`)}});bb(ce=>a.log.info(ce));let S={info:ce=>a.log.info(ce),warn:ce=>a.log.warn(ce)},I=ce=>ni.spawn({...ce,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:S});fI(n.compressToolContent);let x=new hh,A=new sh(k,I,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:n.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,sessionDefaults:n.sessionDefaults,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:S,npmRegistry:n.npmRegistry,extensionCommands:x,defaultCwd:n.defaultCwd,disableWorkspaceSnapshots:n.disableWorkspaceSnapshots}),_=new Nh(c,void 0,{resolvesLocally:async ce=>await A.resolveCanonicalId(ce)!==void 0,cache:u}),P=new fh(fy(n),void 0,{tokenRegistry:p}),$=new ph(py(n),void 0,{tokenRegistry:p}),F=[];$A(a,Ue,ci(n),()=>F);let J=new jh,Y=new qh,W,Z=()=>{if(W!==void 0)return W;let ce=a.server.address();return W=`http://127.0.0.1:${ce&&typeof ce=="object"?ce.port:n.daemon.port}`,W},ne={agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction};MA(a,A,ne,{extensionMcp:Y,mcpTokenRegistry:J,getDaemonOrigin:Z},c,u),RA(a,{store:c,localMiss:{resolvesLocally:async ce=>await A.resolveCanonicalId(ce)!==void 0,cache:u}}),_A(a,k,A,{npmRegistry:n.npmRegistry}),OA(a,P),FA(a,$),LA(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,sessionDefaults:{...t.sessionDefaults},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]})),qA(a,{store:d,rateLimiter:f,staticTokenValidator:m}),VA(a,{store:c,health:l}),ZA(a,{processRegistry:p}),lT(a,J),pT(a,J);let ve=mT(a,J,Y);aT(a,{validator:h,manager:A,defaultAgent:n.defaultAgent,processRegistry:p,onExtensionVersion:(ce,Je)=>P.reportVersion(ce,Je),onTransformerVersion:(ce,Je)=>$.reportVersion(ce,Je),transformers:$,extensionCommands:x,mcpTokenRegistry:J,extensionMcp:Y,extensionMcpControls:ve,getDaemonOrigin:Z,registry:k,foreignSessions:_});let Ne=!!n.daemon.tls;await a.listen({host:Ne?"127.0.0.1":n.daemon.host,port:Ne?0:n.daemon.port});let Re=a.server.address(),Ge=Re&&typeof Re=="object"?Re.port:n.daemon.port,Ae,de=n.daemon.host,De=Ge;if(Ne&&r&&s){Ae=nU({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:Ge,tlsOptions:{key:r,cert:s},logger:a.log});let ce=Ae.address();ce&&typeof ce=="object"&&(De=ce.port)}await zs.mkdir(D.home(),{recursive:!0}),await dx({pid:process.pid,host:de,port:De,loopbackPort:Ge,startedAt:new Date().toISOString()});let it={daemonUrl:`http://127.0.0.1:${Ge}`,daemonHost:"127.0.0.1",daemonPort:Ge,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${Ge}/acp`,hydraHome:D.home()};P.setContext(it),$.setContext(it),await P.start(),await $.start();try{await A.reconcilePermissionFlags()}catch(ce){a.log.warn(`permission flag reconcile failed: ${ce.message}`)}try{await A.seedSessionIndex()}catch(ce){a.log.warn(`session index seed failed: ${ce.message}`)}A.resurrectPendingQueues().catch(ce=>{a.log.warn(`queue replay scan failed: ${ce.message}`)}),A.resumePendingCompactions().catch(ce=>{a.log.warn(`compaction resume scan failed: ${ce.message}`)}),A.resumePendingAgentSwaps().catch(ce=>{a.log.warn(`agent-swap resume scan failed: ${ce.message}`)});let Rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Me=Rt>0?UR({registry:k,manager:A,intervalMs:Rt,logger:S}):void 0,Kt=n.daemon.sessionGcIntervalMinutes*60*1e3,Ve=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ys=Kt>0?WR({manager:A,intervalMs:Kt,maxAgeMs:Ve,logger:S}):void 0,Ti=KR({bootConfig:n,apply:ce=>{t=ce,k.setConfig(ce),A.setLiveConfig({sessionDefaults:ce.sessionDefaults}),ne.agentId=ce.defaultAgent,ne.cwd=ce.defaultCwd,Ul(ce.daemon.scrubEnv)},onDrift:ce=>{F=ce},logger:S});return{app:a,manager:A,registry:k,extensions:P,transformers:$,mcpTokenRegistry:J,extensionMcp:Y,processRegistry:p,shutdown:async()=>{l.stop(),u.stop(),Ti(),ys&&ys(),Me&&Me(),clearInterval(w),clearInterval(b);let ce=async(Je,xe)=>{try{await xe()}catch(an){a.log.warn(`shutdown step ${Je} failed: ${an instanceof Error?an.message:String(an)}`)}};await ce("sessionTokenStore.flush",()=>d.flush()),await ce("extensions.stop",()=>P.stop()),await ce("transformers.stop",()=>$.stop()),await ce("manager.closeAll",()=>A.closeAll()),await ce("manager.flushSynopsis",()=>A.flushSynopsis(3e4)),await ce("manager.shutdownSynopsis",()=>A.shutdownSynopsis()),await ce("manager.flushMetaWrites",()=>A.flushMetaWrites()),await ce("manager.flushHistoryWrites",()=>A.flushHistoryWrites()),ow(null),dw(null),bb(null),Ae&&await ce("tlsTerminator.close",()=>new Promise(Je=>Ae.close(()=>Je()))),await ce("app.close",()=>a.close());try{wT.unlinkSync(D.pidFile())}catch{}await ce("fileStream.flushSync",()=>i.flushSync())}}}var yT=20;async function eU(n,e){let t=$c.dirname(n),r=$c.basename(n,".log"),s=new RegExp(`^${r}\\.(\\d+)\\.log$`),o;try{o=await zs.readdir(t)}catch{return}let i=[];for(let d of o){let c=d.match(s);c&&i.push({name:d,n:Number(c[1])})}if(i.length<=e)return;i.sort((d,c)=>d.n-c.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>zs.unlink($c.join(t,d.name))))}async function tU(n){await eU(D.logFile(),yT);let e=await ZH({file:D.logFile(),size:"10m",mkdir:!0,symlink:dh,limit:{count:yT,removeOtherLogFiles:!0}}),t=gT.destination(2);return{stream:gT.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function nU(n){let e=kT.createServer(n.tlsOptions,t=>{let r=bT.connect({host:n.upstreamHost,port:n.upstreamPort}),s=!1,o=i=>{if(!s){s=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{r.destroy()}catch{}}};t.on("error",o),r.on("error",o),t.on("close",()=>o()),r.on("close",()=>o()),t.pipe(r),r.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 rU(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.`)}Ra();dr();Rc();Ru();async function AT(n={}){let e=await go(),t=await Il();if(await zh(e)){let s=await Lc();process.stdout.write(`Daemon already running${s?` (pid ${s.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
|
|
408
|
+
`;await li.mkdir(D.home(),{recursive:!0}),await li.writeFile(Mb(),r,{encoding:"utf8",mode:384})}async function Oh(){try{return(await li.readFile(Mb(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Fh(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await li.readFile(Mb(),"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 r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await UA(n,i,a.length,{N:r,r:s,p:o,maxmem:WA});return d.length!==a.length?!1:GB(d,a)}var QB=ui.object({password:ui.string().min(1),label:ui.string().min(1).max(256).optional(),ttlSec:ui.number().int().positive().optional()}),XB=ui.object({id:ui.string().optional()}).optional(),ZB=ui.object({token:ui.string().min(32)});function qA(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,r)=>{let s=eH(t);if(e.rateLimiter.isBlocked(s))return r.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=QB.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}if(!await Oh())return r.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Fh(o.password))return e.rateLimiter.recordFailure(s),r.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(s);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return r.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,r)=>{let s;try{s=XB.parse(t.body??void 0)}catch{return r.code(400).send({error:"Invalid request body"})}let o=s?.id??t.authIdentity;if(!o||o==="service")return r.code(200).send({revoked:!1});let i=await e.store.revoke(o);return r.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,r)=>r.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,r)=>r.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions",async(t,r)=>{let s=await e.store.revokeAll();return r.code(200).send({revoked:s})}),n.delete("/v1/auth/sessions/:id",async(t,r)=>{let s=t.params.id;return await e.store.revoke(s)?r.code(204).send():r.code(404).send({error:"Not found"})}),n.post("/v1/auth/rotate-token",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=ZB.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(s.token),r.code(200).send({rotated:!0})})}function eH(n){return n.ip||"unknown"}rt();import{z as fi}from"zod";ke();es();var _b=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,Lh=class n{data;constructor(e){this.data=e}static async load(){let e=await jt(D.peers());return new n(tH(e))}get(e){return this.data.entries[e]}async set(e){this.data.entries[e.name]=e,await zA(this.data)}async delete(e){return e in this.data.entries?(delete this.data.entries[e],await zA(this.data),!0):!1}list(){return Object.values(this.data.entries).map(({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})=>({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})).sort((e,t)=>e.addedAt.localeCompare(t.addedAt))}};function tH(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},r={};for(let[s,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||typeof i.host!="string"||typeof i.port!="number"||typeof i.token!="string"||typeof i.expiresAt!="string"||typeof i.addedAt!="string")continue;let a={name:i.name,host:i.host,port:i.port,token:i.token,expiresAt:i.expiresAt,addedAt:i.addedAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),r[s]=a}return{version:1,entries:r}}async function zA(n){await nn(D.peers(),n,{mode:384})}Ts();var nH=3600*24*365,qs=class extends Error{status;constructor(e,t){super(e),this.name="PeerLoginError",this.status=t}};function KA(n,e){return`${Vt(n)?"http":"https"}://${n}:${e}`}async function GA(n){let e=n.fetchImpl??fetch,t=`${n.host}:${n.port}`,r=KA(n.host,n.port),s;try{s=await e(`${r}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n.password,label:n.label,ttlSec:n.ttlSec??nH})})}catch(i){throw new qs(`Could not reach ${t}: ${i.message}`,502)}if(s.status===401)throw new qs(`Wrong password for ${t}.`,401);if(s.status===403)throw new qs(`No password is configured on ${t}. Run \`hydra-acp auth password\` on that daemon first.`,502);if(s.status===429)throw new qs(`Too many failed login attempts on ${t}; try again later.`,429);if(!s.ok)throw new qs(`Login to ${t} failed: HTTP ${s.status}`,502);let o=await s.json();if(!o.session_token||!o.expires_at)throw new qs(`Login to ${t} returned a malformed response.`,502);return{token:o.session_token,expiresAt:o.expires_at}}async function JA(n){let e=n.fetchImpl??fetch,t=KA(n.host,n.port);try{await e(`${t}/v1/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch{}}Xo();var rH=fi.object({name:fi.string().min(1).max(64).regex(_b),host:fi.string().min(1),port:fi.number().int().positive().optional(),password:fi.string().min(1),label:fi.string().min(1).max(256).optional(),ttlSec:fi.number().int().positive().optional(),pinnedFingerprint:fi.string().min(1).optional()});function VA(n,e){n.post("/v1/remotes",async(t,r)=>{let s;try{s=rH.parse(t.body)}catch{return r.code(400).send({error:`Invalid request body (name must match ${_b} and the rest is a normal login request)`})}let o=s.port??An;s.pinnedFingerprint&&Yo(s.host,o,s.pinnedFingerprint);let i;try{i=await GA({host:s.host,port:o,password:s.password,label:s.label,ttlSec:s.ttlSec})}catch(c){if(c instanceof qs)return r.code(c.status).send({error:c.message});throw c}let a=new Date().toISOString(),d={name:s.name,host:s.host,port:o,token:i.token,expiresAt:i.expiresAt,addedAt:a,...s.label!==void 0?{label:s.label}:{},...s.pinnedFingerprint!==void 0?{pinnedFingerprint:s.pinnedFingerprint,pinnedAt:a}:{}};return await e.store.set(d),e.health?.markOk(d.name),r.code(201).send({name:d.name,host:d.host,port:d.port,expiresAt:d.expiresAt,label:d.label,addedAt:d.addedAt,pinnedFingerprint:d.pinnedFingerprint,status:e.health?.get(d.name)?.status??"unknown"})}),n.get("/v1/remotes",async(t,r)=>{let s=e.store.list().map(o=>{let i=e.health?.get(o.name);return{...o,status:i?.status??"unknown",...i?.checkedAt?{lastCheckedAt:i.checkedAt}:{}}});return r.code(200).send({remotes:s})}),n.delete("/v1/remotes/:name",async(t,r)=>{let s=t.params.name,o=e.store.get(s);return o?(await JA({host:o.host,port:o.port,token:o.token}),await e.store.delete(s),e.health?.forget(s),e.store.list().some(a=>a.host===o.host&&a.port===o.port)||xy(o.host,o.port),r.code(204).send()):r.code(404).send({error:"Not found"})})}ko();Sa();qd();Ts();Gl();fn();var sH=new Set(["session/attach","session/detach","session/prompt","session/cancel","session/close","session/delete","hydra-acp/session/delete","session/set_model","session/set_mode","session/set_config_option","_session/steering","hydra-acp/prompt/cancel","hydra-acp/prompt/update","hydra-acp/prompt/amend","hydra-acp/session/tool_content","hydra-acp/session/force_cancel"]);function oH(n){return sH.has(n)}function QA(n,e,t,r){let s=[],o=a=>{for(let d of s)d(a)},i=(a,d)=>{e.handleLocalMessage(a,d,{connection:t.connection,clientId:r}).then(c=>c?n.send(c):void 0).catch(()=>{})};return n.onMessage(a=>{if("method"in a&&oH(a.method)){let d=a.params,c=typeof d?.sessionId=="string"?d.sessionId:void 0;if(c){if(Bs(c)){i(a,c);return}if(a.method==="session/attach"){let l="id"in a;e.resolveLocalMiss(c).then(u=>{if(u.ok){i(a,u.foreignId);return}if(u.ambiguous&&l){n.send(Iu(a.id,G.SessionNotFound,`Session "${c}" exists on more than one remote (${u.ambiguous.join(", ")}). Address it as "<remote>:${c}".`));return}o(a)});return}}}o(a)}),{send:a=>n.send(a),onMessage:a=>s.push(a),onClose:a=>n.onClose(a),close:()=>n.close()}}var Nh=class{constructor(e,t=aH,r){this.store=e;this.dial=t;this.localMiss=r}store;dial;localMiss;attachments=new Map;async resolveLocalMiss(e){if(!this.localMiss)return{ok:!1};if(await this.localMiss.resolvesLocally(e))return{ok:!1};let t=this.localMiss.cache.findByLocalId(e);return t.length===0?{ok:!1}:t.length>1?{ok:!1,ambiguous:t.map(r=>r.name)}:{ok:!0,foreignId:Ds(t[0])}}async handleLocalMessage(e,t,r){let s="id"in e,o=s?e.id:void 0,i=Bs(t);if(!i)return s?Iu(o,G.SessionNotFound,`not a federated session id: ${t}`):void 0;let a=YA(r.clientId,t),d={...e.params,sessionId:i.localId};if(e.method==="session/attach"){let l=this.store.get(i.name);if(!l)return s?Iu(o,G.SessionNotFound,`No remote named "${i.name}". Run \`hydra remote add\` first.`):void 0;let u=this.attachments.get(a);u&&(this.attachments.delete(a),u.peerConnection.close().catch(()=>{}));let f;try{f=await this.dial(l)}catch(g){return s?Iu(o,G.InternalError,`Could not reach remote "${i.name}": ${g.message}`):void 0}let p={peerConnection:f,localId:i.localId,target:r};this.wireAttachment(i.name,p);let m;try{m=await f.request("session/attach",d)}catch(g){return f.close().catch(()=>{}),s?$b(o,g):void 0}this.attachments.set(a,p);let h=m&&typeof m.sessionId=="string"?{...m,sessionId:t}:m;return s?{jsonrpc:"2.0",id:o,result:h}:void 0}let c=this.attachments.get(a);if(!c)return s?Iu(o,G.SessionNotFound,`"${t}" is not attached through this daemon.`):void 0;if(e.method==="session/detach"){let l,u;try{l=await c.peerConnection.request("session/detach",d)}catch(f){u=f}return this.attachments.delete(a),c.peerConnection.close().catch(()=>{}),u?s?$b(o,u):void 0:s?{jsonrpc:"2.0",id:o,result:l??{}}:void 0}if(s)try{let l=await c.peerConnection.request(e.method,d);return{jsonrpc:"2.0",id:o,result:l}}catch(l){return $b(o,l)}await c.peerConnection.notify(e.method,d).catch(()=>{})}detachClient(e){for(let[t,r]of[...this.attachments.entries()])r.target.clientId===e&&(this.attachments.delete(t),r.peerConnection.request("session/detach",{sessionId:r.localId}).catch(()=>{}),r.peerConnection.close().catch(()=>{}))}wireAttachment(e,t){let{peerConnection:r,localId:s,target:o}=t,i=Ds({name:e,localId:s}),a=()=>{this.attachments.delete(YA(o.clientId,i))};r.onAnyNotification((d,c)=>{let l=d;!l||l.sessionId!==s||(c==="hydra-acp/session/closed"&&a(),o.connection.notify(c,{...l,sessionId:i}).catch(()=>{}))}),r.onRequest("hydra-acp/session/request_permission",async d=>{let c=d;if(!c||c.sessionId!==s)throw{code:G.MethodNotFound,message:"unexpected sessionId"};return o.connection.request("hydra-acp/session/request_permission",{...c,sessionId:i})}),r.onClose(()=>{a(),o.connection.notify("hydra-acp/session/closed",{sessionId:i}).catch(()=>{})})}};function YA(n,e){return`${n} ${e}`}function Iu(n,e,t){return{jsonrpc:"2.0",id:n,error:{code:e,message:t}}}function $b(n,e){let t=e,r=typeof t?.code=="number"?t.code:G.InternalError,s=typeof t?.message=="string"?t.message:String(e??"forward failed");return{jsonrpc:"2.0",id:n,error:{code:r,message:s,...t?.data!==void 0?{data:t.data}:{}}}}var iH=1e4;async function aH(n){let t=`${Vt(n.host)?"ws":"wss"}://${n.host}:${n.port}/acp`,r=await bo(t,["acp.v1",`hydra-acp-token.${n.token}`],iH);return new pn(Rr(r))}Ts();var dH=3e4,cH=5e3,Dh=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;snapshots=new Map;timer;start(){this.timer||(this.checkAll(),this.timer=setInterval(()=>{this.checkAll()},this.opts.intervalMs??dH),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get(e){return this.snapshots.get(e)}markOk(e){this.snapshots.set(e,{status:"ok",checkedAt:new Date().toISOString()})}forget(e){this.snapshots.delete(e)}async checkAll(){let e=this.opts.fetchImpl??fetch;await Promise.allSettled(this.store.list().map(async t=>{let r=this.store.get(t.name);if(!r)return;let o=`${Vt(r.host)?"http":"https"}://${r.host}:${r.port}/v1/auth/verify`,i=new AbortController,a=setTimeout(()=>i.abort(),cH);try{let d=await e(o,{headers:{Authorization:`Bearer ${r.token}`},signal:i.signal});this.snapshots.set(t.name,{status:d.ok?"ok":"unauthorized",checkedAt:new Date().toISOString()})}catch(d){this.snapshots.set(t.name,{status:"unreachable",checkedAt:new Date().toISOString(),error:d.message})}finally{clearTimeout(a)}}))}};Xo();import{z as XA}from"zod";var lH=XA.object({sessionLabel:XA.string().min(1).max(256)});function ZA(n,e){n.post("/v1/process-tokens",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=lH.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}let o=e.processRegistry.mint(s.sessionLabel,"script");return r.code(201).send({token:o})}),n.delete("/v1/process-tokens/:sessionLabel",async(t,r)=>t.authIdentity!=="service"?r.code(403).send({error:"Requires the service token"}):(e.processRegistry.revoke(t.params.sessionLabel),r.code(204).send()))}ko();Sc();Sa();import{nanoid as Ob}from"nanoid";Rp();fn();Os();Od();dr();import{randomBytes as sT}from"crypto";import*as oT from"os";import*as iT from"path";cc();var uH=200;function fH(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[ut];if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.sentBy;if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o={};if(typeof s.sessionId=="string"&&s.sessionId.length>0&&(o.sessionId=s.sessionId),typeof s.label=="string"&&s.label.length>0&&(o.label=s.label.slice(0,uH)),s.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function eT(n,e,t){let r=fH(n);if(!r)return;let s={};if(r.label!==void 0&&(s.fromLabel=r.label),r.awaiting===!0&&(s.awaiting=!0),r.sessionId!==void 0){let o=await e.resolveCanonicalId(r.sessionId)??r.sessionId,i=await e.getOne(o);if(i){s.fromSession=o,i.title&&(s.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;s.depth=(a??0)+1}else t?.(r.sessionId)}if(!(s.fromSession===void 0&&s.fromLabel===void 0))return s}var Cu=new Map;function tT(n,e){let t=Cu.get(n);t||(t=new Set,Cu.set(n,t)),t.add(e);let r=!1;return()=>{if(r)return;r=!0;let s=Cu.get(n);s&&(s.delete(e),s.size===0&&Cu.delete(n))}}function nT(n,e){if(n===e)return!0;let t=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(t.has(s))continue;t.add(s);let o=Cu.get(s);if(o){if(o.has(n))return!0;for(let i of o)r.push(i)}}return!1}function he(n,e,t){let r=new Error(e);return r.code=n,t!==void 0&&(r.data=t),r}function yH(n){if(!n||typeof n!="object")return 512;let r=n.params?.update;if(!r)return 512;let s=512,o=r.content;if(typeof o=="string")s+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(s+=a.text.length),typeof a.data=="string"&&(s+=a.data.length)}let i=r.toolCall;if(i&&(typeof i.rawInput=="string"?s+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(s+=256),typeof i.rawOutput=="string"?s+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(s+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(s+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(s+=c.text.length)}}return s}function cr(n,e,t){let r=n.get(e);if(!r)throw he(G.SessionNotFound,t??`session ${e} not found`);return r}async function xa(n,e){let t=Pc(n),r,s,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(r=sT(32).toString("hex"),s=n.mcpTokenRegistry.reserve(r),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${r}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=Tb({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),s!==void 0&&s.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(c),r!==void 0&&s!==void 0&&n.mcpTokenRegistry!==void 0){let l=r,u=n.mcpTokenRegistry;s.complete(c),c.onClose(()=>{u.unbind(l)})}return AH(c,n),dT(c.sessionId,n),c}function aT(n,e){n.get("/acp",{websocket:!0},async(t,r)=>{let s=eA({headers:r.headers,url:r.url});if(!s||!await e.validator.validate(s)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(s),i=`hydra_client_${Ob(12)}`,a=Rr(t),d={},c=e.foreignSessions?QA(a,e.foreignSessions,d,i):a,l=new pn(c);d.connection=l;let u={clientId:i,processIdentity:o,attached:new Map};l.onClose(()=>{for(let m of u.attached.values())e.manager.get(m.sessionId)?.detach(m.clientId);u.attached.clear(),e.foreignSessions?.detachClient(i)});let f=(m,h)=>{if(u.attached.get(m)?.readonly)throw he(G.PermissionDenied,`${h} not permitted on a read-only attachment`)};if(l.onRequest("initialize",async m=>{let h=$I.parse(m??{});h.clientInfo?.name&&(u.clientInfo={name:h.clientInfo.name,...h.clientInfo.version!==void 0?{version:h.clientInfo.version}:{}});let g=h.clientInfo?.version;return g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g)),RH()}),o&&e.extensionCommands){let m=e.extensionCommands;l.onRequest("hydra-acp/commands/register",async h=>{let g=h??{},w=Array.isArray(g.commands)?g.commands.map(b=>{if(!b||typeof b!="object")return;let k=b;if(typeof k.verb!="string")return;let S={verb:k.verb};return typeof k.argsHint=="string"&&(S.argsHint=k.argsHint),typeof k.description=="string"&&(S.description=k.description),S}).filter(b=>b!==void 0):[];return m.register(o.name,l,w),{ok:!0,registered:w.length}}),l.onClose(()=>{m.clear(o.name)})}if(o&&e.extensionMcp){let m=e.extensionMcp;l.onRequest("hydra-acp/mcp_tools/register",async g=>{let w=g??{},b=typeof w.instructions=="string"?w.instructions:void 0,k=Array.isArray(w.tools)?w.tools.map(S=>{if(!S||typeof S!="object")return;let I=S;if(typeof I.name!="string"||I.name.length===0||typeof I.description!="string"||I.inputSchema===null||typeof I.inputSchema!="object")return;let x={name:I.name,description:I.description,inputSchema:I.inputSchema};return I.outputSchema!==null&&typeof I.outputSchema=="object"&&(x.outputSchema=I.outputSchema),x}).filter(S=>S!==void 0):[];if(k.length===0)throw new Error("register_mcp_tools requires at least one tool");return m.register(o.name,l,b,k),{ok:!0,registered:k.length}});let h=g=>{let w=g??{};if(typeof w.sessionId!="string"||w.sessionId.length===0)throw he(G.InvalidParams,"sessionId is required");return w.sessionId};if(l.onRequest("hydra-acp/session/extension_state/get",async g=>{let w=h(g),b=g??{};if(typeof b.key!="string"||b.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(w,o.name,b.key)??null}}),l.onRequest("hydra-acp/session/extension_state/list",async g=>{let w=h(g);if(!e.manager)throw he(G.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(w,o.name)}}),l.onRequest("hydra-acp/session/extension_state/set",async g=>{let w=h(g),b=g??{};if(typeof b.key!="string"||b.key.length===0)throw he(G.InvalidParams,"key is required");if(b.value===void 0)throw he(G.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw he(G.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(w,o.name,b.key,b.value)}catch(k){throw he(G.InvalidParams,k.message)}return{ok:!0}}),l.onRequest("hydra-acp/session/extension_state/delete",async g=>{let w=h(g),b=g??{};if(typeof b.key!="string"||b.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(w,o.name,b.key),{ok:!0}}),e.extensionMcpControls){let g=e.extensionMcpControls;l.onRequest("hydra-acp/mcp_tools/refresh_session",async w=>{let b=w??{};if(typeof b.sessionId!="string"||b.sessionId.length===0)throw he(G.InvalidParams,"refresh_session requires sessionId");return await g.notifyToolListChanged(b.sessionId,o.name),{ok:!0}})}l.onClose(()=>{m.clear(o.name)})}if(o?.kind==="transformer"){l.onRequest("hydra-acp/transformer/initialize",async h=>{let g=h??{},w=Array.isArray(g.intercepts)?g.intercepts.filter(b=>typeof b=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,l,w),e.manager?.defaultTransformers.includes(o.name))){let b=e.transformers.resolveChain([o.name])[0];if(b)for(let k of e.manager.liveSessions())k.addTransformer(b)}return{ack:!0}}),l.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),l.onRequest("hydra-acp/message/emit",async h=>{let g=h??{},w=typeof g.sessionId=="string"?g.sessionId:void 0,b=typeof g.method=="string"?g.method:void 0,k=g.envelope,S=g.route;if(!w)throw he(-32602,"emit_message requires sessionId");if(!b&&S!=="client_broadcast")throw he(-32602,"emit_message requires method");let I=cr(e.manager,w),x=typeof g.respondsTo=="string"?g.respondsTo:void 0;if(x)return I.dischargeClaim(x,k),{ok:!0};if(S==="chain")return{ok:!0,response:await I.emitToChain(o.name,b,k)};if(S==="queue"){if(b!=="session/prompt")throw he(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await I.emitToQueue(o.name,k)}}if(S==="daemon")return{ok:!0,response:await I.emitToChain(o.name,b,k)};if(S==="client_broadcast"){if(!k||typeof k!="object")throw he(-32602,"client_broadcast requires an envelope object");return I.broadcastClientUpdate(k),{ok:!0}}throw he(-32602,`unsupported route: ${JSON.stringify(S)}`)}),l.onRequest("hydra-acp/session/request_permission",async h=>{let g=h??{},w=typeof g.sessionId=="string"?g.sessionId:void 0;if(!w)throw he(-32602,"hydra-acp/session/request_permission requires sessionId");return cr(e.manager,w).requestPermissionFromClients(g)}),l.onRequest("hydra-acp/transformer/attach",async h=>SH(h,o.name,e)),l.onRequest("hydra-acp/child_session/spawn",async h=>{let g=h??{},w=typeof g.agentId=="string"?g.agentId:void 0,b=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.parentSessionId=="string"?g.parentSessionId:void 0,S=Pn(g._meta??void 0),I=S.title,x=S.model,A=S.workspace;if(!b&&k){let Z=e.manager.get(k);Z&&(b=Z.cwd)}if(!b)throw he(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let _=await $d(b),P=w??_.agentId??e.defaultAgent,$=await e.registry?.getAgent(P),F=xr(_.configDefaults,$??{id:P})?.value,J=x??F?.model,Y=typeof g.interactive=="boolean"?g.interactive:!1,W=await e.manager.create({agentId:P,cwd:b,parentSessionId:k,interactive:Y,transformChain:[],title:I,model:J,configDefaults:F,...A!==void 0?{workspace:A}:{}});return{childSessionId:W.sessionId,...W.workspace!==void 0||W.workspaceError!==void 0?{_meta:{[ut]:{...W.workspace!==void 0?{workspaceInfo:W.workspace}:{},...W.workspaceError!==void 0?{workspaceError:W.workspaceError}:{}}}}:{}}}),l.onRequest("hydra-acp/session/fork",async h=>{let g=h??{};if(typeof g.sessionId!="string")throw he(G.InvalidParams,"fork_session requires sessionId");let w=typeof g.forkAt=="string"?g.forkAt:void 0,b=typeof g.cwd=="string"?g.cwd:void 0,k=typeof g.agentId=="string"?g.agentId:void 0,S=typeof g.mode=="string"&&(g.mode==="verbatim"||g.mode==="synthesis")?g.mode:void 0,I=typeof g.model=="string"&&g.model.length>0?g.model:void 0,x=await e.manager.forkSession(g.sessionId,{...w!==void 0?{forkAt:w}:{},...b!==void 0?{cwd:b}:{},...k!==void 0?{agentId:k}:{},...S!==void 0?{mode:S}:{},...I!==void 0?{model:I}:{}}),A=e.manager.get(x.sessionId);if(!A){let $=await e.manager.loadFromDisk(x.sessionId);if(!$)throw he(G.InternalError,`fork ${x.sessionId} vanished before it could be attached`);A=await xa(e,{...$,onInstallProgress:Bh(l)})}Mc(u,A,A.sessionId);let _=pi(l,A,u),{entries:P}=await A.attach(_,"full");u.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:_.clientId,readonly:!1});for(let $ of P){if(l.isClosed())break;await l.notify($.method,Ls(Fs($.params,$.recordedAt),$.seq)).catch(()=>{})}return{...x,sessionId:A.sessionId}}),l.onRequest("session/fork",async h=>{let g=h??{};if(typeof g.sessionId!="string")throw he(G.InvalidParams,"session/fork requires sessionId");let w=typeof g.cwd=="string"?g.cwd:void 0,b=await e.manager.forkSession(g.sessionId,{...w!==void 0?{cwd:w}:{},mode:"verbatim"}),k=e.manager.get(b.sessionId);if(!k){let x=await e.manager.loadFromDisk(b.sessionId);if(!x)throw he(G.InternalError,`fork ${b.sessionId} vanished before it could be attached`);k=await xa(e,{...x,onInstallProgress:Bh(l)})}Mc(u,k,k.sessionId);let S=pi(l,k,u),{entries:I}=await k.attach(S,"full");u.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:S.clientId,readonly:!1});for(let x of I){if(l.isClosed())break;await l.notify(x.method,Ls(Fs(x.params,x.recordedAt),x.seq)).catch(()=>{})}return{sessionId:k.sessionId}});let m=async(h,g)=>{let w=h??{};if(typeof w.sessionId!="string")throw he(G.InvalidParams,`${g} requires sessionId`);let b=await e.manager.resolveCanonicalId(w.sessionId)??w.sessionId,k=e.manager.get(b);if(k)return await k.close({deleteRecord:!0,by:`session/delete ${u.clientId}`}),await e.manager.waitForDeletion(b),await e.manager.hasRecord(b)&&await e.manager.deleteRecord(b),{id:b,existed:!0};let S=await e.manager.deleteRecord(b);return{id:b,existed:S}};l.onRequest("session/delete",async h=>(await m(h,"session/delete"),{})),l.onRequest("session/close",async h=>{let g=h??{};if(typeof g.sessionId!="string")throw he(G.InvalidParams,"session/close requires sessionId");f(g.sessionId,"session/close");let w=await e.manager.resolveCanonicalId(g.sessionId)??g.sessionId,b=e.manager.get(w);if(b)return await b.close({deleteRecord:!1,by:`session/close ${u.clientId}`+(u.processIdentity?` (${u.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(w))return{};throw he(G.SessionNotFound,`session ${w} not found`)}),l.onRequest("hydra-acp/session/delete",async h=>{let{id:g,existed:w}=await m(h,"hydra-acp/session/delete");if(!w)throw he(G.SessionNotFound,`session ${g} not found`);return{deleted:!0,sessionId:g}}),l.onRequest("hydra-acp/child_session/await",async h=>{let g=h??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0,b=g.until==="idle"?"idle":"turn_complete",k=typeof g.timeoutMs=="number"?Math.min(g.timeoutMs,18e5):3e5;if(!w)throw he(-32602,"await_child requires childSessionId");let S=cr(e.manager,w,`child session ${w} not found`);return new Promise(I=>{let _=[],P=[],$=0,F=!1,J,Y,W=!1,Z=()=>{W||(W=!0,clearTimeout(ne),J?.(),Y?.(),I(F?{entries:_,truncated:!0}:{entries:_}))};J=S.onBroadcast(ve=>{let Ne=yH(ve);for(_.push(ve),P.push(Ne),$+=Ne;_.length>0&&(_.length>1e3||$>1048576);)_.shift(),$-=P.shift()??0,F=!0;b==="turn_complete"&&ve.params?.update?.sessionUpdate==="turn_complete"&&Z()});let ne=setTimeout(Z,k);typeof ne.unref=="function"&&ne.unref(),Y=S.onClose(()=>Z())})}),l.onRequest("hydra-acp/child_session/close",async h=>{let g=h??{},w=typeof g.childSessionId=="string"?g.childSessionId:void 0;if(!w)throw he(-32602,"close_child_session requires childSessionId");let b=e.manager.get(w);return b&&await b.close({deleteRecord:!1,by:`child_session/close ${u.clientId}`}),{ok:!0}}),l.onRequest("hydra-acp/attention/set",async h=>xH(h,o.name,e)),l.onRequest("hydra-acp/attention/clear",async h=>IH(h,o.name,e)),l.onRequest("hydra-acp/connection/keep_alive",async h=>{let g=h??{},w=typeof g.token=="string"?g.token:void 0,b=typeof g.sessionId=="string"?g.sessionId:void 0,k=typeof g.estimatedRemainingMs=="number"?g.estimatedRemainingMs:void 0;return w&&b&&e.manager.get(b)?.keepAliveClaim(w,k),{ok:!0}})}l.onRequest("hydra-acp/session/tool_content",async m=>{let h=m??{};if(typeof h.sessionId!="string"||typeof h.hash!="string")throw he(G.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let g=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,w=await e.manager.loadToolBlob(g,h.hash);if(w===null)throw he(G.SessionNotFound,"tool content not found");return{content:w}}),l.onRequest("authenticate",async m=>wH(m,e)),l.onRequest("logout",async m=>bH(m,e)),l.onRequest("session/new",async m=>{let h=OI.parse(m),g=Pn(m?._meta),w=Array.isArray(g.transformers)&&g.transformers.every(Re=>typeof Re=="string")?g.transformers:e.manager.defaultTransformers??[],b=e.transformers?.resolveChain(w)??[],k=await $d(h.cwd),S=g.agentId??k.agentId??e.defaultAgent,I=await e.registry?.getAgent(S),x=xr(k.configDefaults,I??{id:S})?.value,A,_,P=h.mcpServers;if(g.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){A=sT(32).toString("hex"),_=e.mcpTokenRegistry.reserve(A);let Ge={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${A}`}]};P=[...h.mcpServers??[],Ge]}let $,F,J=Pc(e);J!==void 0&&(P=[...P??[],...J.descriptors]);let Y=Tb({baselineMcpServers:h.mcpServers,stdinEnabled:g.mcpStdin===!0,deps:e}),W;try{W=await e.manager.create({cwd:h.cwd,agentId:S,mcpServers:P,title:g.title,agentArgs:g.agentArgs,model:g.model??x?.model,configDefaults:x,onInstallProgress:Bh(l),transformChain:b,originatingClient:u.clientInfo,...g.interactive!==void 0?{interactive:g.interactive}:{},...g.env!==void 0?{forwardedEnv:g.env}:{},...g.workspace!==void 0?{workspace:g.workspace}:{},...Y?{mintMcpServersForSwap:Y}:{}})}catch(Re){throw _!==void 0&&_.abandon(Re instanceof Error?Re:void 0),F!==void 0&&F.abandon(Re instanceof Error?Re:void 0),J!==void 0&&J.abandon(Re instanceof Error?Re:void 0),Re}if(A!==void 0&&_!==void 0&&e.mcpTokenRegistry!==void 0){let Re=A,Ge=e.mcpTokenRegistry;_.complete(W),W.onClose(()=>{Ge.unbind(Re)})}if($!==void 0&&F!==void 0&&e.mcpTokenRegistry!==void 0){let Re=$,Ge=e.mcpTokenRegistry;F.complete(W),W.onClose(()=>{Ge.unbind(Re)})}J!==void 0&&J.bindToSession(W),dT(W.sessionId,e);let Z,ne;try{Mc(u,W,W.sessionId),Z=pi(l,W,u),{entries:ne}=await W.attach(Z,"full")}catch(Re){throw await W.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),Re}u.attached.set(W.sessionId,{sessionId:W.sessionId,clientId:Z.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let Re of ne){if(l.isClosed())break;await l.notify(Re.method,Ls(Fs(Re.params,Re.recordedAt),Re.seq)).catch(()=>{})}})()});let ve=Hh(W),Ne=Uh(W);return{sessionId:W.sessionId,...ve?{modes:ve}:{},...Ne?{models:Ne}:{},configOptions:W.buildConfigOptions(),_meta:Wh(e.manager,W,{clientId:Z.clientId})}}),l.onRequest("session/attach",async m=>{let h=LI.parse(m),g=h.clientInfo?.version;g&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,g):e.onTransformerVersion?.(o.name,g));let w=Pn(h._meta),b=w.resume,k=w.readonly===!0,S=w.env;n.log.info(`session/attach sessionId=${h.sessionId} hasResumeHints=${!!b} readonly=${k}`);let I=b?h.sessionId:await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,x=e.manager.get(I);if(!x&&k){let W=await e.manager.loadFromDisk(I);if(!W)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);let Z=await e.manager.loadHistory(I,{...w.historyLimit!==void 0?{maxEntries:w.historyLimit}:{}}),ne=h.clientId??`cli_${Ob(8)}`;u.attached.set(W.hydraSessionId,{sessionId:W.hydraSessionId,clientId:ne,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${W.hydraSessionId} clientId=${ne} attachedCount=${u.attached.size} replayed=${Z.length}`);for(let ve of Z)await l.notify(ve.method,Ls(Fs(ve.params,ve.recordedAt),ve.seq)).catch(()=>{});return{sessionId:W.hydraSessionId,clientId:ne,connectedClients:[ne],historyPolicy:"full",replayed:Z.length,_meta:CH(W)}}let A=!x;if(!x){let W=await e.manager.loadFromDisk(I),Z=await kH(I,b,W?.upstreamSessionId,e.manager);Z.kind==="ignore"&&n.log.warn(Z.logMessage);let ne=W;if(b&&Z.kind==="honor"&&(ne={...W,hydraSessionId:h.sessionId,upstreamSessionId:b.upstreamSessionId,agentId:b.agentId,cwd:W?.workspace?.path??b.cwd,...b.title!==void 0?{title:b.title}:{},...b.agentArgs!==void 0?{agentArgs:b.agentArgs}:{}}),!ne)throw he(G.SessionNotFound,`session ${h.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(ne.agentId,ne.upstreamSessionId))throw he(G.SessionNotFound,`session ${h.sessionId} was deleted`);let ve=ne.originatingClient?ne:{...ne,originatingClient:u.clientInfo},Ne=S!==void 0?{...ve,forwardedEnv:S}:ve;x=await xa(e,{...Ne,onInstallProgress:Bh(l)})}Mc(u,x,x.sessionId);let _=pi(l,x,u,h.clientInfo,h.clientId),P=w.replayMode==="drip",{entries:$,appliedPolicy:F}=await x.attach(_,h.historyPolicy,{afterMessageId:h.afterMessageId,afterSeq:h.afterSeq,raw:P,...w.historyLimit!==void 0?{historyLimit:w.historyLimit}:{},...w.toolContent!==void 0?{toolContent:w.toolContent}:{}});if(u.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:_.clientId,readonly:k}),S!==void 0&&await e.manager.setForwardedEnv(x.sessionId,S).catch(()=>{}),n.log.info(`session/attach OK sessionId=${x.sessionId} clientId=${_.clientId} attachedCount=${u.attached.size} requestedPolicy=${h.historyPolicy} appliedPolicy=${F} replayed=${$.length} readonly=${k}${P?" replayMode=drip":""}`),P){let W=w.dripSpeed&&w.dripSpeed>0?w.dripSpeed:1,Z=750;(async()=>{let ne=null;for(let ve of $){let Ne=typeof ve.recordedAt=="number"?ve.recordedAt:null;if(ne!==null&&Ne!==null){let Re=Math.min(Z,Math.max(0,(Ne-ne)/W));Re>0&&await new Promise(Ge=>setTimeout(Ge,Re))}Ne!==null&&(ne=Ne);try{await l.notify(ve.method,Ls(Fs(ve.params,Ne??void 0),ve.seq))}catch{return}}})()}else for(let W=0;W<$.length&&!l.isClosed();W++){let Z=$[W],ne=l.notify(Z.method,Ls(Fs(Z.params,Z.recordedAt),Z.seq)).catch(()=>{});(W+1)%200===0&&await ne}x.replayPendingPermissions(_);let J=Hh(x),Y=Uh(x);return{sessionId:x.sessionId,clientId:_.clientId,connectedClients:x.connectedClients(_.clientId),historyPolicy:F,replayed:$.length,...J?{modes:J}:{},...Y?{models:Y}:{},configOptions:x.buildConfigOptions(),_meta:Wh(e.manager,x,{resurrected:A})}}),l.onRequest("session/detach",async m=>{let h=NI.parse(m),g=u.attached.get(h.sessionId);if(!g)throw he(G.SessionNotFound,"client not attached to that session");let w=e.manager.get(h.sessionId);return w?.detach(g.clientId),u.attached.delete(h.sessionId),w&&e.manager.reapIfOrphanedNonInteractive(h.sessionId),{sessionId:h.sessionId,_meta:{[ut]:{detachStatus:"detached"}}}}),l.onRequest("session/list",async m=>{let h=DI.parse(m??{});return{sessions:(await e.manager.list({cwd:h.cwd})).filter(k=>k.originatingClient?.name!==pa).map(BI)}}),l.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw he(G.InternalError,"agent registry unavailable");return dc(e.registry)}),l.onRequest("hydra-acp/agents/auth_methods",async m=>{let h=m??{};if(typeof h.agentId!="string"||h.agentId.length===0)throw he(G.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(h.agentId)).authMethods??[]}}),l.onRequest("session/prompt",async m=>{let h=UI.parse(m);f(h.sessionId,"session/prompt");let g=await eT(h,e.manager,S=>{n.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${S} sessionId=${h.sessionId}`)});if(g?.fromSession!==void 0){if((g.depth??0)>3)throw n.log.warn(`session/prompt: refusing depth ${g.depth} chain from ${g.fromSession} to ${h.sessionId}`),he(G.InvalidRequest,`message chain too deep (${g.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(g.awaiting===!0&&nT(g.fromSession,h.sessionId))throw n.log.warn(`session/prompt: refusing deadlock ${g.fromSession} -> ${h.sessionId}`),he(G.InvalidRequest,`would deadlock: ${h.sessionId} is already blocked waiting on ${g.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let w=u.attached.get(h.sessionId);if(!w)throw n.log.warn(`session/prompt rejected: not attached sessionId=${h.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),he(G.SessionNotFound,"not attached to session");let b=e.manager.get(h.sessionId);if(!b){let S=await e.manager.loadFromDisk(h.sessionId);if(!S)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${h.sessionId}`),b=await xa(e,S);let I=pi(l,b,u,void 0,w.clientId);await b.attach(I,"none")}let k=g?.awaiting===!0&&g.fromSession!==void 0?tT(g.fromSession,h.sessionId):void 0;try{return await b.prompt(w.clientId,h,g)}finally{k?.()}});let p=m=>{let h;try{h=wp.parse(m)}catch(b){n.log.warn(`session/cancel: invalid params: ${b.message}`);return}let g=u.attached.get(h.sessionId);if(!g)return;if(g.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${h.sessionId}`);return}let w=e.manager.get(h.sessionId);w&&w.cancel(g.clientId).catch(b=>{n.log.warn(`session/cancel for ${h.sessionId}: ${b.message}`)})};l.onNotification("session/cancel",p),l.onRequest("session/cancel",async m=>{let h=wp.parse(m);return f(h.sessionId,"session/cancel"),p(m),null}),l.onRequest("hydra-acp/prompt/cancel",async m=>{let h=jI.parse(m);return f(h.sessionId,"hydra-acp/prompt/cancel"),cr(e.manager,h.sessionId).cancelQueuedPrompt(h.messageId)}),l.onRequest("hydra-acp/session/force_cancel",async m=>{let h=wp.parse(m);return f(h.sessionId,"hydra-acp/session/force_cancel"),cr(e.manager,h.sessionId).forceCancel()}),l.onRequest("hydra-acp/prompt/update",async m=>{let h=qI.parse(m);return f(h.sessionId,"hydra-acp/prompt/update"),cr(e.manager,h.sessionId).updateQueuedPrompt(h.messageId,h.prompt)}),l.onRequest("hydra-acp/prompt/amend",async m=>{let h=zI.parse(m);f(h.sessionId,"hydra-acp/prompt/amend");let g=u.attached.get(h.sessionId);if(!g)throw he(G.SessionNotFound,"not attached to session");return cr(e.manager,h.sessionId).amendPrompt(g.clientId,h)}),l.onRequest("_session/steering",async m=>{let h=KI.parse(m);f(h.sessionId,"_session/steering");let g=u.attached.get(h.sessionId);if(!g)throw he(G.SessionNotFound,"not attached to session");let w=e.manager.get(h.sessionId);if(!w){let b=await e.manager.loadFromDisk(h.sessionId);if(!b)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);w=await xa(e,b);let k=pi(l,w,u,void 0,g.clientId);await w.attach(k,"none")}return w.steer(g.clientId,h)}),l.onRequest("session/resume",async m=>{let h=m??{},g=typeof h.sessionId=="string"?h.sessionId:void 0;if(!g)throw he(G.InvalidParams,"session/resume requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,b=e.manager.get(w);if(!b){let x=await e.manager.loadFromDisk(w);if(!x)throw he(G.SessionNotFound,`session ${g} not found in memory or on disk`);b=await xa(e,x)}Mc(u,b,b.sessionId);let k=pi(l,b,u);await b.attach(k,"pending_only"),u.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:k.clientId,readonly:!1}),b.replayPendingPermissions(k);let S=Hh(b),I=Uh(b);return{sessionId:b.sessionId,...S?{modes:S}:{},...I?{models:I}:{},configOptions:b.buildConfigOptions(),_meta:Wh(e.manager,b,{clientId:k.clientId})}}),l.onRequest("session/load",async m=>{let h=m??{},g=typeof h.sessionId=="string"?h.sessionId:void 0;if(!g)throw he(G.InvalidParams,"session/load requires sessionId");let w=await e.manager.resolveCanonicalId(g)??g,b=e.manager.get(w);if(!b){let A=await e.manager.loadFromDisk(w);if(!A)throw he(G.SessionNotFound,`session ${g} not found in memory or on disk`);b=await xa(e,A)}Mc(u,b,b.sessionId);let k=pi(l,b,u),{entries:S}=await b.attach(k,"full");u.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:k.clientId,readonly:!1});for(let A of S){if(l.isClosed())break;await l.notify(A.method,Ls(Fs(A.params,A.recordedAt),A.seq)).catch(()=>{})}b.replayPendingPermissions(k);let I=Hh(b),x=Uh(b);return{sessionId:b.sessionId,...I?{modes:I}:{},...x?{models:x}:{},configOptions:b.buildConfigOptions(),_meta:Wh(e.manager,b,{clientId:k.clientId})}}),l.onRequest("session/set_model",async m=>{let h=m?.sessionId;typeof h=="string"&&f(h,"session/set_model");let g=vH(m,e.manager);if(g.kind==="error")throw n.log.warn(g.logMessage),he(g.code,g.message);if(g.kind==="no_op")return n.log.warn(g.logMessage),await l.notify("session/update",{sessionId:g.sessionId,update:{sessionUpdate:"_hydra_current_model_update",currentModel:g.currentModel}}).catch(()=>{}),null;n.log.info(g.logMessage);let{modelId:w}=g,b=await g.session.forwardModelChange(w,m);return g.session.applyAgentConfigOptionResponse(b,"model"),g.session.applyModelChange(w),b}),l.onRequest("session/set_mode",async m=>{let h=m,g=h?.sessionId;if(typeof g=="string"&&f(g,"session/set_mode"),!h||typeof h.sessionId!="string")throw he(G.InvalidParams,"session/set_mode requires string sessionId");if(typeof h.modeId!="string")throw he(G.InvalidParams,"session/set_mode requires string modeId");let w=cr(e.manager,h.sessionId),b=await w.forwardRequest("session/set_mode",m);return w.applyModeChange(h.modeId),b}),l.onRequest("session/set_config_option",async m=>{let h=m,g=S=>he(G.InvalidParams,S),w=h?.sessionId;if(typeof w=="string"&&f(w,"session/set_config_option"),!h||typeof h.sessionId!="string")throw g("session/set_config_option requires string sessionId");if(typeof h.configId!="string")throw g("session/set_config_option requires string configId");if(typeof h.value!="string")throw g("session/set_config_option requires string value");let b=cr(e.manager,h.sessionId),k=b.buildConfigOptions().find(S=>S.id===h.configId);if(!k)throw g(`unknown configId ${JSON.stringify(h.configId)} for this session`);if(!k.options.some(S=>S.value===h.value))throw g(`value ${JSON.stringify(h.value)} is not valid for configId ${JSON.stringify(h.configId)}`);switch(h.configId){case"model":{if(h.value!==b.currentModel){let S=await b.forwardModelChange(h.value);b.applyAgentConfigOptionResponse(S,"model")}b.applyModelChange(h.value);break}case"mode":{h.value!==b.currentMode&&await b.forwardRequest("session/set_mode",{sessionId:h.sessionId,modeId:h.value}),b.applyModeChange(h.value);break}case"agent":{h.value!==b.agentId&&await b.setAgent(h.value);break}default:{let S=await b.forwardRequest("session/set_config_option",{sessionId:h.sessionId,configId:h.configId,value:h.value});b.applyAgentConfigOptionResponse(S,h.configId)&&b.broadcastConfigOptions()}}return{configOptions:b.buildConfigOptions()}}),l.setDefaultHandler(async(m,h)=>{let g=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),w=h.startsWith("session/"),b=h.startsWith("hydra-acp/");if(!w&&!b||m===null||typeof m!="object"||g.has(h))throw he(G.MethodNotFound,`Method not found: ${h}`);let k=m.sessionId;if(typeof k!="string")throw he(G.MethodNotFound,`Method not found: ${h}`);return f(k,h),cr(e.manager,k).forwardRequest(h,m)})})}async function wH(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw he(G.InvalidParams,"authenticate requires a non-empty methodId string");let r=t.methodId,s=t._meta?.["hydra-acp"],o=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===r);if(!c){let p=d.map(m=>m.id);throw he(G.InvalidParams,`authenticate: methodId ${JSON.stringify(r)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).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=(k,S)=>{if(!Array.isArray(k))throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be a string[]; got ${k===null?"null":typeof k}`);for(let I of k)if(typeof I!="string")throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be string[]; got non-string entry ${JSON.stringify(I)}`);return k},m=await e.manager.planSpawnForAgent(a.agentId),h,g;if(u?.args!==void 0){let k=typeof u.command=="string"?u.command:void 0;h=k!==void 0&&iT.isAbsolute(k)?k:m.command,g=p(u.args,'_meta["terminal-auth"].args')}else{let k=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=k!==void 0?p(k.raw,k.label):[];h=m.command,g=[...m.args,...S]}let w={};for(let[k,S]of Object.entries(process.env))typeof S=="string"&&(w[k]=S);Object.assign(w,m.env);let b=oT.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${r}`),{kind:"terminal",command:h,args:g,env:w,cwd:b}}try{return await a.connection.request("authenticate",{methodId:r})}catch(p){throw di(p,a)}}async function bH(n,e){let r=(n??{})._meta?.["hydra-acp"],s=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,i=s!==void 0?e.manager.getAgentForSession(s):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function Bh(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(bp,t).catch(()=>{})}}function Hh(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(s=>{let o={id:s.id,name:s.name??s.id};return s.description!==void 0&&(o.description=s.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Uh(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(s=>{let o={modelId:s.modelId};return s.name!==void 0&&(o.name=s.name),s.description!==void 0&&(o.description=s.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}async function kH(n,e,t,r){return e?await r.isRetiredGeneration(n,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${n} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function vH(n,e){if(!n||typeof n!="object")return{kind:"error",code:G.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:G.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:G.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let r=e.get(t.sessionId);if(!r)return{kind:"error",code:G.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let s=r.availableModels(),o=hc(t.modelId,s);if(o.kind==="none")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:r,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=s.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return r.currentModel!==void 0&&r.currentModel.length>0?{kind:"no_op",session:r,sessionId:t.sessionId,currentModel:r.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(r.currentModel)} agentId=${r.agentId} known=[${i}]`}:{kind:"error",code:G.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${r.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${r.agentId} known=[${i}] (no current model to fall back to)`}}async function SH(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)throw he(G.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw he(G.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw he(G.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return cr(t.manager,s).addTransformer(o),{ok:!0}}async function xH(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/set requires string reason");return cr(t.manager,s).setAttentionFlag(e,o,r.payload),{ok:!0}}async function IH(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string reason");return cr(t.manager,s).clearAttentionFlag(e,o),{ok:!0}}function CH(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,workspace:n.workspace,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:ga(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,armedTasks:0,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels,armedTaskList:[]};return{[ut]:gp(e,t)}}function Wh(n,e,t={}){let r=n.liveListEntry(e),s={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(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return ql(e.agentMeta,gp(r,s))}function RH(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Ue},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:{...ql(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}}}),steering:{supported:!0}}}}function AH(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let r=e.transformers.resolveChain([t])[0];r&&n.addTransformer(r)}}function dT(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let r of t)r.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function pi(n,e,t,r,s){return{clientId:s??`cli_${Ob(8)}`,connection:n,clientInfo:r}}function Mc(n,e,t){let r=n.attached.get(t);r&&(e.detach(r.clientId),n.attached.delete(t))}var jh=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,r,s=new Promise((i,a)=>{t=i,r=a});s.catch(()=>{});let o={session:void 0,sessionReady:s,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),r(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:r}=this.reserve(e);r(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let r=this.byToken.get(e);r!==void 0&&r.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let r of t.disposers)try{await r()}catch{}}}size(){return this.byToken.size}};import{randomUUID as TH}from"crypto";import{McpServer as EH}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as PH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Mn}from"zod";function Fb(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 Zn(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var cT="Bearer ";function _c(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(cT))return;let t=e.slice(cT.length).trim();return t.length>0?t:void 0}function MH(n){let e=new EH({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:Mn.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let r=n.streamTail(t);return Zn(r)}),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:Mn.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let r=n.streamHead(t);return Zn(r)}),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:Mn.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:Mn.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Mn.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:r,wait_ms:s})=>{let o=await n.streamRead(t,r,s);return Zn(o)}),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:Mn.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Mn.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:r})=>{let s=await n.streamWaitFor(t,r),o=n.streamInfo();return Zn({outcome:s,writeCursor:o.writeCursor,closed:o.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:Mn.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Mn.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Mn.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Mn.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Mn.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Mn.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Mn.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Mn.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Mn.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 r={pattern:t.pattern};t.regex!==void 0&&(r.regex=t.regex),t.case_insensitive!==void 0&&(r.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(r.invert=t.invert),t.max_matches!==void 0&&(r.maxMatches=t.max_matches),t.max_bytes!==void 0&&(r.maxBytes=t.max_bytes),t.context_before!==void 0&&(r.contextBefore=t.context_before),t.context_after!==void 0&&(r.contextAfter=t.context_after),t.cursor!==void 0&&(r.cursor=t.cursor);let s=n.streamGrep(r);return Zn(s)}),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 Zn(t)}),e}var _H=1e4;function lT(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=MH(a),l=new PH({sessionIdGenerator:()=>TH()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=_c(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(h=>{f=setTimeout(()=>h(void 0),_H)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let u=await r(d,l);a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)})}Tp();import{randomUUID as $H}from"crypto";import{McpServer as OH}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as FH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as zs}from"zod";function LH(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var uT=2e3,fT=2e4;function NH(n,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return gc([n]);let r=[],s=Vl(t);s!==void 0?r.push(`Tool: ${s}`):typeof t.title=="string"&&t.title.length>0&&r.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&r.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&r.push(a.path);let i=Ap(t);return i!==void 0&&r.push(i),r.join(`
|
|
409
|
+
`)}function DH(n,e){if(n.length<=148)return n;let s=Math.floor(148/2),o=e-s;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function BH(n){let e=new OH({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. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. 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:zs.string().min(1).describe("Case-insensitive substring to search for."),limit:zs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:zs.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:r=10,include_tool_calls:s=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return Zn({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 i=[],a=t.toLowerCase();for await(let{entryId:c,entry:l}of o.iterRecallNewestFirst()){let u=Fb(l);if(!u)continue;let{kind:f,update:p}=u;if((f==="tool_call"||f==="tool_call_update")&&!s)continue;let m=NH(l,f,p),h=m.toLowerCase().indexOf(a);if(h<0)continue;let g=LH(f),w=DH(m,h),b=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(i.push({entryId:c,speaker:g,snippet:w,timestamp:b}),i.length>=r)break}i.sort((c,l)=>c.entryId-l.entryId);let d=i.length>=r;return Zn({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:zs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:zs.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:r})=>{let s=await n();if(!s.summarizedThroughEntry||s.summarizedThroughEntry===0)return Zn({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(r<t)throw new Error(`range: to_entry (${r}) must be >= from_entry (${t})`);let o=r-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await s.getRecallTotalCount();if(i===0)return Zn({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(r,i-1),c=a>t||d<r;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await s.sliceRecallHistory(a,d),u=gc(l,{toolOutput:{maxPerCall:uT,maxTotal:fT}});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, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:zs.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:zs.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:zs.string().optional(),limit:zs.number().int().min(1).max(100).optional(),include_output:zs.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:r,file_path:s,limit:o=20,include_output:i=!0})=>{let a=await n();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return Zn({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 d=typeof t=="string"&&t.length>0,c=typeof r=="string"&&r.length>0,l=typeof s=="string"&&s.length>0;if(!d&&!c&&!l)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let u=new Map,f=Math.max(o*4,200);for await(let{entryId:b,entry:k}of a.iterRecallNewestFirst()){let S=Fb(k);if(!S)continue;let{kind:I,update:x}=S;if(I!=="tool_call"&&I!=="tool_call_update")continue;let A=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:`__noid_${b}`,_=u.get(A);if(_||(_={entryId:b,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},u.set(A,_)),b<_.entryId&&(_.entryId=b),!_.nameAuthoritative){let $=Vl(x);$!==void 0?(_.toolName=$,_.nameAuthoritative=!0):typeof x.name=="string"&&x.name.length>0?(_.toolName=x.name,_.nameAuthoritative=!0):I==="tool_call"&&typeof x.title=="string"&&x.title.length>0&&(_.toolName=x.title,_.nameAuthoritative=!0)}if(_.kind===void 0&&typeof x.kind=="string"&&x.kind.length>0&&(_.kind=x.kind),_.output===void 0){let $=Ap(x);$!==void 0&&(_.output=$)}let P=x.rawInput;if(P&&typeof P=="object"&&!Array.isArray(P)&&Object.keys(P).length>0)for(let[$,F]of Object.entries(P))_.rawInput[$]===void 0&&(_.rawInput[$]=F);if(Array.isArray(x.locations))for(let $ of x.locations){let F=$?.path;typeof F=="string"&&F.length>0&&!_.locations.includes(F)&&_.locations.push(F)}if(typeof x.status=="string"&&_.status==="in_progress"&&(_.status=x.status),k.recordedAt!==void 0&&_.timestamp===void 0&&(_.timestamp=String(k.recordedAt)),u.size>=f)break}let p=[...u.keys()].sort((b,k)=>u.get(b).entryId-u.get(k).entryId),m=[],h=fT,g=!1;for(let b of p){let k=u.get(b);if(k.toolName=Cw({name:k.toolName,rawInput:k.rawInput,...k.kind!==void 0?{kind:k.kind}:{}}),d&&!k.toolName.toLowerCase().includes(t.toLowerCase())||c&&(k.kind??"").toLowerCase()!==r.toLowerCase())continue;if(l){let x=s.toLowerCase(),A=["file_path","filePath","path"],_=!1;for(let P of A){let $=k.rawInput[P];if(typeof $=="string"&&$.toLowerCase().includes(x)){_=!0;break}}if(!_){for(let P of k.locations)if(P.toLowerCase().includes(x)){_=!0;break}}if(!_)continue}let S={};for(let[x,A]of Object.entries(k.rawInput))typeof A=="string"?S[x]=A.length>500?A.slice(0,497)+"\u2026":A:(typeof A=="number"||typeof A=="boolean")&&(S[x]=A);k.locations.length>0&&S.locations===void 0&&(S.locations=k.locations);let I={entryId:k.entryId,tool:k.toolName,args:S,status:k.status,timestamp:k.timestamp};if(k.kind!==void 0&&(I.kind=k.kind),i&&k.output!==void 0){let x=k.output,A=Math.min(uT,h);if(A<=0)g=!0;else{let _=x.length<=A?x:x.slice(0,A-1)+"\u2026";I.output=_,I.outputBytes=x.length,I.outputTruncated=_.length<x.length,h-=_.length}}if(m.push(I),m.length>=o)break}let w=m.length>=o;return Zn({calls:m,truncated:w,...g?{outputBudgetExhausted:g}:{}})}),e}var HH=1e4;function pT(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=BH(a),l=new FH({sessionIdGenerator:()=>$H()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=_c(i);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 r(d,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(h=>{f=setTimeout(()=>h(void 0),HH)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)})}var qh=class{byName=new Map;changeHandlers=[];register(e,t,r,s){this.byName.set(e,{connection:t,instructions:r,tools:[...s]}),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 r of this.changeHandlers)try{r(e,t)}catch{}}};import{StreamableHTTPServerTransport as JH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as VH}from"crypto";import{Server as UH}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as WH,ListToolsRequestSchema as jH}from"@modelcontextprotocol/sdk/types.js";function hT(n,e,t,r){let s=typeof t=="function"?async()=>t():async()=>t,o=new UH({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(jH,async()=>{let a=r?.peekSessionId?.();if(a!==void 0&&r?.fetchSessionTools!==void 0)try{let d=await r.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(WH,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,u=zH(l,d.sendNotification);try{let f=await s(),p=await KH(e.connection,n,c,a.params.arguments??{},f);return GH(p,c)}catch(f){return Lb(f instanceof Error?f.message:String(f))}finally{u()}}),o}var qH=15e3;function zH(n,e,t=qH){if(n===void 0)return()=>{};let r=0,s=setInterval(()=>{r+=1,e({method:"notifications/progress",params:{progressToken:n,progress:r}}).catch(()=>{})},t);return s.unref?.(),()=>clearInterval(s)}async function KH(n,e,t,r,s){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:r,sessionId:s})}function GH(n,e){if(n===null||typeof n!="object")return Lb(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Lb(`extension ${e} omitted content array`)}function Lb(n){return{content:[{type:"text",text:n}],isError:!0}}var YH=1e4;function mT(n,e,t){let r=new Map;async function s(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),s(f))}}async function i(l,u){for(let[f,p]of r){if(e.lookup(f)?.session?.sessionId!==l)continue;let h=p.get(u);if(h!==void 0)try{await h.server.sendToolListChanged()}catch{}}}t.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let S=r.get(l);if(S!==void 0){r.delete(l);for(let I of S.values())await s(I)}}));let p=f.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let b=hT(u,m,async()=>{let S=e.lookup(l);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let I,x=new Promise(_=>{I=setTimeout(()=>_(void 0),YH)}),A=await Promise.race([S.sessionReady.catch(()=>{}),x]);if(I!==void 0&&clearTimeout(I),A===void 0)throw new Error("session not ready");return A.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async S=>{let I=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:S});if(!I||typeof I!="object")return;let x=I.tools;if(!Array.isArray(x))return;let A=[];for(let _ of x){if(!_||typeof _!="object")continue;let P=_;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),A.push($)}return A}}),k=new JH({sessionIdGenerator:()=>VH()});return await b.connect(k),f.set(u,{server:b,transport:k}),k}async function d(l,u){let f=_c(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 m=l.params.name,h=await a(f,m);if(h===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await h.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:i}}async function vT(n,e){rU(n),Ul(n.daemon.scrubEnv);let t=n,r=n.daemon.tls?await Ks.readFile(mt(n.daemon.tls.key)):void 0,s=n.daemon.tls?await Ks.readFile(mt(n.daemon.tls.cert)):void 0;await Ks.mkdir(D.home(),{recursive:!0});let{stream:o,fileStream:i}=await tU(n.daemon.logLevel),a=QH({logger:{level:n.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(XH,{options:{handleProtocols:iI}}),ow(ce=>{a.log.info(ce)}),dw(ce=>{a.log.info(ce)});let d=await gh.load(),c=await Lh.load();_l(),Ry(c);let l=new Dh(c);l.start();let u=new Ph(c);u.start();let f=new vh,p=new kh,m=new yh(e),h=new bh([m,new wh(d),p]),g=ZR({validator:h});a.addHook("onRequest",async(ce,Je)=>{ce.routeOptions.config?.skipAuth||ce.url==="/acp"||ce.url?.startsWith("/acp?")||(await g(ce,Je),!Je.sent&&ce.authIdentity?.startsWith("script:")&&!tA(ce.method,ce.routeOptions.url)&&Je.code(403).send({error:"script tokens may only access read-only session data"}))});let w=setInterval(()=>{d.sweepExpired()},300*1e3);w.unref();let b=setInterval(()=>{f.sweepExpired()},300*1e3);b.unref();let k=new hp(n,{onFetched:()=>{HR(k,A)},onStaleFallback:(ce,Je)=>{let xe=Math.round(Je/36e5),an=xe>=48?`${Math.round(xe/24)}d`:`${xe}h`;a.log.warn(`registry fetch failed (${ce.message}); serving stale cache last synced ${an} ago; agent versions may be outdated ('hydra registry refresh' to retry)`)}});bb(ce=>a.log.info(ce));let S={info:ce=>a.log.info(ce),warn:ce=>a.log.warn(ce)},I=ce=>ni.spawn({...ce,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:S});fI(n.compressToolContent);let x=new hh,A=new sh(k,I,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:n.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,sessionDefaults:n.sessionDefaults,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:S,npmRegistry:n.npmRegistry,extensionCommands:x,defaultCwd:n.defaultCwd,disableWorkspaceSnapshots:n.disableWorkspaceSnapshots}),_=new Nh(c,void 0,{resolvesLocally:async ce=>await A.resolveCanonicalId(ce)!==void 0,cache:u}),P=new fh(fy(n),void 0,{tokenRegistry:p}),$=new ph(py(n),void 0,{tokenRegistry:p}),F=[];$A(a,Ue,ci(n),()=>F);let J=new jh,Y=new qh,W,Z=()=>{if(W!==void 0)return W;let ce=a.server.address();return W=`http://127.0.0.1:${ce&&typeof ce=="object"?ce.port:n.daemon.port}`,W},ne={agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction};MA(a,A,ne,{extensionMcp:Y,mcpTokenRegistry:J,getDaemonOrigin:Z},c,u),RA(a,{store:c,localMiss:{resolvesLocally:async ce=>await A.resolveCanonicalId(ce)!==void 0,cache:u}}),_A(a,k,A,{npmRegistry:n.npmRegistry}),OA(a,P),FA(a,$),LA(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,sessionDefaults:{...t.sessionDefaults},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]})),qA(a,{store:d,rateLimiter:f,staticTokenValidator:m}),VA(a,{store:c,health:l}),ZA(a,{processRegistry:p}),lT(a,J),pT(a,J);let ve=mT(a,J,Y);aT(a,{validator:h,manager:A,defaultAgent:n.defaultAgent,processRegistry:p,onExtensionVersion:(ce,Je)=>P.reportVersion(ce,Je),onTransformerVersion:(ce,Je)=>$.reportVersion(ce,Je),transformers:$,extensionCommands:x,mcpTokenRegistry:J,extensionMcp:Y,extensionMcpControls:ve,getDaemonOrigin:Z,registry:k,foreignSessions:_});let Ne=!!n.daemon.tls;await a.listen({host:Ne?"127.0.0.1":n.daemon.host,port:Ne?0:n.daemon.port});let Re=a.server.address(),Ge=Re&&typeof Re=="object"?Re.port:n.daemon.port,Ae,de=n.daemon.host,De=Ge;if(Ne&&r&&s){Ae=nU({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:Ge,tlsOptions:{key:r,cert:s},logger:a.log});let ce=Ae.address();ce&&typeof ce=="object"&&(De=ce.port)}await Ks.mkdir(D.home(),{recursive:!0}),await dx({pid:process.pid,host:de,port:De,loopbackPort:Ge,startedAt:new Date().toISOString()});let it={daemonUrl:`http://127.0.0.1:${Ge}`,daemonHost:"127.0.0.1",daemonPort:Ge,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${Ge}/acp`,hydraHome:D.home()};P.setContext(it),$.setContext(it),await P.start(),await $.start();try{await A.reconcilePermissionFlags()}catch(ce){a.log.warn(`permission flag reconcile failed: ${ce.message}`)}try{await A.seedSessionIndex()}catch(ce){a.log.warn(`session index seed failed: ${ce.message}`)}A.resurrectPendingQueues().catch(ce=>{a.log.warn(`queue replay scan failed: ${ce.message}`)}),A.resumePendingCompactions().catch(ce=>{a.log.warn(`compaction resume scan failed: ${ce.message}`)}),A.resumePendingAgentSwaps().catch(ce=>{a.log.warn(`agent-swap resume scan failed: ${ce.message}`)});let Rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Me=Rt>0?UR({registry:k,manager:A,intervalMs:Rt,logger:S}):void 0,Kt=n.daemon.sessionGcIntervalMinutes*60*1e3,Ve=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ys=Kt>0?WR({manager:A,intervalMs:Kt,maxAgeMs:Ve,logger:S}):void 0,Ti=KR({bootConfig:n,apply:ce=>{t=ce,k.setConfig(ce),A.setLiveConfig({sessionDefaults:ce.sessionDefaults}),ne.agentId=ce.defaultAgent,ne.cwd=ce.defaultCwd,Ul(ce.daemon.scrubEnv)},onDrift:ce=>{F=ce},logger:S});return{app:a,manager:A,registry:k,extensions:P,transformers:$,mcpTokenRegistry:J,extensionMcp:Y,processRegistry:p,shutdown:async()=>{l.stop(),u.stop(),Ti(),ys&&ys(),Me&&Me(),clearInterval(w),clearInterval(b);let ce=async(Je,xe)=>{try{await xe()}catch(an){a.log.warn(`shutdown step ${Je} failed: ${an instanceof Error?an.message:String(an)}`)}};await ce("sessionTokenStore.flush",()=>d.flush()),await ce("extensions.stop",()=>P.stop()),await ce("transformers.stop",()=>$.stop()),await ce("manager.closeAll",()=>A.closeAll()),await ce("manager.flushSynopsis",()=>A.flushSynopsis(3e4)),await ce("manager.shutdownSynopsis",()=>A.shutdownSynopsis()),await ce("manager.flushMetaWrites",()=>A.flushMetaWrites()),await ce("manager.flushHistoryWrites",()=>A.flushHistoryWrites()),ow(null),dw(null),bb(null),Ae&&await ce("tlsTerminator.close",()=>new Promise(Je=>Ae.close(()=>Je()))),await ce("app.close",()=>a.close());try{wT.unlinkSync(D.pidFile())}catch{}await ce("fileStream.flushSync",()=>i.flushSync())}}}var yT=20;async function eU(n,e){let t=$c.dirname(n),r=$c.basename(n,".log"),s=new RegExp(`^${r}\\.(\\d+)\\.log$`),o;try{o=await Ks.readdir(t)}catch{return}let i=[];for(let d of o){let c=d.match(s);c&&i.push({name:d,n:Number(c[1])})}if(i.length<=e)return;i.sort((d,c)=>d.n-c.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>Ks.unlink($c.join(t,d.name))))}async function tU(n){await eU(D.logFile(),yT);let e=await ZH({file:D.logFile(),size:"10m",mkdir:!0,symlink:dh,limit:{count:yT,removeOtherLogFiles:!0}}),t=gT.destination(2);return{stream:gT.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function nU(n){let e=kT.createServer(n.tlsOptions,t=>{let r=bT.connect({host:n.upstreamHost,port:n.upstreamPort}),s=!1,o=i=>{if(!s){s=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{r.destroy()}catch{}}};t.on("error",o),r.on("error",o),t.on("close",()=>o()),r.on("close",()=>o()),t.pipe(r),r.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 rU(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.`)}Ra();dr();Rc();Ru();async function AT(n={}){let e=await yo(),t=await Il();if(await zh(e)){let s=await Lc();process.stdout.write(`Daemon already running${s?` (pid ${s.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
|
|
410
410
|
`);return}if(Ed(n,"foreground")){process.title="hydra-acp-daemon";let s=await vT(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
|
|
411
411
|
`);let o=1e4,i=!1,a=async()=>{i&&(process.stderr.write(`Second signal received; exiting immediately.
|
|
412
412
|
`),process.exit(1)),i=!0,process.stdout.write(`Shutting down...
|
|
@@ -430,12 +430,12 @@ ${A}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),th
|
|
|
430
430
|
`);return}process.stdout.write(`CLI version: ${Ue}
|
|
431
431
|
`),process.stdout.write(`Daemon version: ${t.version}
|
|
432
432
|
`);let a=Fl(process.stdout),d=c=>aa("cli-warn",c,a);s||process.stdout.write(d("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),s&&!o&&process.stdout.write(d("Daemon is bound differently than config.json describes (host/port/TLS) \u2014 run `hydra-acp daemon restart` to apply.\n")),i.length>0&&process.stdout.write(d(`These settings changed since the daemon started and need a restart to apply: ${i.join(", ")}.
|
|
433
|
-
`))}async function Lc(){return Es()}rt();
|
|
433
|
+
`))}async function Lc(){return Es()}rt();go();vr();wo();Ts();ir();Tu();ma();Sc();import*as Ar from"fs/promises";import*as qT from"os";import*as Tr from"path";Nc();rt();import*as Dc from"path";function UT(n){let e=n.trim();return Dc.resolve(mt(e.length===0?".":e))}function WT(n,e){let t=[n.cwd,n.workspace?.sourceCwd],r=e.endsWith(Dc.sep)?e:e+Dc.sep;for(let s of t){if(typeof s!="string"||s.length===0)continue;let o=Dc.resolve(s);if(o===e||o.startsWith(r))return!0}return!1}function em(n,e){if(e==="all")return!0;if(e==="local")return!n.remote&&(!n.importedFromMachine||!!n.upstreamSessionId);let t=!!n.importedFromMachine&&!n.upstreamSessionId;return n.remote===e&&!t||n.importedFromMachine===e&&!n.upstreamSessionId}async function zT(n={}){let e=await He(),t=n.includeNonInteractive||n.all?"?includeNonInteractive=true":"",s=(await Pe(`/v1/sessions${t}`,{expectStatus:200})).body,o=s.sessions,i=n.host??"local",a=o.filter(w=>em(w,i)),d=n.dir===void 0?a:a.filter(w=>WT(w,n.dir));if(n.json){process.stdout.write(JSON.stringify(d,null,2)+`
|
|
434
434
|
`);return}if(d.length===0){if(n.dir!==void 0){let w=a.length;process.stdout.write(`No sessions in ${n.dir}.`+(w>0?` ${w} session${w===1?"":"s"} elsewhere \u2014 drop --dir to see them.`:"")+`
|
|
435
435
|
`);return}if(i==="local"&&s.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
|
|
436
436
|
`);return}if(i!=="local"&&i!=="all"){process.stdout.write(`No sessions from ${i}.
|
|
437
437
|
`);return}process.stdout.write(`No active sessions.
|
|
438
|
-
`);return}let c=d.slice().sort((w,b)=>{let k=(b.status==="warm"?1:0)-(w.status==="warm"?1:0);return k!==0?k:String(b.updatedAt||"").localeCompare(String(w.updatedAt||""))}),l=c,u=0;if(!n.all){let w=c.filter(I=>I.status!=="cold").length,b=e.sessionListColdLimit,k=c.slice(w,w+b),S=c.length-w-k.length;l=[...c.slice(0,w),...k],u=S}let f=Date.now(),p=l.map(w=>ds(w,f)),m={columns:n.columns??e.tui.sessionColumns??mi,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=
|
|
438
|
+
`);return}let c=d.slice().sort((w,b)=>{let k=(b.status==="warm"?1:0)-(w.status==="warm"?1:0);return k!==0?k:String(b.updatedAt||"").localeCompare(String(w.updatedAt||""))}),l=c,u=0;if(!n.all){let w=c.filter(I=>I.status!=="cold").length,b=e.sessionListColdLimit,k=c.slice(w,w+b),S=c.length-w-k.length;l=[...c.slice(0,w),...k],u=S}let f=Date.now(),p=l.map(w=>ds(w,f)),m={columns:n.columns??e.tui.sessionColumns??mi,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Vs(p,m),g=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(Co,h,g,m)+`
|
|
439
439
|
`);for(let w of p)process.stdout.write(ur(w,h,g,m)+`
|
|
440
440
|
`);u>0&&process.stdout.write(`
|
|
441
441
|
... ${u} more cold session${u===1?"":"s"} hidden. Use --all to show.
|
|
@@ -471,7 +471,7 @@ ${A}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),th
|
|
|
471
471
|
`),process.exit(1));let i=o.body;process.stdout.write(i.replaced?`Replaced ${i.sessionId} (from ${i.importedFromSessionId})
|
|
472
472
|
`:`Imported as ${i.sessionId} (from ${i.importedFromSessionId})
|
|
473
473
|
`)}function TU(n){return{sessionId:n.session.sessionId,cwd:n.session.cwd,agentId:n.session.agentId,currentUsage:ga(n.session.currentUsage),title:n.session.title,importedFromMachine:n.exportedFrom.machine,attachedClients:0,updatedAt:n.session.updatedAt,status:"cold",compactionState:n.session.compactionState}}function EU(n,e){let t;try{t=as(n)}catch(c){process.stderr.write(`Not a valid bundle: ${c.message}
|
|
474
|
-
`),process.exit(1)}let r=TU(t),s=ds(r),o={columns:Zh,cwdMaxWidth:e},i=
|
|
474
|
+
`),process.exit(1)}let r=TU(t),s=ds(r),o={columns:Zh,cwdMaxWidth:e},i=Vs([s],o),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(Co,i,a,o)+`
|
|
475
475
|
`),process.stdout.write(ur(s,i,a,o)+`
|
|
476
476
|
`);let d=t.session.upstreamSessionId??"-";process.stdout.write(`
|
|
477
477
|
lineage: ${t.session.lineageId}
|
|
@@ -480,7 +480,7 @@ origin session: ${t.session.sessionId}
|
|
|
480
480
|
origin upstream: ${d}
|
|
481
481
|
history entries: ${t.history.length}`+(t.promptHistory?`, prompt history: ${t.promptHistory.length}
|
|
482
482
|
`:`
|
|
483
|
-
`))}async function PU(){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 MU(n,e){let t=n.headers.get("content-disposition");if(t){let s=t.match(/filename="([^"]+)"/);if(s)return s[1]}let r=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${r}.hydra`}async function ZT(n,e={}){let t=await He(),r;if(n!==void 0&&n.length>0)r=n;else{let c=await rn(t),l=e.cwd?Tr.resolve(e.cwd):process.cwd(),u=await
|
|
483
|
+
`))}async function PU(){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 MU(n,e){let t=n.headers.get("content-disposition");if(t){let s=t.match(/filename="([^"]+)"/);if(s)return s[1]}let r=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${r}.hydra`}async function ZT(n,e={}){let t=await He(),r;if(n!==void 0&&n.length>0)r=n;else{let c=await rn(t),l=e.cwd?Tr.resolve(e.cwd):process.cwd(),u=await Gs(c,{cwd:l,all:!0}),f=Yh(u,l);f||(process.stderr.write(`No sessions found for ${l}.
|
|
484
484
|
`),process.exit(1)),r=f.sessionId}let{host:s,port:o,isFallback:i}=_U(e.host,t),a=st(r),d=ox({host:s,port:o,sessionId:a});process.stdout.write(d+`
|
|
485
485
|
`),i&&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.
|
|
486
486
|
`)}function _U(n,e){if(n!==void 0&&n.length>0){let{host:t,port:r}=jT(n,An);return{host:t,port:r,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:r}=jT(e.daemon.publicHost,An);return{host:t,port:r,isFallback:!1}}return $U(e.daemon.host)?{host:OU(),port:e.daemon.port,isFallback:!1}:Vt(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 $U(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function OU(){let n=qT.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function jT(n,e){if(n.startsWith("[")){let r=n.indexOf("]");if(r>0){let s=n.slice(1,r),o=n.slice(r+1);if(o.startsWith(":")){let i=Number(o.slice(1));return{host:s,port:Number.isInteger(i)&&i>0?i:e}}return{host:s,port:e}}}let t=n.lastIndexOf(":");if(t>0&&n.indexOf(":")===t){let r=n.slice(0,t),s=Number(n.slice(t+1));if(Number.isInteger(s)&&s>0)return{host:r,port:s}}return{host:n,port:e}}ke();es();import*as fr from"fs/promises";import*as Er from"path";ke();Wd();vr();Nc();function FU(){return Er.join(D.home(),"workspaces")}async function LU(n,e){let t=await fr.stat(D.historyFile(n)).catch(()=>{});return t!==void 0?new Date(t.mtimeMs).toISOString():e}async function Bc(){let n=Er.join(D.home(),"sessions"),e=await fr.readdir(n).catch(()=>[]),t=[];for(let r of e){let s=await jt(Er.join(n,r,"meta.json"));if(s?.workspace?.path!==void 0&&typeof s.sessionId=="string"){let o=await LU(s.sessionId,s.updatedAt);t.push({sessionId:s.sessionId,...o!==void 0?{updatedAt:o}:{},workspace:s.workspace})}}return t}async function NU(){let n=FU(),e=await fr.readdir(n).catch(()=>[]),t=[];for(let r of e){let s=await fr.readdir(Er.join(n,r)).catch(()=>[]);for(let o of s){if(o.endsWith(".manifest.json"))continue;let i=Er.join(n,r,o);(await fr.stat(i).catch(()=>{}))?.isDirectory()&&t.push(i)}}return t}function Pu(n){return{path:n.path,sourceCwd:n.sourceCwd,label:n.label,provider:n.provider,...n.snapshot!==void 0?{snapshot:n.snapshot}:{},...n.line!==void 0?{line:n.line}:{},...n.vcs!==void 0?{vcs:n.vcs}:{}}}function cs(n){return{path:n.path,sourceCwd:n.sourceCwd,label:n.label,provider:n.provider,...n.branch!==void 0?{line:n.branch,vcs:{branch:n.branch}}:{}}}function e0(n){return{sessionId:n.sessionId,...n.updatedAt!==void 0?{updatedAt:n.updatedAt}:{}}}async function nm(){let n=await Bc(),e=new Map;for(let s of n){let o=e.get(s.workspace.path);o===void 0?e.set(s.workspace.path,[s]):o.push(s)}let t=new Set(await NU()),r=[];for(let s of t){let o=e.get(s),i=o?.[0];if(o!==void 0&&i!==void 0){r.push({path:s,sourceCwd:i.workspace.sourceCwd,label:i.workspace.label,provider:i.workspace.provider,state:"active",sessionId:i.sessionId,sessions:o.map(e0),...i.workspace.line!==void 0?{branch:i.workspace.line}:{}});continue}let a=await tm(s);r.push({path:s,sourceCwd:a?.sourceCwd??"(unknown)",label:a?.label??Er.basename(s),provider:a?.provider??"(unknown)",state:"unowned",...a?.line!==void 0?{branch:a.line}:{}})}for(let[s,o]of e){if(t.has(s))continue;let i=o[0];r.push({path:s,sourceCwd:i.workspace.sourceCwd,label:i.workspace.label,provider:i.workspace.provider,state:"inactive",sessionId:i.sessionId,sessions:o.map(e0),...i.workspace.line!==void 0?{branch:i.workspace.line}:{}})}for(let s of r){if(s.state==="inactive"||s.provider==="(unknown)")continue;let o=je(s.provider);if(o===void 0)continue;let i=e.get(s.path)?.[0],a=i!==void 0?Pu(i.workspace):await tm(s.path);if(a===void 0)continue;let d=await o.status(a).catch(()=>{});d!==void 0&&(s.clean=d.clean,s.changedCount=d.changedPaths.length)}return r.sort((s,o)=>s.path.localeCompare(o.path)),r}async function tm(n){for(let e of aR()){let t=await je(e)?.attributeOrphan(n).catch(()=>{});if(t!==void 0)return t}}async function qb(n){let e=(await nm()).filter(s=>s.state==="active");if(n!==void 0){let s=n.replace(/^hydra_session_/,""),o=e.filter(i=>i.sessionId?.replace(/^hydra_session_/,"")===s||i.label===s);if(o.length===0)throw new Error(`no bound workspace matches "${n}"`);return o[0]}let t=Er.resolve(process.cwd()),r=e.filter(s=>s.sourceCwd===t);if(r.length===1)return r[0];throw r.length===0?new Error(`no workspace is derived from ${V(t)}; name a session id explicitly`):new Error(`${r.length} workspaces are derived from ${V(t)}; name one explicitly:
|
|
@@ -529,7 +529,7 @@ ${r} removed, ${s} kept.
|
|
|
529
529
|
`),process.exit(2));let r=await He(),s=await Pe("/v1/sessions?includeNonInteractive=true",{expectStatus:200}),o=new Map;for(let g of s.body.sessions)o.set(g.sessionId,g);let a=(await Pe("/v1/sessions/search",{method:"POST",body:{q:`edit:"${t}"`},expectStatus:200})).body,d=a.results;e.host!==void 0&&e.host!=="all"&&(d=d.filter(g=>em(o.get(g.sessionId)??{},e.host))),d.length>0&&!d.some(g=>g.snippets.some(w=>w.kind==="edit"))&&(process.stderr.write("The daemon does not support the `edit:` search scope, so these results would be file mentions (reads, greps) rather than changes.\nRestart the daemon to pick up the current build: hydra daemon restart\n"),process.exit(1)),d=d.slice().sort((g,w)=>{let b=(w.status==="warm"?1:0)-(g.status==="warm"?1:0);return b!==0?b:String(w.updatedAt||"").localeCompare(String(g.updatedAt||""))});let l=e.files===!0||e.json===!0?await $W(d.map(g=>g.sessionId),t,o):new Map;if(e.json){process.stdout.write(JSON.stringify({query:t,truncated:a.truncated,results:d.map(g=>({sessionId:g.sessionId,...g.title!==void 0?{title:g.title}:{},cwd:g.cwd,status:g.status,updatedAt:g.updatedAt,fileCount:g.totalMatches,files:l.get(g.sessionId)??[]}))},null,2)+`
|
|
530
530
|
`);return}if(d.length===0){process.stdout.write(`No sessions changed files under ${V(t)}.
|
|
531
531
|
Note: deletes and shell-driven edits (sed -i, git checkout, mv) carry no edit payload, so they are invisible to this search.
|
|
532
|
-
`);return}let u=Date.now(),f=[];for(let g of d){let w=o.get(g.sessionId);f.push(ds(w??OW(g),u))}let p={columns:e.columns??r.tui.sessionColumns??mi,cwdMaxWidth:r.tui.cwdColumnMaxWidth},m=
|
|
532
|
+
`);return}let u=Date.now(),f=[];for(let g of d){let w=o.get(g.sessionId);f.push(ds(w??OW(g),u))}let p={columns:e.columns??r.tui.sessionColumns??mi,cwdMaxWidth:r.tui.cwdColumnMaxWidth},m=Vs(f,p),h=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(Co,m,h,p)+`
|
|
533
533
|
`),d.forEach((g,w)=>{process.stdout.write(ur(f[w],m,h,p)+`
|
|
534
534
|
`);let b=o.get(g.sessionId),k=b?Ec(b):void 0;for(let S of MW(g,l.get(g.sessionId),t,k))process.stdout.write(S+`
|
|
535
535
|
`)}),a.truncated&&process.stdout.write(`
|
|
@@ -558,7 +558,7 @@ Note: deletes and shell-driven edits (sed -i, git checkout, mv) carry no edit pa
|
|
|
558
558
|
`),m+=1;continue}let w=g.body,b=w.pid!=null?` pid=${w.pid}`:"";process.stdout.write(`${h.name}: ${w.status}${b}
|
|
559
559
|
`)}catch(g){process.stdout.write(`${h.name}: ERROR ${g.message}
|
|
560
560
|
`),m+=1}m>0&&process.exit(1)}async function d(c){let{name:l,rest:u}=Jh(c);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
|
|
561
|
-
`),process.exit(2);return}let f=e.logFile(l);await Fc(f,u,`No log file (${e.singular} never ran?)`)}return{list:r,add:s,remove:o,start:c=>i(c,"start"),stop:c=>i(c,"stop"),restart:c=>i(c,"restart"),logs:d}}function O0(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Ea=lm("extension"),F0=Ea.list,L0=Ea.add,N0=Ea.remove,D0=Ea.start,B0=Ea.stop,H0=Ea.restart,U0=Ea.logs;var Pa=lm("transformer"),W0=Pa.list,j0=Pa.add,q0=Pa.remove,z0=Pa.start,K0=Pa.stop,G0=Pa.restart,J0=Pa.logs;gm();qd();Sa();
|
|
561
|
+
`),process.exit(2);return}let f=e.logFile(l);await Fc(f,u,`No log file (${e.singular} never ran?)`)}return{list:r,add:s,remove:o,start:c=>i(c,"start"),stop:c=>i(c,"stop"),restart:c=>i(c,"restart"),logs:d}}function O0(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Ea=lm("extension"),F0=Ea.list,L0=Ea.add,N0=Ea.remove,D0=Ea.start,B0=Ea.stop,H0=Ea.restart,U0=Ea.logs;var Pa=lm("transformer"),W0=Pa.list,j0=Pa.add,q0=Pa.remove,z0=Pa.start,K0=Pa.stop,G0=Pa.restart,J0=Pa.logs;gm();qd();Sa();ko();rt();wo();Ra();fn();dr();jl();Sk();import tj from"os";import{spawn as nj}from"child_process";async function rj({conn:n,agentId:e,authMethods:t,method:r,spawn:s}){let o;try{let d=await n.request("hydra-acp/agents/auth_methods",{agentId:e});o=Array.isArray(d?.authMethods)?d.authMethods:[]}catch{o=void 0}let i=d=>new Promise(c=>{let l=s(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 sj(d,r),u=await vk(l,{authenticate:f=>n.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:c}}}),runTerminalAuth:i});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
|
|
562
562
|
`),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
|
|
563
563
|
`),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
|
|
564
564
|
`),{exitCode:1})};if(o!==void 0&&o.length>0)return a(o,e);try{return await n.request("session/new",{cwd:tj.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
|
|
@@ -569,7 +569,7 @@ ${r.join(`
|
|
|
569
569
|
`);let{createInterface:s}=await import("readline/promises"),o=s({input:process.stdin,output:process.stdout}),i=await o.question("method> ");o.close();let a=parseInt(i.trim(),10);return(Number.isNaN(a)||a<1||a>n.length)&&(process.stderr.write(`invalid selection "${i}" \u2014 enter a number between 1 and ${n.length}
|
|
570
570
|
`),process.exit(2)),n[a-1]}let t=n.map(r=>r.id).join(", ");process.stderr.write(`multiple auth methods available; pass --method <id> (one of: ${t})
|
|
571
571
|
`),process.exit(2)}async function wE(n,e){(n===void 0||n.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
|
|
572
|
-
`),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(gm(),Z0)),r=await t(n,"hydra agent auth"),s=await He(),o=await rn(s);await hi(s,o);let i=["acp.v1",`hydra-acp-token.${o.token}`],a=await
|
|
572
|
+
`),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(gm(),Z0)),r=await t(n,"hydra agent auth"),s=await He(),o=await rn(s);await hi(s,o);let i=["acp.v1",`hydra-acp-token.${o.token}`],a=await bo(o.wsUrl,i),d=Rr(a),c=new pn(d);try{await c.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:Ue}})}catch{}let l;try{l=await rj({conn:c,agentId:r,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:nj})}finally{a.close()}process.exit(l.exitCode)}Ru();ep();vr();async function bE(n){let e=Ed(n,"force");if(await Oh()&&!e){let s=await Vo("Current password: ");await Fh(s)||(process.stderr.write(`Wrong password.
|
|
573
573
|
`),process.exit(1))}let t=await Vo("New password: ");t.length===0&&(process.stderr.write(`Password must not be empty.
|
|
574
574
|
`),process.exit(2));let r=await Vo("Confirm new password: ");t!==r&&(process.stderr.write(`Passwords did not match.
|
|
575
575
|
`),process.exit(1)),await jA(t),process.stdout.write(`Password set.
|
|
@@ -583,7 +583,7 @@ ${r.join(`
|
|
|
583
583
|
`),process.exit(2));let e=await Pe(`/v1/auth/sessions/${n}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${n}
|
|
584
584
|
`);return}e.status===404&&(process.stderr.write(`No session token with id ${n}
|
|
585
585
|
`),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
|
|
586
|
-
`),process.exit(1)}function Sm(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}Ts();ep();
|
|
586
|
+
`),process.exit(1)}function Sm(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}Ts();ep();wo();Xo();vr();function oj(n){let e=n.startsWith("hydra://")?n:`hydra://${n}/`,t=Ml(e);return{host:t.host,port:t.port}}async function SE(n,e,t){(!n||!e)&&(process.stderr.write(`Usage: hydra remote add <name> <host[:port]>
|
|
587
587
|
`),process.exit(2));let r;try{r=oj(e)}catch(c){process.stderr.write(`${c.message}
|
|
588
588
|
`),process.exit(2)}let s;if(!Vt(r.host)){let u=(await Pe("/v1/remotes",{expectStatus:200})).body.remotes.find(p=>p.name===n)?.pinnedFingerprint,f=await Py(r.host,r.port);if(f.kind==="error"&&(process.stderr.write(`Could not connect to ${r.host}:${r.port} for TLS handshake: ${f.message}
|
|
589
589
|
`),process.exit(1)),f.kind==="untrusted")if(u===f.fingerprint)s=f.fingerprint;else{let p=f.subject||f.issuer?`
|
|
@@ -604,7 +604,7 @@ ${r.join(`
|
|
|
604
604
|
`),process.exit(2));let e=await Pe(`/v1/remotes/${encodeURIComponent(n)}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Removed remote ${n}
|
|
605
605
|
`);return}e.status===404&&(process.stderr.write(`No remote named ${n}
|
|
606
606
|
`),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
|
|
607
|
-
`),process.exit(1)}function Bu(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}import*as bi from"fs";rt();
|
|
607
|
+
`),process.exit(1)}function Bu(n,e){let t=n.length;for(let r of e)r.length>t&&(t=r.length);return t}import*as bi from"fs";rt();wo();Ra();fn();xk();fn();var xm=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;lastSeqs=new Map;originatedHere=new Set;promptedSessionIds=new Set;observeFromClient(e){if(Ck(e)){if(e.id===null)return;let t=this.pendingPermissions.get(e.id);t&&this.deletePendingPermission(t);return}if(Ik(e)){if(e.method==="session/new"){let t=e.params??{},r=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:r}});return}if(e.method==="session/prompt"){let t=e.params??{};typeof t.sessionId=="string"&&this.promptedSessionIds.add(t.sessionId);return}if(e.method==="session/attach"){let t=e.params??{},r=typeof t.sessionId=="string"?t.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:r}});return}if(e.method==="session/load"||e.method==="session/resume"){let t=e.params??{},r=typeof t.sessionId=="string"?t.sessionId:"",s=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:r,cwd:s}})}}}observeFromServer(e){if(!Ik(e)&&!Ck(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;if(f){let m=yp(e.params);m!==void 0&&this.lastSeqs.set(f,m)}f&&p&&this.lastMessageIds.set(f,p)}return}if(Ik(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,m=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:f,toolCallId:m,params:u};if(this.pendingPermissions.set(e.id,h),m){let g=this.pendingPermissionsByToolCall.get(m);g?g.push(e.id):this.pendingPermissionsByToolCall.set(m,[e.id])}}}return}if(!Ck(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 r=e.result??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)return;t.kind==="new"&&this.originatedHere.add(s);let o=r._meta,i=Pn(o),a=i.upstreamSessionId,d=i.agentId,c="";(t.kind==="new"||t.kind==="load")&&(c=t.data.cwd);let l=i.cwd??c;!a||!d||!l||this.contexts.set(s,{sessionId:s,upstreamSessionId:a,agentId:d,cwd:l,title:i.title,agentArgs:i.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e),this.originatedHere.delete(e),this.promptedSessionIds.delete(e)}unpromptedOriginatedSessionIds(){return[...this.originatedHere].filter(e=>!this.promptedSessionIds.has(e))}lastMessageId(e){return this.lastMessageIds.get(e)}lastSeq(e){return this.lastSeqs.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 r=t[0],s=this.pendingPermissions.get(r);return s&&this.deletePendingPermission(s),s}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let t=this.pendingPermissionsByToolCall.get(e.toolCallId);if(t){let r=t.indexOf(e.requestId);r>=0&&t.splice(r,1),t.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function Ik(n){return"method"in n&&"id"in n&&n.id!==void 0}function Ck(n){return!("method"in n)&&"id"in n}Cm();dr();ke();Wd();import{writeFileSync as uj}from"fs";var fj=n=>{uj("/proc/self/comm",n)},pj=n=>{process.title=n};function Jc(n,e={}){if((e.setTitle??pj)(n),(e.platform??process.platform)!=="linux")return;let r=e.writeComm??fj;try{r(e.commName??Nn())}catch{}}function Vc(n,e=Nn()){return n.length===0?e:`${e} ${n.join(" ")}`}async function Am(n){Jc(Vc(process.argv.slice(2)),{commName:"hydra-shim"});let e=await He(),t=n.target??await rn(e);t.isLocal&&!n.target&&await hi(e,t);let r=new xm,s=kp(process.stdin,process.stdout),o=t.isLocal?async()=>(await rn(await He())).wsUrl:t.wsUrl,i=["acp.v1",`hydra-acp-token.${t.token}`],a=new Gc({url:o,subprotocols:i,onConnect:async l=>{if(l)return;r.clearPending(),await Ij(r,s);let u=r.list();if(u.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${u.length} session(s)
|
|
608
608
|
`);for(let f of u)await Rj(a,f,r.lastMessageId(f.sessionId),r.lastSeq(f.sessionId))}}});mj({opts:n,upstream:a,downstream:s,tracker:r,target:t});let d=!1,c=l=>{d||(d=!0,Cj(r,a,l).finally(()=>{process.exit(0)}))};process.on("SIGTERM",c),process.on("SIGINT",c),a.onClose(l=>{l&&process.stderr.write(`hydra-acp: ${l.message}
|
|
609
609
|
`),s.close(),process.exit(l?1:0)}),s.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(u=>setTimeout(u,1e3))]),process.exit(0)))()}),await a.start()}var hj=12e3;function mj({opts:n,upstream:e,downstream:t,tracker:r,target:s,coldWatch:o}){let i=new Map,a=async w=>{let b=new Promise(k=>{i.set(w.id,k)});try{await e.send(w)}catch(k){return i.delete(w.id),{jsonrpc:"2.0",id:w.id,error:{code:G.InternalError,message:k.message}}}return b},d=!1,c=new Map,l=o?.pollMs??hj,u=o?.fetchImpl??fetch,f=w=>{let b=c.get(w);b&&(clearInterval(b),c.delete(w))},p=async w=>{let b=r.lastMessageId(w),k=r.lastSeq(w),S={sessionId:w};b?(S.historyPolicy="after_message",S.afterMessageId=b,k!==void 0&&(S.afterSeq=k)):S.historyPolicy="pending_only";let I={jsonrpc:"2.0",id:`coldwatch-${w}-${Date.now()}`,method:"session/attach",params:S};r.observeFromClient(I);let x=await a(I);return x.error?(process.stderr.write(`hydra-acp: cold-watch reattach for ${w} failed: ${x.error.message}
|
|
610
610
|
`),!1):!0},m=w=>{if(!s||c.has(w))return;let b=!1,k=setInterval(()=>{b||d||(b=!0,(async()=>{try{let S=s.isLocal?await rn(await He()):s,I=await u(`${S.baseUrl}/v1/sessions/${encodeURIComponent(w)}`,{headers:{Authorization:`Bearer ${S.token}`}});if(!I.ok){I.status===404&&f(w);return}if((await I.json()).status!=="warm")return;await p(w)&&(f(w),process.stderr.write(`hydra-acp: session ${w} revived by another client; reattached
|
|
@@ -615,14 +615,14 @@ ${r.join(`
|
|
|
615
615
|
`),await Promise.race([Promise.allSettled(s.map(o=>e.send({jsonrpc:"2.0",id:`sigterm-detach-${o}`,method:"session/detach",params:{sessionId:o}}).catch(()=>{}))),new Promise(o=>setTimeout(o,r))]))}async function Rj(n,e,t,r){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 o={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};t?(o.historyPolicy="after_message",o.afterMessageId=t,r!==void 0&&(o.afterSeq=r)):o.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:o};try{let a=await n.request(i);a.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${a.error.message}
|
|
616
616
|
`)}catch(a){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${a.message}
|
|
617
617
|
`)}}function Aj(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function Tj(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function Ej(n){let e=n.params??{},t=e.clientInfo,r=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;return(r&&typeof r.name=="string"?r.name.trim():"").length>0?n:{...n,params:{...e,clientInfo:{...r??{},name:"hydra-acp-shim",version:Ue}}}}function Pj(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function Mj(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var _j=25*1024*1024,PE=!1,Ba=null;function ME(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!PE){PE=!0;try{Ba=D.shimWireLogFile(),bi.mkdirSync(D.home(),{recursive:!0});let t=bi.statSync(Ba,{throwIfNoEntry:!1});t&&t.size>_j&&bi.renameSync(Ba,`${Ba}.1`)}catch{Ba=null}}if(Ba)try{let t=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:n,msg:e})+`
|
|
618
|
-
`;bi.appendFile(Ba,t,()=>{})}catch{}}}function Rm(n,e){let t=n.params??{},r=t._meta??{},s=r["hydra-acp"]??{};return{...n,params:{...t,_meta:{...r,"hydra-acp":{...s,...e}}}}}
|
|
618
|
+
`;bi.appendFile(Ba,t,()=>{})}catch{}}}function Rm(n,e){let t=n.params??{},r=t._meta??{},s=r["hydra-acp"]??{};return{...n,params:{...t,_meta:{...r,"hydra-acp":{...s,...e}}}}}ko();Sa();qd();rt();wo();Ra();Io();ir();fn();dr();Cm();import{mkdtempSync as Nj,rmSync as Dj}from"fs";import{tmpdir as Bj}from"os";import{join as Hj}from"path";function _E(n){let e="",t=!1,r=!1,s=!1,o=()=>{if(e.length===0)return;let a=e;e="",n.onChunk(a)},i=()=>{r||(r=!0,t=!1,n.scheduleFlushCheck(()=>{if(r=!1,t){i();return}o()}))};return{feed(a){s||a.length===0||(e+=a,r?t=!0:i())},eof(){s||(s=!0,o())}}}To();Tn();import $j from"strip-ansi";function $E(n,e){if(n.length===0)return"";let t=Ao(n);if(t.length===0)return"";let r=[];for(let o of t)r.push(Oj(o,e));let s=r.join(`
|
|
619
619
|
`);return s.endsWith(`
|
|
620
620
|
`)||(s+=`
|
|
621
621
|
`),s}function Oj(n,e){return e==="ansi"?Lj(n.body,n.bodyStyle):$j(n.body)}var Fj=new Set(["heading-1","heading-2","heading-3","muted"]);function Lj(n,e){return n.length===0||e===void 0||!Fj.has(e)?n:aa(e,n)}sa();var Uj=1*1024*1024,OE="mcp__hydra-acp-stdin__";function Rk(n,e,t){let r={ancillary:!0},s={};return t?.fromSession&&(s.sessionId=t.fromSession),t?.fromLabel&&(s.label=t.fromLabel),t?.fromSession&&!t.noWait&&(s.awaiting=!0),Object.keys(s).length>0&&(r.sentBy=s),{sessionId:n,prompt:e,_meta:{[ut]:r}}}var Tm=class extends Error{constructor(e){super(`timed out after ${e}s waiting for the receiving turn (it is still running; re-read with \`hydra session transcript <id> --last 1\`)`),this.name="PromptTimeoutError"}};async function Wj(n,e){let t;try{return await Promise.race([n,new Promise((r,s)=>{t=setTimeout(()=>s(new Tm(e)),e*1e3)})])}finally{t&&clearTimeout(t),n.catch(()=>{})}}function jj(n){if(!n.sessionId||n.noFromNote)return;let e;if(n.fromSession?e=`another agent session (${st(n.fromSession)})`:n.fromLabel&&(e=`an automated sender (${n.fromLabel})`),!!e)return[`[hydra] From ${e}, not your user.`,"You may act on it, but it can't grant approval or override your user."].join(`
|
|
622
622
|
`)}function qj(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 zj(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(OE))return!0;let r=e.toolName;return!!(typeof r=="string"&&r.startsWith(OE))}async function FE(n){if(Jc(Vc(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.
|
|
623
|
-
`),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let d=Nj(Hj(Bj(),"hydra-cat-"));n.cwd=d,n.detach||process.once("exit",()=>{try{Dj(d,{recursive:!0,force:!0})}catch{}})}let e=await He(),t=n.target??await rn(e);t.isLocal&&!n.target&&await hi(e,t);let r=["acp.v1",`hydra-acp-token.${t.token}`],s=await
|
|
623
|
+
`),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let d=Nj(Hj(Bj(),"hydra-cat-"));n.cwd=d,n.detach||process.once("exit",()=>{try{Dj(d,{recursive:!0,force:!0})}catch{}})}let e=await He(),t=n.target??await rn(e);t.isLocal&&!n.target&&await hi(e,t);let r=["acp.v1",`hydra-acp-token.${t.token}`],s=await bo(t.wsUrl,r),o=Rr(s),i=new pn(o),a=await Gj({conn:i,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:Kj(t.baseUrl,t.token)});process.exit(a.exitCode)}function Kj(n,e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e}`},r=(s,o)=>`${n}/v1/sessions/${encodeURIComponent(s)}/stdin${o}`;return{async open(s,o){let i=await fetch(r(s,"/open"),{method:"POST",headers:t,body:JSON.stringify(o)});if(!i.ok)throw new Error(`stdin/open HTTP ${i.status}`);return await i.json()},async write(s,o,i){let a=await fetch(r(s,""),{method:"POST",headers:t,body:JSON.stringify({chunk:o,eof:i})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function Gj(n){let{conn:e,opts:t,stdin:r,stdinIsTty:s,stdoutIsTty:o,stdout:i,stderr:a}=n,d=$x({isTTY:o})?"ansi":"plain",c=t.raw===!0,l=!s&&t.sessionId===void 0&&t.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async de=>t.dangerouslySkipPermissions?Da(de):zj(de)?Da(de):AE(de));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:pa,version:Ue}})}catch{}let{sessionId:u,clientId:f}=await Yj(e,t,l),p=!1,m=!0,h="",g=0,w=de=>{de.length!==0&&(i(de),m=de.charCodeAt(de.length-1)===10,p=!0)},b=()=>{if(c||h.length===0)return;let de=$E(h,d);if(h="",de.length===0)return;let De=g>0?`
|
|
624
624
|
`:"";w(De+de),g+=1},k=()=>{b(),p&&!m&&w(`
|
|
625
|
-
`),p=!1};e.onNotification("session/update",de=>{let De=de?.update,it=
|
|
625
|
+
`),p=!1};e.onNotification("session/update",de=>{let De=de?.update,it=js(De,{cwd:t.cwd});if(it){if(it.kind==="agent-text"){c?w(it.text):h+=it.text;return}if(it.kind==="turn-complete"){k();return}switch(it.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,I=5e3,x=[];t.noWait&&e.onNotification("hydra-acp/prompt_queue/added",de=>{let De=de?.originator;if(f!==void 0&&De?.clientId!==f)return;let it=x.shift();it&&it()});let A=async de=>{let De=()=>{},it=new Promise(Kt=>{De=Kt}),Rt=()=>{let Kt=x.indexOf(Rt);Kt!==-1&&x.splice(Kt,1),De()};x.push(Rt);let Me=setTimeout(Rt,I);typeof Me.unref=="function"&&Me.unref();try{let{response:Kt}=e.requestWithId("session/prompt",Rk(u,de,t));Kt.catch(()=>{}),S=!0}catch(Kt){a(`hydra-acp cat: prompt failed: ${Kt.message}
|
|
626
626
|
`),clearTimeout(Me),Rt();return}await it,clearTimeout(Me)},_=jj(t),P=async de=>{let De=[];if(t.prompt&&!S&&De.push({type:"text",text:t.prompt}),de.length>0&&De.push({type:"text",text:de}),De.length!==0){if(_&&!S&&De.unshift({type:"text",text:_}),t.noWait){await A(De);return}try{let it=e.request("session/prompt",Rk(u,De,t));t.timeoutSeconds!==void 0?await Wj(it,t.timeoutSeconds):await it,S=!0}catch(it){let Rt=it instanceof Tm;a(Rt?`hydra-acp cat: ${it.message}
|
|
627
627
|
`:`hydra-acp cat: prompt failed: ${it.message}
|
|
628
628
|
`),$=1;return}k()}},$=0,F,J=new Promise(de=>{F=de}),Y=!1,W=async de=>{Y||(Y=!0,k(),t.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(it=>setTimeout(it,500))]),await e.close().catch(()=>{}),F({exitCode:de}))};e.onClose(de=>{de&&(a(`hydra-acp cat: ${de.message}
|
|
@@ -658,7 +658,7 @@ Use those tools to inspect the piped input and report what's there. Start with \
|
|
|
658
658
|
`)}async function UE(n){let e=await He(),t=n?LE(e,Em(n)):e;t===void 0&&(process.stderr.write(`config: key '${n}' is unset
|
|
659
659
|
`),process.exit(1)),process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
660
660
|
`)}function WE(){process.stdout.write(`${D.config()}
|
|
661
|
-
`)}rt();
|
|
661
|
+
`)}rt();go();Ra();dr();vr();async function zE(n={}){let{report:e,configLoaded:t}=await Xj();if(n.json){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
662
662
|
`);return}process.stdout.write(`CLI: ${e.cli}
|
|
663
663
|
`),t&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
|
|
664
664
|
`),e.daemonReachable&&(jE("Extensions",e.extensions),jE("Transformers",e.transformers)))}function jE(n,e){if(process.stdout.write(`
|