@hydra-acp/cli 0.1.65 → 0.1.66
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 +207 -206
- package/dist/index.d.ts +1 -1
- package/dist/index.js +15 -15
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,{encoding:"utf8",mode:384})}async function Mr(){let t=await Os();if(t)return t;let e=Fs();return await Ls(e),process.stderr.write(`hydra-acp: initialized ${
|
|
4
|
-
`),e}var wt=V(()=>{"use strict";de()});import*as Yt from"fs/promises";import*as qc from"fs";import{randomBytes as
|
|
5
|
-
`;await
|
|
6
|
-
`)}async function G(){return await To(),Kc.parse(await Ro())}async function Ns(t){await To();let e=await Ro();t(e),Kc.parse(e),await bt(
|
|
7
|
-
`),i(),e(o);return}if(l===3){i(),n(new Error("password entry cancelled"));return}if(l===127||l===8){o=o.slice(0,-1);continue}o+=String.fromCharCode(l)}},d=c=>{i(),n(c)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",d)}):
|
|
8
|
-
`);i!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,i).replace(/\r$/,"")))},r=o=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(o)};process.stdin.on("data",s),process.stdin.on("error",r)})}var xa=V(()=>{"use strict"});import*as sl from"path";function Mn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=sl.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var $o=V(()=>{"use strict"});import*as ol from"os";async function Qt(t){let e=await Mr(),n=t.daemon.host,s=t.daemon.port,r=!!t.daemon.tls,o=r?"https":"http",i=r?"wss":"ws";return{baseUrl:`${o}://${n}:${s}`,wsUrl:`${i}://${n}:${s}/acp`,token:e,display:`${n}:${s}`,isLocal:mn(n)}}function Aa(t,e){let{httpScheme:n,wsScheme:s}=va(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:al(t),isLocal:t.isLoopback}}async function il(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Ds,r=e.preferServiceToken??!0,o=e.allowPrompt??!0;if(t.isLoopback&&r){let g=await Os();if(g)return Aa(t,g)}let i=e.store??await Mo.load(),a=i.get(t.host,t.port);if(a)return Aa(t,a.token);if(!o)throw new Ca(t.host,t.port);let d=al(t),c=await s(`Password for ${d}: `);if(c.length===0)throw new Error("Password is required to attach to a remote daemon.");let{httpScheme:l}=va(t.host),f=`${l}://${t.host}:${t.port}`,u=await n(`${f}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:c,label:rl()})});if(u.status===401)throw new Error(`Wrong password for ${d}.`);if(u.status===403)throw new Error(`No password is configured on ${d}. Run \`hydra-acp auth password\` on the daemon host first.`);if(u.status===429)throw new Error(`Too many failed login attempts on ${d}; try again later.`);if(!u.ok)throw new Error(`Login to ${d} failed: HTTP ${u.status}`);let p=await u.json();if(!p.session_token||!p.expires_at)throw new Error(`Login to ${d} returned a malformed response.`);return await i.set(t.host,t.port,{token:p.session_token,expiresAt:p.expires_at,label:rl()}),Aa(t,p.session_token)}function rl(){try{let t=ol.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function al(t){let e=t.isLoopback?Bs:443;return t.port===e?t.host:`${t.host}:${t.port}`}var Ca,Hs=V(()=>{"use strict";_e();wt();_r();nl();xa();$o();_r();Ca=class extends Error{host;port;constructor(e,n){let s=n===443?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Mn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{z as x}from"zod";function St(t){if(!t)return{};let e=t[Mt];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=Rg.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Ll.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let o of n.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),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let o of n.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),r.push({messageId:i.messageId,originator:d,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let o of n.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),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let o of n.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),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="live"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}return n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),s}function No(t,e){return{...t??{},[Mt]:e}}function Do(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue)),n}function Bl(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:No(t._meta,Do(t))};return t.title!==void 0&&(e.title=t.title),e}var It,N,Ml,Cg,$l,Rg,_l,Mt,Fl,Ol,Ll,Ax,Tg,Cx,Nl,Ho,Dl,Rx,Tx,Ex,Hl,Px,Ul,Mx,jl,$x,_x,ql,Uo,dt=V(()=>{"use strict";It=1,N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014},Ml=x.object({protocolVersion:x.number().optional(),clientCapabilities:x.record(x.unknown()).optional(),clientInfo:x.object({name:x.string(),version:x.string().optional()}).optional()}),Cg=x.enum(["full","pending_only","none","after_message"]),$l=x.object({cwd:x.string(),mcpServers:x.array(x.unknown()).optional(),_meta:x.record(x.unknown()).optional()}),Rg=x.object({upstreamSessionId:x.string(),agentId:x.string(),cwd:x.string(),title:x.string().optional(),agentArgs:x.array(x.string()).optional()}),_l=x.object({sessionId:x.string(),historyPolicy:Cg.default("full"),afterMessageId:x.string().optional(),clientId:x.string().optional(),clientInfo:x.object({name:x.string(),version:x.string().optional()}).optional(),_meta:x.record(x.unknown()).optional()}),Mt="hydra-acp";Fl=x.object({sessionId:x.string()}),Ol=x.object({cwd:x.string().optional(),cursor:x.string().optional()}),Ll=x.object({used:x.number().optional(),size:x.number().optional(),costAmount:x.number().optional(),costCurrency:x.string().optional()}),Ax=x.object({sessionId:x.string(),upstreamSessionId:x.string().optional(),cwd:x.string(),title:x.string().optional(),agentId:x.string().optional(),currentModel:x.string().optional(),currentUsage:Ll.optional(),importedFromMachine:x.string().optional(),importedFromUpstreamSessionId:x.string().optional(),parentSessionId:x.string().optional(),forkedFromSessionId:x.string().optional(),forkedFromMessageId:x.string().optional(),originatingClient:x.object({name:x.string(),version:x.string().optional()}).optional(),interactive:x.boolean().optional(),updatedAt:x.string(),attachedClients:x.number().int().nonnegative(),status:x.enum(["live","cold"]).default("live"),busy:x.boolean().default(!1),awaitingInput:x.boolean().default(!1),_meta:x.record(x.unknown()).optional()}),Tg=x.object({sessionId:x.string(),cwd:x.string(),title:x.string().optional(),updatedAt:x.string().optional(),_meta:x.record(x.unknown()).optional()}),Cx=x.object({sessions:x.array(Tg),nextCursor:x.string().optional()});Nl=x.object({sessionId:x.string(),prompt:x.array(x.unknown()),_meta:x.record(x.unknown()).optional()}),Ho=x.object({sessionId:x.string()}),Dl=x.object({clientId:x.string(),name:x.string().optional(),version:x.string().optional()}),Rx=x.object({sessionId:x.string(),messageId:x.string(),originator:Dl,prompt:x.array(x.unknown()),position:x.number().int().nonnegative(),queueDepth:x.number().int().positive(),enqueuedAt:x.number()}),Tx=x.object({sessionId:x.string(),messageId:x.string(),prompt:x.array(x.unknown())}),Ex=x.object({sessionId:x.string(),messageId:x.string(),reason:x.enum(["started","cancelled","abandoned"])}),Hl=x.object({sessionId:x.string(),messageId:x.string()}),Px=x.object({cancelled:x.boolean(),reason:x.enum(["ok","not_found","already_running"])}),Ul=x.object({sessionId:x.string(),messageId:x.string(),prompt:x.array(x.unknown())}),Mx=x.object({updated:x.boolean(),reason:x.enum(["ok","not_found","already_running"])}),jl=x.object({sessionId:x.string(),targetMessageId:x.string(),prompt:x.array(x.unknown()),replaceQueue:x.boolean().optional(),onTargetCompleted:x.enum(["reject","send_anyway"]).optional()}),$x=x.object({amended:x.boolean(),reason:x.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:x.string().optional()}),_x=x.object({sessionId:x.string(),cancelledMessageId:x.string(),newMessageId:x.string(),prompt:x.array(x.unknown()),originator:Dl,amendedAt:x.number()}),ql=x.object({agentId:x.string(),version:x.string(),source:x.enum(["binary","npm"]),phase:x.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:x.number().optional(),totalBytes:x.number().optional(),packageSpec:x.string().optional()}),Uo="hydra-acp/agents/install_progress"});import{nanoid as Eg}from"nanoid";var Zt,Fr=V(()=>{"use strict";dt();Zt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)return{id:"",response:Promise.reject(new Error("connection is closed"))};let s=Eg(),r={jsonrpc:"2.0",id:s,method:e,params:n},o=new Promise((i,a)=>{this.pending.set(s,{resolve:d=>i(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:o}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:N.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??N.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);s||(s=[],this.bufferedNotifications.set(e.method,s)),s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});import*as Jl from"fs/promises";function Ug(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Fg,Og,zs,Lg,Bg,Ng,Dg,Hg,zl,Wo,Kl=V(()=>{"use strict";Fg=64*1024*1024,Og=1*1024*1024,zs=64*1024,Lg=6e4,Bg=100,Ng=1e3,Dg=64*1024,Hg=256*1024,zl=20;Wo=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??Fg,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Og,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,n){let s=Math.max(0,Math.min(n,zs));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(f.gap=o),this.closed&&(f.eof=!0),f}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return o>0&&(l.gap=o),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,zs)),s=this.oldestAvailable,r=this.writeCursor-n,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let n=Math.max(0,Math.min(e,zs)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+n);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,Lg));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,o=0;s!==void 0&&s<n&&(o=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(Ug(e.pattern),d),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Bg,Ng)),u=Math.max(1,Math.min(e.maxBytes??Dg,Hg)),p=Math.max(0,Math.min(e.contextBefore??0,zl)),g=Math.max(0,Math.min(e.contextAfter??0,zl)),h=[],w=[],v=[],b=0,A=!1,T=0,$=0,K=(D,_)=>{for(let be of v)be.remaining>0&&(be.match.after===void 0&&(be.match.after=[]),be.match.after.push({cursor:D,line:_}),be.remaining--,b+=_.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(c.test(_)!==l&&h.length<f){let be={cursor:D,line:_};if(p>0&&w.length>0){be.before=w.slice();for(let xe of be.before)b+=xe.line.length}b+=_.length,h.push(be),g>0&&v.push({match:be,remaining:g})}if(p>0)for(w.push({cursor:D,line:_});w.length>p;)w.shift();let q=h.length>=f&&v.length===0,z=b>=u;return q||z};for(let D=0;D<i.length;D++){if(i[D]!==10)continue;let _=i.subarray(T,D).toString("utf8"),H=r+T;if(T=D+1,$=T,K(H,_)){A=!0;break}}if(!A&&T<i.length&&this.closed){let D=i.subarray(T).toString("utf8"),_=r+T;K(_,D)&&(A=!0),$=i.length}let te=Math.min(r+$,this.writeCursor),J={matches:h,truncated:A,nextCursor:te,scannedBytes:$};return o>0&&(J.gap=o),this.closed&&te>=this.writeCursor&&(J.eof=!0),J}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let o=n-this.currentCapacityBytes;e.copy(this.storage,0,o,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,o=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<n&&this.storage.copy(s,o,0,n-o),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Jl.appendFile(n,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var zo,Jx,Vl=V(()=>{"use strict";zo=[{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>",description:"Swap the agent backing this session, preserving context"},{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)"}],Jx=new Map(zo.map(t=>[t.verb,t]))});function Yl(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Js(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.some(r=>r.modelId===t))return{kind:"exact",modelId:t};let n=Yl(t),s=e.map(r=>r.modelId).filter(r=>Yl(r)===n);return s.length===1?{kind:"resolved",modelId:s[0],requested:t}:s.length>1?{kind:"ambiguous",requested:t,candidates:s}:{kind:"unknown",requested:t}}var Jo=V(()=>{"use strict"});function Ql(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=Da(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),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(l,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let f=n.get(l);f?f.push(...c.content):n.set(l,[...c.content])}}let r=[],o=null,i=null;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=Da(d);if(!c||typeof c.sessionUpdate!="string"){r.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?qg(r,o.outIndex,jg(c.content)):(r.push(d),o={outIndex:r.length-1,kind:l});continue}if(o=null,l==="tool_call_update"){let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?Wg(d,n.get(f)??[]):d;f!==void 0&&s.has(f)&&!zg(u)&&(u=Jg(u,s.get(f))),r.push(u);continue}if(l==="plan"){i!==null?r[i]=d:(r.push(d),i=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(i=null),r.push(d)}return r}function Da(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function jg(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function qg(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";t[e]={...s,params:{...r,update:{...o,content:{...i,text:a+n}}}}}function Wg(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function zg(t){let n=Da(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Jg(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Gl=V(()=>{"use strict"});import*as en from"fs/promises";async function Or(t,e){let n=R.queueFile(t);if(e.length===0){await en.unlink(n).catch(()=>{});return}await en.mkdir(R.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
2
|
+
var $h=Object.defineProperty;var V=(t,e)=>()=>(t&&(e=t(t=0)),e);var _h=(t,e)=>{for(var n in e)$h(t,n,{get:e[n],enumerable:!0})};import*as ie from"path";import*as ya from"os";function $e(t){let e=ya.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function pe(){let t=process.env[Nh];if(t&&t.length>0)return ie.resolve(t);if(process.env.VITEST)throw new Error("HYDRA_ACP_HOME is unset under VITEST; vitest.setup.ts must run first");return ie.join(ya.homedir(),".hydra-acp")}var Nh,T,de=V(()=>{"use strict";Nh="HYDRA_ACP_HOME";T={home:pe,config:()=>ie.join(pe(),"config.json"),authToken:()=>ie.join(pe(),"auth-token"),remotes:()=>ie.join(pe(),"remotes.json"),pidFile:()=>ie.join(pe(),"daemon.pid"),logFile:()=>ie.join(pe(),"daemon.log"),currentLogFile:()=>ie.join(pe(),"current.log"),registryCache:()=>ie.join(pe(),"registry.json"),agentsDir:()=>ie.join(pe(),"agents"),agentLogFile:t=>ie.join(pe(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ie.join(pe(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ie.join(pe(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ie.join(pe(),"sessions"),sessionDir:t=>ie.join(pe(),"sessions",t),sessionFile:t=>ie.join(pe(),"sessions",t,"meta.json"),historyFile:t=>ie.join(pe(),"sessions",t,"history.jsonl"),toolsDir:t=>ie.join(pe(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ie.join(pe(),"sessions",t,"tools",e),queueFile:t=>ie.join(pe(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ie.join(pe(),"sessions",".tombstones"),tombstoneAgentDir:t=>ie.join(pe(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ie.join(pe(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ie.join(pe(),"extensions"),extensionLogFile:t=>ie.join(pe(),"extensions",`${t}.log`),extensionPidFile:t=>ie.join(pe(),"extensions",`${t}.pid`),transformersDir:()=>ie.join(pe(),"transformers"),transformerLogFile:t=>ie.join(pe(),"transformers",`${t}.log`),transformerPidFile:t=>ie.join(pe(),"transformers",`${t}.pid`),transformerState:(t,e)=>ie.join(pe(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ie.join(pe(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ie.join(pe(),"prompt-history"),tuiLogFile:()=>ie.join(pe(),"tui.log"),shimWireLogFile:()=>ie.join(pe(),"shim-wire.log")}});import*as _s from"fs/promises";function Fs(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Os(){try{let e=(await _s.readFile(T.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function ce(){let t=await Os();if(!t)throw new Error(`No service token found at ${T.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Ls(t){await _s.mkdir(T.home(),{recursive:!0}),await _s.writeFile(T.authToken(),t+`
|
|
3
|
+
`,{encoding:"utf8",mode:384})}async function Mr(){let t=await Os();if(t)return t;let e=Fs();return await Ls(e),process.stderr.write(`hydra-acp: initialized ${T.authToken()} with a fresh service token.
|
|
4
|
+
`),e}var wt=V(()=>{"use strict";de()});import*as Yt from"fs/promises";import*as qc from"fs";import{randomBytes as Dh}from"crypto";async function bt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
|
|
5
|
+
`;await Hh(t,r,n)}async function Hh(t,e,n={}){let s=Uh(t);await Yt.mkdir(s,{recursive:!0});let r=`${t}.tmp-${process.pid}-${jh()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await Yt.writeFile(r,e,o),await Yt.rename(r,t)}catch(o){throw await Yt.unlink(r).catch(()=>{}),o}if(n.mode!==void 0)try{qc.chmodSync(t,n.mode)}catch{}}async function Pt(t){let e;try{e=await Yt.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Uh(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function jh(){return Dh(4).toString("hex")}var Zn=V(()=>{"use strict"});import*as zc from"fs/promises";import{homedir as wa}from"os";import{z as L}from"zod";function Vc(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Yc(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Ro(){return await Pt(T.config())??{}}async function To(){let t=await Ro(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await zc.access(T.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${T.authToken()} and ${T.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ls(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await bt(T.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${T.config()} to ${T.authToken()}.
|
|
6
|
+
`)}async function G(){return await To(),Kc.parse(await Ro())}async function Ns(t){await To();let e=await Ro();t(e),Kc.parse(e),await bt(T.config(),e,{mode:384})}async function $r(t,e){await Ns(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Eo(t){await Ns(e=>{e.defaultAgent=t})}async function Qc(t,e){await Ns(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Gc(t,e){await Ns(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function ba(t,e){await Ns(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function Xc(t){await Ns(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Zc(){let t=await Ro();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Ht(t){return t==="~"||t==="$HOME"?wa():t.startsWith("~/")?wa()+t.slice(1):t.startsWith("$HOME/")?wa()+t.slice(5):t}var Jc,qh,Bs,Wh,zh,Jh,Kh,Vh,Wc,Yh,Qh,Kc,_e=V(()=>{"use strict";de();wt();Zn();Jc="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",qh=L.object({cert:L.string(),key:L.string()}),Bs=55514,Wh=L.object({host:L.string().default("127.0.0.1"),port:L.number().int().positive().default(Bs),logLevel:L.enum(["debug","info","warn","error"]).default("info"),tls:qh.optional(),sessionIdleTimeoutSeconds:L.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:L.number().int().positive().default(1e4),agentStderrTailBytes:L.number().int().positive().default(4096),publicHost:L.string().optional(),agentSyncIntervalMinutes:L.number().nonnegative().default(60),sessionGcIntervalMinutes:L.number().nonnegative().default(60),sessionGcMaxAgeDays:L.number().positive().default(2)}),zh=L.object({url:L.string().url().default(Jc),ttlHours:L.number().positive().default(24),pinned:L.boolean().default(!1)}),Jh=L.object({name:L.string().optional(),description:L.string().optional(),command:L.string().optional(),args:L.array(L.string()).optional(),env:L.record(L.string()).optional()}),Kh=L.object({packageSpec:L.string().optional()}),Vh=L.object({repaintThrottleMs:L.number().int().nonnegative().default(1e3),maxScrollbackLines:L.number().int().positive().default(1e4),mouse:L.boolean().default(!1),logMaxBytes:L.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:L.number().int().positive().default(32),progressIndicator:L.boolean().default(!0),defaultEnterAction:L.enum(["enqueue","amend"]).default("amend"),showThoughts:L.boolean().default(!0),ambiguousWidth:L.enum(["narrow","wide"]).default("wide"),toolContent:L.enum(["inline","references"]).default("references"),diffContextLines:L.number().int().min(0).default(3),promptHistoryMaxEntries:L.number().int().positive().default(2e3),maxToolItems:L.number().int().nonnegative().default(5),maxPlanItems:L.number().int().nonnegative().default(5),showFileUpdates:L.enum(["none","edit","diff"]).default("edit"),sessionColumns:L.array(L.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Wc=L.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Yh=L.object({command:L.array(L.string()).default([]),args:L.array(L.string()).default([]),env:L.record(L.string()).default({}),enabled:L.boolean().default(!0)}),Qh=L.object({command:L.array(L.string()).default([]),args:L.array(L.string()).default([]),env:L.record(L.string()).default({}),enabled:L.boolean().default(!0)}),Kc=L.object({daemon:Wh.default({}),registry:zh.default({url:Jc,ttlHours:24,pinned:!1}),agents:L.record(L.string(),Jh).default({}),agentOverrides:L.record(L.string(),Kh).default({}),defaultAgent:L.string().default("opencode"),defaultModels:L.record(L.string(),L.string()).default({}),synopsisAgent:L.string().optional(),synopsisModel:L.string().optional(),synopsisOnClose:L.boolean().default(!1),defaultCwd:L.string().default("~"),compressToolContent:L.boolean().default(!0),sessionListColdLimit:L.number().int().nonnegative().default(20),extensions:L.record(Wc,Yh).default({}),transformers:L.record(Wc,Qh).default({}),defaultTransformers:L.array(L.string()).default([]),npmRegistry:L.string().url().optional(),tui:Vh.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!1,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"wide",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit"})})});function mn(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function va(t){return mn(t)?{httpScheme:"http",wsScheme:"ws"}:{httpScheme:"https",wsScheme:"wss"}}function Ia(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${Po(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Po(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let c=Number(n[1]);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=Gh(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Po(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Po(t)}`);let o=mn(r),i;if(s.port){let c=Number(s.port);if(!Number.isInteger(c)||c<=0||c>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);i=c}else i=o?Bs:443;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:i,sessionId:a===""?void 0:a,isLoopback:o}}function el(t){let n=mn(t.host)?Bs:443,s=t.port!==void 0&&t.port!==n?`:${t.port}`:"",r=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${s}${r}`}function Gh(t){try{return new URL(t)}catch{return null}}function Po(t){return t.length>80?`${t.slice(0,77)}...`:t}var _r=V(()=>{"use strict";_e()});function Sa(t,e){return`${t}:${e}`}function tl(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Xh(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Zh(){let t=await Pt(T.remotes());return t===void 0?{version:1,entries:{}}:eg(t)}function eg(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,o]of Object.entries(n)){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),s[r]=a}return{version:1,entries:s}}async function ka(t){await bt(T.remotes(),t,{mode:384})}var Mo,nl=V(()=>{"use strict";de();Zn();Mo=class t{data;constructor(e){this.data=e}static async load(){let e=await Zh(),n=Date.now(),s={},r=!1;for(let[i,a]of Object.entries(e.entries)){if(tl(a,n)){r=!0;continue}s[i]=a}let o={version:1,entries:s};return r&&await ka(o),new t(o)}get(e,n){let s=this.data.entries[Sa(e,n)];if(s&&!tl(s,Date.now()))return s}async set(e,n,s){this.data.entries[Sa(e,n)]=s,await ka(this.data)}async delete(e,n){let s=Sa(e,n);return s in this.data.entries?(delete this.data.entries[s],await ka(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Xh(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Ds(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,o="",i=()=>{s.removeListener("data",a),s.removeListener("error",d),r||s.setRawMode(!1),s.pause()},a=c=>{for(let l of c){if(l===10||l===13){process.stdout.write(`
|
|
7
|
+
`),i(),e(o);return}if(l===3){i(),n(new Error("password entry cancelled"));return}if(l===127||l===8){o=o.slice(0,-1);continue}o+=String.fromCharCode(l)}},d=c=>{i(),n(c)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",d)}):tg()}function tg(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=o=>{n+=o;let i=n.indexOf(`
|
|
8
|
+
`);i!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,i).replace(/\r$/,"")))},r=o=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(o)};process.stdin.on("data",s),process.stdin.on("error",r)})}var xa=V(()=>{"use strict"});import*as sl from"path";function Pn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=sl.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var $o=V(()=>{"use strict"});import*as ol from"os";async function Qt(t){let e=await Mr(),n=t.daemon.host,s=t.daemon.port,r=!!t.daemon.tls,o=r?"https":"http",i=r?"wss":"ws";return{baseUrl:`${o}://${n}:${s}`,wsUrl:`${i}://${n}:${s}/acp`,token:e,display:`${n}:${s}`,isLocal:mn(n)}}function Aa(t,e){let{httpScheme:n,wsScheme:s}=va(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:al(t),isLocal:t.isLoopback}}async function il(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Ds,r=e.preferServiceToken??!0,o=e.allowPrompt??!0;if(t.isLoopback&&r){let g=await Os();if(g)return Aa(t,g)}let i=e.store??await Mo.load(),a=i.get(t.host,t.port);if(a)return Aa(t,a.token);if(!o)throw new Ca(t.host,t.port);let d=al(t),c=await s(`Password for ${d}: `);if(c.length===0)throw new Error("Password is required to attach to a remote daemon.");let{httpScheme:l}=va(t.host),f=`${l}://${t.host}:${t.port}`,u=await n(`${f}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:c,label:rl()})});if(u.status===401)throw new Error(`Wrong password for ${d}.`);if(u.status===403)throw new Error(`No password is configured on ${d}. Run \`hydra-acp auth password\` on the daemon host first.`);if(u.status===429)throw new Error(`Too many failed login attempts on ${d}; try again later.`);if(!u.ok)throw new Error(`Login to ${d} failed: HTTP ${u.status}`);let p=await u.json();if(!p.session_token||!p.expires_at)throw new Error(`Login to ${d} returned a malformed response.`);return await i.set(t.host,t.port,{token:p.session_token,expiresAt:p.expires_at,label:rl()}),Aa(t,p.session_token)}function rl(){try{let t=ol.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function al(t){let e=t.isLoopback?Bs:443;return t.port===e?t.host:`${t.host}:${t.port}`}var Ca,Hs=V(()=>{"use strict";_e();wt();_r();nl();xa();$o();_r();Ca=class extends Error{host;port;constructor(e,n){let s=n===443?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Pn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{z as A}from"zod";function St(t){if(!t)return{};let e=t[Mt];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=Tg.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Ll.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let o of n.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),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let o of n.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),r.push({messageId:i.messageId,originator:d,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let o of n.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),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let o of n.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),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="live"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}return n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),s}function No(t,e){return{...t??{},[Mt]:e}}function Do(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue)),n}function Bl(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:No(t._meta,Do(t))};return t.title!==void 0&&(e.title=t.title),e}var It,N,Ml,Rg,$l,Tg,_l,Mt,Fl,Ol,Ll,Hx,Eg,Ux,Nl,Ho,Dl,jx,qx,Wx,Hl,zx,Ul,Jx,jl,Kx,Vx,ql,Uo,dt=V(()=>{"use strict";It=1,N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014},Ml=A.object({protocolVersion:A.number().optional(),clientCapabilities:A.record(A.unknown()).optional(),clientInfo:A.object({name:A.string(),version:A.string().optional()}).optional()}),Rg=A.enum(["full","pending_only","none","after_message"]),$l=A.object({cwd:A.string(),mcpServers:A.array(A.unknown()).optional(),_meta:A.record(A.unknown()).optional()}),Tg=A.object({upstreamSessionId:A.string(),agentId:A.string(),cwd:A.string(),title:A.string().optional(),agentArgs:A.array(A.string()).optional()}),_l=A.object({sessionId:A.string(),historyPolicy:Rg.default("full"),afterMessageId:A.string().optional(),clientId:A.string().optional(),clientInfo:A.object({name:A.string(),version:A.string().optional()}).optional(),_meta:A.record(A.unknown()).optional()}),Mt="hydra-acp";Fl=A.object({sessionId:A.string()}),Ol=A.object({cwd:A.string().optional(),cursor:A.string().optional()}),Ll=A.object({used:A.number().optional(),size:A.number().optional(),costAmount:A.number().optional(),costCurrency:A.string().optional()}),Hx=A.object({sessionId:A.string(),upstreamSessionId:A.string().optional(),cwd:A.string(),title:A.string().optional(),agentId:A.string().optional(),currentModel:A.string().optional(),currentUsage:Ll.optional(),importedFromMachine:A.string().optional(),importedFromUpstreamSessionId:A.string().optional(),parentSessionId:A.string().optional(),forkedFromSessionId:A.string().optional(),forkedFromMessageId:A.string().optional(),originatingClient:A.object({name:A.string(),version:A.string().optional()}).optional(),interactive:A.boolean().optional(),updatedAt:A.string(),attachedClients:A.number().int().nonnegative(),status:A.enum(["live","cold"]).default("live"),busy:A.boolean().default(!1),awaitingInput:A.boolean().default(!1),_meta:A.record(A.unknown()).optional()}),Eg=A.object({sessionId:A.string(),cwd:A.string(),title:A.string().optional(),updatedAt:A.string().optional(),_meta:A.record(A.unknown()).optional()}),Ux=A.object({sessions:A.array(Eg),nextCursor:A.string().optional()});Nl=A.object({sessionId:A.string(),prompt:A.array(A.unknown()),_meta:A.record(A.unknown()).optional()}),Ho=A.object({sessionId:A.string()}),Dl=A.object({clientId:A.string(),name:A.string().optional(),version:A.string().optional()}),jx=A.object({sessionId:A.string(),messageId:A.string(),originator:Dl,prompt:A.array(A.unknown()),position:A.number().int().nonnegative(),queueDepth:A.number().int().positive(),enqueuedAt:A.number()}),qx=A.object({sessionId:A.string(),messageId:A.string(),prompt:A.array(A.unknown())}),Wx=A.object({sessionId:A.string(),messageId:A.string(),reason:A.enum(["started","cancelled","abandoned"])}),Hl=A.object({sessionId:A.string(),messageId:A.string()}),zx=A.object({cancelled:A.boolean(),reason:A.enum(["ok","not_found","already_running"])}),Ul=A.object({sessionId:A.string(),messageId:A.string(),prompt:A.array(A.unknown())}),Jx=A.object({updated:A.boolean(),reason:A.enum(["ok","not_found","already_running"])}),jl=A.object({sessionId:A.string(),targetMessageId:A.string(),prompt:A.array(A.unknown()),replaceQueue:A.boolean().optional(),onTargetCompleted:A.enum(["reject","send_anyway"]).optional()}),Kx=A.object({amended:A.boolean(),reason:A.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:A.string().optional()}),Vx=A.object({sessionId:A.string(),cancelledMessageId:A.string(),newMessageId:A.string(),prompt:A.array(A.unknown()),originator:Dl,amendedAt:A.number()}),ql=A.object({agentId:A.string(),version:A.string(),source:A.enum(["binary","npm"]),phase:A.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:A.number().optional(),totalBytes:A.number().optional(),packageSpec:A.string().optional()}),Uo="hydra-acp/agents/install_progress"});import{nanoid as Pg}from"nanoid";var Zt,Fr=V(()=>{"use strict";dt();Zt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)return{id:"",response:Promise.reject(new Error("connection is closed"))};let s=Pg(),r={jsonrpc:"2.0",id:s,method:e,params:n},o=new Promise((i,a)=>{this.pending.set(s,{resolve:d=>i(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:o}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:N.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??N.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);s||(s=[],this.bufferedNotifications.set(e.method,s)),s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});import*as Jl from"fs/promises";function jg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Og,Lg,zs,Bg,Ng,Dg,Hg,Ug,zl,Wo,Kl=V(()=>{"use strict";Og=64*1024*1024,Lg=1*1024*1024,zs=64*1024,Bg=6e4,Ng=100,Dg=1e3,Hg=64*1024,Ug=256*1024,zl=20;Wo=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??Og,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Lg,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,n){let s=Math.max(0,Math.min(n,zs));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(f.gap=o),this.closed&&(f.eof=!0),f}let d=Math.min(a,s),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return o>0&&(l.gap=o),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,zs)),s=this.oldestAvailable,r=this.writeCursor-n,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let n=Math.max(0,Math.min(e,zs)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+n);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,Bg));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,o=0;s!==void 0&&s<n&&(o=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(jg(e.pattern),d),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Ng,Dg)),u=Math.max(1,Math.min(e.maxBytes??Hg,Ug)),p=Math.max(0,Math.min(e.contextBefore??0,zl)),g=Math.max(0,Math.min(e.contextAfter??0,zl)),h=[],w=[],v=[],b=0,x=!1,E=0,$=0,K=(D,_)=>{for(let be of v)be.remaining>0&&(be.match.after===void 0&&(be.match.after=[]),be.match.after.push({cursor:D,line:_}),be.remaining--,b+=_.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(c.test(_)!==l&&h.length<f){let be={cursor:D,line:_};if(p>0&&w.length>0){be.before=w.slice();for(let xe of be.before)b+=xe.line.length}b+=_.length,h.push(be),g>0&&v.push({match:be,remaining:g})}if(p>0)for(w.push({cursor:D,line:_});w.length>p;)w.shift();let q=h.length>=f&&v.length===0,z=b>=u;return q||z};for(let D=0;D<i.length;D++){if(i[D]!==10)continue;let _=i.subarray(E,D).toString("utf8"),H=r+E;if(E=D+1,$=E,K(H,_)){x=!0;break}}if(!x&&E<i.length&&this.closed){let D=i.subarray(E).toString("utf8"),_=r+E;K(_,D)&&(x=!0),$=i.length}let te=Math.min(r+$,this.writeCursor),J={matches:h,truncated:x,nextCursor:te,scannedBytes:$};return o>0&&(J.gap=o),this.closed&&te>=this.writeCursor&&(J.eof=!0),J}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let o=n-this.currentCapacityBytes;e.copy(this.storage,0,o,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,o=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<n&&this.storage.copy(s,o,0,n-o),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Jl.appendFile(n,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var zo,aA,Vl=V(()=>{"use strict";zo=[{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>",description:"Swap the agent backing this session, preserving context"},{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)"}],aA=new Map(zo.map(t=>[t.verb,t]))});function Yl(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Js(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.some(r=>r.modelId===t))return{kind:"exact",modelId:t};let n=Yl(t),s=e.map(r=>r.modelId).filter(r=>Yl(r)===n);return s.length===1?{kind:"resolved",modelId:s[0],requested:t}:s.length>1?{kind:"ambiguous",requested:t,candidates:s}:{kind:"unknown",requested:t}}var Jo=V(()=>{"use strict"});function Ql(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=Da(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),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(l,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let f=n.get(l);f?f.push(...c.content):n.set(l,[...c.content])}}let r=[],o=null,i=null;for(let a=0;a<t.length;a++){let d=t[a];if(d===void 0)continue;let c=Da(d);if(!c||typeof c.sessionUpdate!="string"){r.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?Wg(r,o.outIndex,qg(c.content)):(r.push(d),o={outIndex:r.length-1,kind:l});continue}if(o=null,l==="tool_call_update"){let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?zg(d,n.get(f)??[]):d;f!==void 0&&s.has(f)&&!Jg(u)&&(u=Kg(u,s.get(f))),r.push(u);continue}if(l==="plan"){i!==null?r[i]=d:(r.push(d),i=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(i=null),r.push(d)}return r}function Da(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function qg(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Wg(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";t[e]={...s,params:{...r,update:{...o,content:{...i,text:a+n}}}}}function zg(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function Jg(t){let n=Da(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Kg(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Gl=V(()=>{"use strict"});import*as en from"fs/promises";async function Or(t,e){let n=T.queueFile(t);if(e.length===0){await en.unlink(n).catch(()=>{});return}await en.mkdir(T.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`;await en.writeFile(n,s,"utf8")}async function Xl(t){let e=
|
|
11
|
-
`))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Zl(t){let e=R.queueFile(t);await en.unlink(e).catch(()=>{})}var Ha=V(()=>{"use strict";de()});import{customAlphabet as tu}from"nanoid";import*as ru from"fs/promises";function Ks(){return`m_${su()}`}function Oe(t){return t.startsWith(hn)?t.slice(hn.length):t}function kt(t,e){return t.code=e,t}function Qg(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Yg.has(s)}function Gg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Xg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Zg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ss(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function Ys(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={id:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function ey(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.availableModes;if(!Array.isArray(s))return[];let r=[];for(let o of s){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),r.push(a)}return r}function ty(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function ny(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.commands;if(!Array.isArray(s))return[];let r=[];for(let o of s){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),r.push(a)}return r}function sy(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:Ks()}}}function qa(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function ry(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function oy(t){let e=iy(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=ay(t.resolver),n}function iy(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let o=e.reason;return typeof o=="string"&&(s.reason=o),s}function ay(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function ns(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function ja(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Wa(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var nu,su,eu,hn,Kg,Ua,Vg,Vs,Yg,tn=V(()=>{"use strict";Kl();Vl();Jo();Gl();Ha();dt();nu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",su=tu(nu,16),eu=tu(nu,16),hn="hydra_session_";Kg=1e3,Ua=300*1e3,Vg=64,Vs=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}title;currentModel;currentMode;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){this.sessionId=e.sessionId??`${hn}${su()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Kg,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){ty(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,n=new Set,s=0){let r=e,o=this.injectCumulativeCost(e);for(let d=s;d<this.transformChain.length;d++){let c=this.transformChain[d];if(n.has(c.name)||!c.intercepts.has("response:session/update"))continue;let l=`t_${eu()}`,f;try{f=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return;if(u==="processing"){let p=d,g=o,h=new Set(n);await new Promise(w=>{let v=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.runResponseChain(g,new Set([...h,c.name]),p+1).then(w))},Ua);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:()=>w(),timer:v,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(c.name)}let i=ny(o);if(i!==null){this.setAgentAdvertisedCommands(i);return}let a=ey(o);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let n=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),n.push(r)}return n}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.inFlightPermissions.size>0}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}attach(e,n,s={}){if(this.closed)throw kt(new Error("session is closed"),N.SessionNotFound);if(this.clients.has(e.clientId))throw kt(new Error(`client ${e.clientId} is already attached`),N.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=i=>n.raw?i:Ql(i),r=await this.getHistorySnapshot(n.toolContent??"inline"),o=this.buildStateSnapshotReplay();if(e==="after_message"){let i=n.afterMessageId?qa(r,n.afterMessageId):-1;return i<0?{entries:[...o,...s(r)],appliedPolicy:"full"}:{entries:[...o,...s(r.slice(i+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(r)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:n,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:n,update:i},recordedAt:s})}return e}replayPendingPermissions(e){for(let n of this.inFlightPermissions)n.addClient(e)}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,n){let s=this.clients.get(e);if(!s)throw kt(new Error("client not attached"),N.SessionNotFound);if(this.closing)throw kt(new Error("session is closing; new prompts cannot be accepted"),N.SessionClosing);let r=ns((n??{}).prompt).trim();if(r.startsWith("/hydra"))return this.handleSlashCommand(r);let o=Ks();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(St((n??{})._meta).ancillary===!0)&&this._interactive===void 0){this._interactive=!0;for(let a of this.interactiveHandlers)try{a(!0)}catch{}}return this.enqueueUserPrompt(s,n,o)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:n}},e.clientId);let s=ns(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}broadcastTurnComplete(e,n,s,r){let o=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Ks()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>Vg;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};n?.amending!==void 0&&(o._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,n){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw kt(new Error("client not attached"),N.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let o=Ks(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,n){let s=Ks(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw kt(new Error("client not attached"),N.SessionNotFound);this.lastCancelAt=Date.now(),await this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId})}addTransformer(e){let n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,n,s=new Set,r=0){let o=this.rewriteForAgent(n);for(let i=r;i<this.transformChain.length;i++){let a=this.transformChain[i];if(s.has(a.name))continue;let d=`request:${e}`;if(!a.intercepts.has(d))continue;let c=`t_${eu()}`,l;try{l=await a.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(u){this.logger?.warn(`transformer ${a.name} error on ${d}: ${u.message}`);continue}let f=l?.action??"continue";if(f==="stop")return l?.payload??ja(e);if(f==="processing"){let u=i,p=o,g=new Set(s);return new Promise(h=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:a.name}),this.forwardRequest(e,p,new Set([...g,a.name]),u+1).then(h).catch(()=>h(ja(e))))},Ua);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:h,timer:w,transformerName:a.name,method:e,envelope:p,chainIdx:u,originatedBy:g,side:"request"})})}s.add(a.name)}return this.agent.connection.request(e,o)}dischargeClaim(e,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):Ua,o=setTimeout(()=>{this.pendingClaims.delete(e)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response"?this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)):this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve(ja(s.method))))},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,i,o);return}await this.forwardRequest(n,s,i,o)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){this.closeHandlers.push(e)}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=ns((e??{}).prompt),r=Wa(s,200);r&&(this._firstPromptSeeded=!0,this.setTitle(r))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=ss(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.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 s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=ss(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=i.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(i.id==="mode"){let a=Ys(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=i.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let o=r.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 s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let n={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=n;for(let s of this.usageHandlers)try{s(n)}catch{}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Gg(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Xg(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),Zg(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}applyModelChange(e){let n=e.trim();if(!n)return;if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}applyModeChange(e){let n=e.trim();if(!n)return;if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...n,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{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"}];if(this.extensionCommands)for(let{name:n,command:s}of this.extensionCommands.list()){let r=`hydra ${n} ${s.verb}`,i={name:s.argsHint?`${r} ${s.argsHint}`:r};s.description&&(i.description=s.description),e.push(i)}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e){let s=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),r=s?.[1]??"",o=(s?.[2]??"").trim();if(r==="")return{stopReason:"end_turn"};if(zo.some(d=>d.verb===r))switch(r){case"title":return this.runTitleCommand(o);case"agent":return this.runAgentCommand(o);case"kill":return this.runKillCommand();case"restart":return this.runRestartCommand();default:{let d=new Error(`no dispatcher for /hydra verb ${r}`);throw d.code=N.InternalError,d}}if(this.extensionCommands?.has(r))return this.runExtensionCommand(r,o);let i=zo.map(d=>d.verb);if(this.extensionCommands){let d=new Set;for(let{name:c}of this.extensionCommands.list())d.has(c)||(i.push(c),d.add(c))}let a=new Error(`unknown /hydra verb: ${r} (known: ${i.join(", ")})`);throw a.code=N.InvalidParams,a}runExtensionCommand(e,n){return this.enqueuePrompt(async()=>{let s=this.extensionCommands?.get(e);if(!s)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let r=n.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o===""){let c=s.commands.map(l=>l.verb).join(", ");return this.emitExtensionReply(`/hydra ${e} requires a verb (known: ${c||"(none)"})`)}if(!s.commands.some(c=>c.verb===o)){let c=s.commands.map(l=>l.verb).join(", ");return this.emitExtensionReply(`unknown verb "${o}" for ${e} (known: ${c||"(none)"})`)}let a;try{a=await s.connection.request("hydra-acp/commands/invoke",{sessionId:this.sessionId,verb:o,args:i})}catch(c){return this.emitExtensionReply(`${e} ${o}: ${c.message}`)}let d=a&&typeof a=="object"&&typeof a.text=="string"?a.text:"";return d.length>0?this.emitExtensionReply(d):{stopReason:"end_turn"}})}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
10
|
+
`;await en.writeFile(n,s,"utf8")}async function Xl(t){let e=T.queueFile(t),n;try{n=await en.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
|
|
11
|
+
`))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Zl(t){let e=T.queueFile(t);await en.unlink(e).catch(()=>{})}var Ha=V(()=>{"use strict";de()});import{customAlphabet as tu}from"nanoid";import*as ru from"fs/promises";function Ks(){return`m_${su()}`}function Oe(t){return t.startsWith(hn)?t.slice(hn.length):t}function kt(t,e){return t.code=e,t}function Gg(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Qg.has(s)}function Xg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Zg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ey(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ns(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function Ys(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={id:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function ty(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.availableModes;if(!Array.isArray(s))return[];let r=[];for(let o of s){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),r.push(a)}return r}function ny(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function sy(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.commands;if(!Array.isArray(s))return[];let r=[];for(let o of s){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),r.push(a)}return r}function ry(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:Ks()}}}function qa(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function oy(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function iy(t){let e=ay(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=dy(t.resolver),n}function ay(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let o=e.reason;return typeof o=="string"&&(s.reason=o),s}function dy(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function ts(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function ja(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Wa(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var nu,su,eu,hn,Vg,Ua,Yg,Vs,Qg,tn=V(()=>{"use strict";Kl();Vl();Jo();Gl();Ha();dt();nu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",su=tu(nu,16),eu=tu(nu,16),hn="hydra_session_";Vg=1e3,Ua=300*1e3,Yg=64,Vs=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}title;currentModel;currentMode;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){this.sessionId=e.sessionId??`${hn}${su()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Vg,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){ny(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,n=new Set,s=0){let r=e,o=this.injectCumulativeCost(e);for(let d=s;d<this.transformChain.length;d++){let c=this.transformChain[d];if(n.has(c.name)||!c.intercepts.has("response:session/update"))continue;let l=`t_${eu()}`,f;try{f=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return;if(u==="processing"){let p=d,g=o,h=new Set(n);await new Promise(w=>{let v=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.runResponseChain(g,new Set([...h,c.name]),p+1).then(w))},Ua);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:()=>w(),timer:v,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(c.name)}let i=sy(o);if(i!==null){this.setAgentAdvertisedCommands(i);return}let a=ty(o);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let n=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),n.push(r)}return n}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.inFlightPermissions.size>0}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}attach(e,n,s={}){if(this.closed)throw kt(new Error("session is closed"),N.SessionNotFound);if(this.clients.has(e.clientId))throw kt(new Error(`client ${e.clientId} is already attached`),N.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=i=>n.raw?i:Ql(i),r=await this.getHistorySnapshot(n.toolContent??"inline"),o=this.buildStateSnapshotReplay();if(e==="after_message"){let i=n.afterMessageId?qa(r,n.afterMessageId):-1;return i<0?{entries:[...o,...s(r)],appliedPolicy:"full"}:{entries:[...o,...s(r.slice(i+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(r)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:n,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:n,update:i},recordedAt:s})}return e}replayPendingPermissions(e){for(let n of this.inFlightPermissions)n.addClient(e)}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,n){let s=this.clients.get(e);if(!s)throw kt(new Error("client not attached"),N.SessionNotFound);if(this.closing)throw kt(new Error("session is closing; new prompts cannot be accepted"),N.SessionClosing);let r=ts((n??{}).prompt).trim();if(r.startsWith("/hydra"))return this.handleSlashCommand(r);let o=Ks();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(St((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let a of this.interactiveHandlers)try{a(!0)}catch{}}return this.enqueueUserPrompt(s,n,o)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:n}},e.clientId);let s=ts(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}broadcastTurnComplete(e,n,s,r){let o=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Ks()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>Yg;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};n?.amending!==void 0&&(o._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,n){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw kt(new Error("client not attached"),N.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let d=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let o=Ks(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,n){let s=Ks(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw kt(new Error("client not attached"),N.SessionNotFound);this.lastCancelAt=Date.now(),await this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId})}addTransformer(e){let n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,n,s=new Set,r=0){let o=this.rewriteForAgent(n);for(let i=r;i<this.transformChain.length;i++){let a=this.transformChain[i];if(s.has(a.name))continue;let d=`request:${e}`;if(!a.intercepts.has(d))continue;let c=`t_${eu()}`,l;try{l=await a.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(u){this.logger?.warn(`transformer ${a.name} error on ${d}: ${u.message}`);continue}let f=l?.action??"continue";if(f==="stop")return l?.payload??ja(e);if(f==="processing"){let u=i,p=o,g=new Set(s);return new Promise(h=>{let w=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:a.name}),this.forwardRequest(e,p,new Set([...g,a.name]),u+1).then(h).catch(()=>h(ja(e))))},Ua);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(c,{resolve:h,timer:w,transformerName:a.name,method:e,envelope:p,chainIdx:u,originatedBy:g,side:"request"})})}s.add(a.name)}return this.agent.connection.request(e,o)}dischargeClaim(e,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):Ua,o=setTimeout(()=>{this.pendingClaims.delete(e)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response"?this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)):this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve(ja(s.method))))},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,i,o);return}return this.forwardRequest(n,s,i,o)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){this.closeHandlers.push(e)}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=ts((e??{}).prompt),r=Wa(s,200);r&&(this._firstPromptSeeded=!0,this.setTitle(r))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=ns(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.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 s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=ns(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=i.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(i.id==="mode"){let a=Ys(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=i.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let o=r.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 s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let n={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=n;for(let s of this.usageHandlers)try{s(n)}catch{}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Xg(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Zg(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),ey(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}applyModelChange(e){let n=e.trim();if(!n)return;if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}applyModeChange(e){let n=e.trim();if(!n)return;if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...n,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{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"}];if(this.extensionCommands)for(let{name:n,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${n} ${s.verb}`:`hydra ${n}`,i={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(i.description=s.description),e.push(i),n.startsWith("hydra-acp-")){let a=n.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e){let s=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),r=s?.[1]??"",o=(s?.[2]??"").trim();if(r==="")return{stopReason:"end_turn"};if(zo.some(c=>c.verb===r))switch(r){case"title":return this.runTitleCommand(o);case"agent":return this.runAgentCommand(o);case"kill":return this.runKillCommand();case"restart":return this.runRestartCommand();default:{let c=new Error(`no dispatcher for /hydra verb ${r}`);throw c.code=N.InternalError,c}}if(this.extensionCommands?.has(r))return this.runExtensionCommand(r,o);let i=`hydra-acp-${r}`;if(this.extensionCommands?.has(i))return this.runExtensionCommand(i,o);let a=zo.map(c=>c.verb);if(this.extensionCommands){let c=new Set;for(let{name:l}of this.extensionCommands.list())c.has(l)||(a.push(l),c.add(l))}let d=new Error(`unknown /hydra verb: ${r} (known: ${a.join(", ")})`);throw d.code=N.InvalidParams,d}runExtensionCommand(e,n){return this.enqueuePrompt(async()=>{let s=this.extensionCommands?.get(e);if(!s)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let r=n.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(!s.commands.some(c=>c.verb===o)){let c=s.commands.map(l=>l.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${c||"(none)"})`)}let a;try{a=await s.connection.request("hydra-acp/commands/invoke",{sessionId:this.sessionId,verb:o,args:i})}catch(c){return this.emitExtensionReply(`${e} ${o}: ${c.message}`)}let d=a&&typeof a=="object"&&typeof a.text=="string"?a.text:"";return d.length>0?this.emitExtensionReply(d):{stopReason:"end_turn"}})}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
12
12
|
${e}
|
|
13
13
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let n=await this.listSessions();if(n.length===0)e="_(no sessions)_";else{let s=n.map(r=>{let o=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",d=r.title?` ${r.title}`:"";return`\`${o}\` ${r.cwd}${i}${a}${d}`});e=`Sessions (${n.length}):
|
|
14
14
|
${s.join(`
|
|
@@ -29,9 +29,9 @@ Available models:
|
|
|
29
29
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(c=>c.id===o):!0,d=r.map(c=>{let l=c.id===o?"\u25B6 ":" ",f=c.name&&c.name!==c.id?` ${c.name}`:"";return`${l}${c.id}${f}`});!a&&o&&d.unshift(`\u25B6 ${o}`),i=d.join(`
|
|
30
30
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
31
31
|
${i}
|
|
32
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(o=>o.id).join(", ");throw kt(new Error(`unknown mode: ${n} (known: ${r})`),N.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}runTitleCommand(e){return this.enqueuePrompt(async()=>e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"}))}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let n={chunks:[]};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){if(!e)throw kt(new Error("/hydra agent requires an agent id"),N.InvalidParams);if(e===this.agentId)throw kt(new Error(`already on agent ${e}`),N.InvalidParams);if(!this.spawnReplacementAgent)throw kt(new Error("agent switching not configured for this session"),N.InternalError);let n=this.spawnReplacementAgent;return this.enqueuePrompt(async()=>{let s=this.agentId,r=await this.buildSwitchTranscript(s),o=await n({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(o.agent);let i=this.agent;this.agent=o.agent,this.agentId=e,this.upstreamSessionId=o.upstreamSessionId,this.agentMeta=o.agentMeta,this.agentCapabilities=o.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=o.initialModel,this.currentMode=o.initialMode,this.setAgentAdvertisedModels(o.initialModels??[]),this.setAgentAdvertisedModes(o.initialModes??[]),await i.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let d of this.agentChangeHandlers)try{d(a)}catch{}return{stopReason:"end_turn"}})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){if(!this.spawnReplacementAgent)throw kt(new Error("agent restart not configured for this session"),N.InternalError);return this.enqueuePrompt(async()=>(await this.respawnAgent(),{stopReason:"end_turn"}))}async forceCancel(){if(this.closed||this.closing)throw kt(new Error("session is closing"),N.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await o.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(n,n);let i={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let f=(c.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let g=
|
|
33
|
-
`)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new Wo(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(n??zs,zs)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(i.nextCursor,s);(d==="data"||d==="eof")&&(i=r.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 s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,n){return this.requireStreamBuffer().waitForData(e,n)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=N.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0),this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let n=this.promptQueue;this.promptQueue=[];for(let r of n){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Zl(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),o!==void 0&&r.drainFileWrites().then(()=>ru.unlink(o).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let n=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(n).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,n){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),o=!
|
|
34
|
-
`)&&(n==="/model"||n.startsWith("/model ")||n==="/mode"||n.startsWith("/mode ")||n==="/sessions"||n==="/help")){let r;return n==="/sessions"?r=await this.handleSessionsCommand():n==="/help"?r=await this.handleHelpCommand():n==="/mode"||n.startsWith("/mode ")?r=await this.handleModeCommand(n):r=await this.handleModelCommand(n),this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}let s;try{s=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(r){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}return this.closed||this.broadcastTurnComplete(e.clientId,s,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),s}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};
|
|
32
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(o=>o.id).join(", ");throw kt(new Error(`unknown mode: ${n} (known: ${r})`),N.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}runTitleCommand(e){return this.enqueuePrompt(async()=>e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"}))}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let n={chunks:[]};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){if(!e)throw kt(new Error("/hydra agent requires an agent id"),N.InvalidParams);if(e===this.agentId)throw kt(new Error(`already on agent ${e}`),N.InvalidParams);if(!this.spawnReplacementAgent)throw kt(new Error("agent switching not configured for this session"),N.InternalError);let n=this.spawnReplacementAgent;return this.enqueuePrompt(async()=>{let s=this.agentId,r=await this.buildSwitchTranscript(s),o=await n({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(o.agent);let i=this.agent;this.agent=o.agent,this.agentId=e,this.upstreamSessionId=o.upstreamSessionId,this.agentMeta=o.agentMeta,this.agentCapabilities=o.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=o.initialModel,this.currentMode=o.initialMode,this.setAgentAdvertisedModels(o.initialModels??[]),this.setAgentAdvertisedModes(o.initialModes??[]),await i.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let d of this.agentChangeHandlers)try{d(a)}catch{}return{stopReason:"end_turn"}})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){if(!this.spawnReplacementAgent)throw kt(new Error("agent restart not configured for this session"),N.InternalError);return this.enqueuePrompt(async()=>(await this.respawnAgent(),{stopReason:"end_turn"}))}async forceCancel(){if(this.closed||this.closing)throw kt(new Error("session is closing"),N.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await o.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(n,n);let i={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let f=(c.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let g=ts(f.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let h=f.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let g=f.status,h=f.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${g}`})}}if(s.length===0)return"";let o=[],i;for(let c of s)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=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=n?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,d,"","--- begin transcript ---",...o,"--- end transcript ---"].join(`
|
|
33
|
+
`)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new Wo(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(n??zs,zs)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(i.nextCursor,s);(d==="data"||d==="eof")&&(i=r.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 s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,n){return this.requireStreamBuffer().waitForData(e,n)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=N.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0),this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let n=this.promptQueue;this.promptQueue=[];for(let r of n){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Zl(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),o!==void 0&&r.drainFileWrites().then(()=>ru.unlink(o).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let n=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(n).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,n){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),o=!Gg(e,r),i=o?ry(e,r):r;if(o){let a={method:e,params:i,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,i).catch(()=>{})}async handlePermissionRequest(e){let n=[...this.clients.values()];if(n.length===0)throw kt(new Error("no clients attached to handle permission request"),N.PermissionDenied);let s=this.rewriteForClient(e),r=oy(s);return new Promise((o,i)=>{let a=!1,d=[],c={addClient:u};this.inFlightPermissions.add(c);let l=this.sessionId,f=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function u(p){if(a)return;let g=p.connection.request("session/request_permission",s);d.push({client:p}),g.then(h=>{f(()=>{let w=iy({toolCallId:r,result:h,resolver:p});for(let v of d)v.client.clientId!==p.clientId&&v.client.connection.notify("session/update",{sessionId:l,update:w}).catch(()=>{});o(h)})}).catch(h=>{f(()=>i(h))})}for(let p of n)u(p)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Ks(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],o={clientId:e.clientId};return e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),new Promise((i,a)=>{let d={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:i,reject:a};this.promptQueue.push(d),this.persistRewrite(),this.broadcastQueueAdded(d),this.drainQueue()})}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Or(n,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=ts(e.prompt).replace(/\s+$/,"");if(!n.includes(`
|
|
34
|
+
`)&&(n==="/model"||n.startsWith("/model ")||n==="/mode"||n.startsWith("/mode ")||n==="/sessions"||n==="/help")){let r;return n==="/sessions"?r=await this.handleSessionsCommand():n==="/help"?r=await this.handleHelpCommand():n==="/mode"||n.startsWith("/mode ")?r=await this.handleModeCommand(n):r=await this.handleModelCommand(n),this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}let s;try{s=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(r){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}return this.closed||this.broadcastTurnComplete(e.clientId,s,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),s}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};Qg=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"])});import{z as Ut}from"zod";function iu(t){let e=t.trim();if(e.length===0)return;let n=ou(e);if(n===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");if(o<0||i<=o||(n=ou(e.slice(o,i+1)),n===void 0))return}if(n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let o=s.title.trim();o.length>0&&(r.title=o.slice(0,cy))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=Lr.safeParse(s.synopsis);o.success&&ly(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function ou(t){try{return JSON.parse(t)}catch{return}}function ly(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0}var Lr,cy,za,Ko=V(()=>{"use strict";Lr=Ut.object({goal:Ut.string().optional(),outcome:Ut.string().optional(),files_touched:Ut.array(Ut.string()).optional(),tools_used:Ut.array(Ut.string()).optional(),rejected_approaches:Ut.array(Ut.string()).optional(),open_threads:Ut.array(Ut.string()).optional()}),cy=200,za=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
35
35
|
{
|
|
36
36
|
"title": "short summary, max 80 chars",
|
|
37
37
|
"synopsis": {
|
|
@@ -41,24 +41,24 @@ ${i}
|
|
|
41
41
|
"open_threads": ["work started but not finished"]
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
Use empty arrays/strings where a field doesn't apply.`});import*as Qs from"fs/promises";import*as
|
|
45
|
-
`))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function jr(t,e,n=Au){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function
|
|
44
|
+
Use empty arrays/strings where a field doesn't apply.`});import*as Qs from"fs/promises";import*as kA from"path";import{customAlphabet as uy}from"nanoid";import{z as re}from"zod";function Br(){return`${my}${py()}`}function yy(t){if(!Ja.test(t))throw new Error(`unsafe session id: ${t}`)}function Ga(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var fy,py,my,Ka,Va,hy,Ya,Qa,gy,Ja,Vo,Xa=V(()=>{"use strict";de();Zn();Ko();fy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",py=uy(fy,16),my="hydra_lineage_";Ka=re.object({name:re.string(),description:re.string().optional()}),Va=re.object({id:re.string(),name:re.string().optional(),description:re.string().optional()}),hy=re.object({modelId:re.string(),name:re.string().optional(),description:re.string().optional()}),Ya=re.object({used:re.number().optional(),size:re.number().optional(),costAmount:re.number().optional(),costCurrency:re.string().optional(),cumulativeCost:re.number().optional()}),Qa=re.object({name:re.string(),version:re.string().optional()}),gy=re.object({version:re.literal(1),sessionId:re.string(),lineageId:re.string().optional(),upstreamSessionId:re.string(),importedFromSessionId:re.string().optional(),importedFromUpstreamSessionId:re.string().optional(),importedFromMachine:re.string().optional(),agentId:re.string(),cwd:re.string(),title:re.string().optional(),synopsis:Lr.optional(),summarizedThroughEntry:re.number().int().nonnegative().optional(),agentArgs:re.array(re.string()).optional(),currentModel:re.string().optional(),currentMode:re.string().optional(),currentUsage:Ya.optional(),agentCommands:re.array(Ka).optional(),agentModes:re.array(Va).optional(),agentModels:re.array(hy).optional(),pendingHistorySync:re.boolean().optional(),parentSessionId:re.string().optional(),forkedFromSessionId:re.string().optional(),forkedFromMessageId:re.string().optional(),originatingClient:Qa.optional(),interactive:re.boolean().optional(),createdAt:re.string(),updatedAt:re.string()}),Ja=/^[A-Za-z0-9_-]+$/;Vo=class{async write(e){yy(e.sessionId);let n={version:1,...e};await bt(T.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Ja.test(e))return;let n=await Pt(T.sessionFile(e));if(n!==void 0)try{return gy.parse(n)}catch{return}}async delete(e){if(Ja.test(e)){try{await Qs.unlink(T.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Qs.rmdir(T.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await Qs.readdir(T.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as by}from"url";import*as Nr from"path";import*as Qo from"fs";function vy(){try{let t=Nr.dirname(by(import.meta.url));for(let e=0;e<8;e+=1){let n=Nr.join(t,"package.json");if(Qo.existsSync(n)){let r=JSON.parse(Qo.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=Nr.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var le,ss,jt=V(()=>{"use strict";le=vy(),ss="hydra-acp-cat"});function Za(t){let e=new Map;for(let n of yu(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function mu(t){return Za(t).map(e=>e.name)}function ed(t){let e=new Map;for(let n of yu(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,s])=>{let r=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:n,count:o,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function hu(t){return ed(t).map(e=>e.path)}function gu(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function yu(t){let e=new Map,n=0;for(let s of t){let o=s.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${n++}`,c=e.get(d);c===void 0?(c={toolName:fu(o),paths:new Set},e.set(d,c)):c.toolName=fu(o);for(let l of pu(o.rawInput,o.locations))c.paths.add(l);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let d of pu(o.rawInput,o.locations))a.paths.add(d)}return e}function fu(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function pu(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&n.add(i)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var td=V(()=>{"use strict"});import{promises as Hr}from"fs";import*as ad from"path";async function Ur(t){let e;try{e=await Hr.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Uy(e)}function Uy(t){let e=[];for(let n of t.split(`
|
|
45
|
+
`))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function jr(t,e,n=Au){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function rs(t,e){await Hr.mkdir(ad.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await Hr.writeFile(t,n.length>0?n.join(`
|
|
46
46
|
`)+`
|
|
47
47
|
`:"")}async function Cu(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await Hr.mkdir(ad.dirname(t),{recursive:!0}),await Hr.appendFile(t,JSON.stringify(n)+`
|
|
48
|
-
`,{encoding:"utf8"}))}function Zo(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function dd(t,e,n=Au){if(e.length===0)return t;let s=new Set(t),r=t;for(let o of e){let i=o.replace(/\n+$/,"");i.length!==0&&(s.has(i)||(s.add(i),r=jr(r,i,n)))}return r}var Au,ei=V(()=>{"use strict";Au=500});import{z as he}from"zod";function qr(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function qt(t){return qy.parse(t)}var Uy,jy,qy,is=V(()=>{"use strict";Xa();Ko();Uy=he.object({method:he.string(),params:he.unknown(),recordedAt:he.number()}),jy=he.object({sessionId:he.string(),lineageId:he.string(),upstreamSessionId:he.string().optional(),agentId:he.string(),cwd:he.string(),title:he.string().optional(),synopsis:Lr.optional(),summarizedThroughEntry:he.number().int().nonnegative().optional(),currentModel:he.string().optional(),currentMode:he.string().optional(),currentUsage:Ya.optional(),agentCommands:he.array(Ka).optional(),agentModes:he.array(Va).optional(),interactive:he.boolean().optional(),originatingClient:Qa.optional(),createdAt:he.string(),updatedAt:he.string()}),qy=he.object({version:he.literal(1),exportedAt:he.string(),exportedFrom:he.object({hydraVersion:he.string(),machine:he.string(),hydraHost:he.string().optional()}),session:jy,history:he.array(Uy),promptHistory:he.array(he.string()).optional(),toolBlobs:he.record(he.string()).optional()})});import{createHash as sw}from"crypto";function md(t){if(Array.isArray(t))return t.map(md);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=md(t[n]);return e}return t}function Zs(t){let e=JSON.stringify(md(t));return sw("sha256").update(e).digest("hex").slice(0,16)}var ui=V(()=>{"use strict";_e()});import hw from"strip-ansi";function ct(t){return hw(t).replace(gw,"")}function Ie(t){return ct(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function ds(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Sw(n);case"agent_thought_chunk":case"agent_thought":return kw(n);case"user_message_chunk":return xw(n);case"prompt_received":return Aw(n);case"tool_call":return Cw(n,e);case"tool_call_update":return Mw(n,e);case"plan":return Fw(n);case"current_mode_update":return Ow(n);case"current_model_update":return Lw(n);case"turn_complete":return Bw(n);case"usage_update":return Iw(n);case"available_commands_update":return bw(n);case"available_modes_update":return vw(n);case"session_info_update":return ww(n);case"config_option_update":return yw(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function yw(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.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}:{}})}n.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:n}}function ww(t){let e=Ee(t,"title"),n=e!==void 0?Ie(e):void 0,s=t._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s["hydra-acp"];if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i.agentId;typeof a=="string"&&(r=a)}}if(n===void 0&&r===void 0)return null;let o={kind:"session-info"};return n!==void 0&&(o.title=n),r!==void 0&&(o.agentId=r),o}function wi(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:Ie(r)};typeof s.description=="string"&&(o.description=Ie(s.description)),e.push(o)}return e}function bw(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:wi(e)}:null}function vw(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:Ie(r.id)};typeof r.name=="string"&&(o.name=Ie(r.name)),typeof r.description=="string"&&(o.description=Ie(r.description)),n.push(o)}return{kind:"available-modes",modes:n}}function Iw(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function Sw(t){let e=Vr(t.content);return e===null?null:{kind:"agent-text",text:e}}function kw(t){let e=typeof t.text=="string"?ct(t.text):Vr(t.content);return e===null?null:{kind:"agent-thought",text:e}}function xw(t){let e=t._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let n=Vr(t.content);return n===null?null:{kind:"user-text",text:n}}function Aw(t){let e=Nw(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Gu(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Yu(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function bi(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=Yu(r.oldText),i=Yu(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.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 n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Xu(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:ct(n)}function Cw(t,e={}){let n=Ee(t,"toolCallId")??Ee(t,"id");if(!n)return null;let s=Ee(t,"title")??Ee(t,"name")??Ee(t,"label")??"tool call",r=Ee(t,"name")??Ee(t,"title");if(Gu(r)){let f=Xu(t);if(f!==null){let u=Ee(t,"status"),p={kind:"exit-plan-mode",toolCallId:n,plan:f};return u!==void 0&&(p.status=u),p}}let o=ef(Ie(s),t,e),i=Ee(t,"status"),a=Ee(t,"kind"),d={kind:"tool-call",toolCallId:n,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=bi(t);c!==null&&(d.editDiff=c);let l=Zu(t);return l!==void 0&&(d.detail=l),d}function Zu(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.command=="string"&&n.command.trim().length>0){let o=Ie(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return Ew(o,Qu)}let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return Pw($e(Ie(s)),Qu)}function Tw(t){for(let e of Rw)if(t.startsWith(e))return!0;return!1}function ef(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return $e(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${t}`||i.endsWith(`/${t}`)||i===t))return $e(i)}if(Tw(t))return $e(`/${t}`);if(n.cwd&&n.cwd.length>0){let r=n.cwd.endsWith("/")?n.cwd.slice(0,-1):n.cwd;return $e(`${r}/${t}`)}return t}function Ew(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Pw(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function Mw(t,e={}){let n=Ee(t,"toolCallId")??Ee(t,"id");if(!n)return null;let s=Ee(t,"title"),r=s!==void 0?ef(Ie(s),t,e):void 0,o=Ee(t,"status"),i=bi(t),a=Zu(t);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let c=Ee(t,"name")??s;if(Gu(c)){let f={kind:"exit-plan-mode",toolCallId:n},u=Xu(t);return u!==null&&(f.plan=u),o!==void 0&&(f.status=o),f}let l={kind:"tool-call-update",toolCallId:n};if(r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a),o!==void 0&&(l.status=o),i!==null&&(l.editDiff=i),o==="failed"){let f=$w(t);f!==null&&(l.errorText=f),_w(t,f)&&(l.upstreamInterrupted=!0)}return l}function $w(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=Vr(s.content);if(o!==null&&o.length>0)return o}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return ct(s)}return null}function _w(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Fw(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?Ie(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),n.push(i)}return{kind:"plan",entries:n}}function Ow(t){let e=Ee(t,"currentModeId")??Ee(t,"currentMode")??Ee(t,"mode");return e?{kind:"mode-changed",mode:Ie(e)}:null}function Lw(t){let e=Ee(t,"currentModel")??Ee(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Ie(e),...s&&s.length>0?{availableModels:s}:{}}}function Bw(t){let e=Ee(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Vr(t){if(typeof t=="string")return ct(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ct(e.text):null}function Nw(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Vr(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Ee(t,e){let n=t[e];return typeof n=="string"?n:void 0}var gw,Qu,Rw,cs=V(()=>{"use strict";de();gw=/[\x00-\x08\x0b-\x1f\x7f]/g;Qu=64;Rw=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function vi(t){let e=Dw(t),n=Hw(e),s=[];Uw(s,t),jw(s,e,n);let r=s.join(`
|
|
48
|
+
`,{encoding:"utf8"}))}function Zo(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function dd(t,e,n=Au){if(e.length===0)return t;let s=new Set(t),r=t;for(let o of e){let i=o.replace(/\n+$/,"");i.length!==0&&(s.has(i)||(s.add(i),r=jr(r,i,n)))}return r}var Au,ei=V(()=>{"use strict";Au=500});import{z as he}from"zod";function qr(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function qt(t){return Wy.parse(t)}var jy,qy,Wy,os=V(()=>{"use strict";Xa();Ko();jy=he.object({method:he.string(),params:he.unknown(),recordedAt:he.number()}),qy=he.object({sessionId:he.string(),lineageId:he.string(),upstreamSessionId:he.string().optional(),agentId:he.string(),cwd:he.string(),title:he.string().optional(),synopsis:Lr.optional(),summarizedThroughEntry:he.number().int().nonnegative().optional(),currentModel:he.string().optional(),currentMode:he.string().optional(),currentUsage:Ya.optional(),agentCommands:he.array(Ka).optional(),agentModes:he.array(Va).optional(),interactive:he.boolean().optional(),originatingClient:Qa.optional(),createdAt:he.string(),updatedAt:he.string()}),Wy=he.object({version:he.literal(1),exportedAt:he.string(),exportedFrom:he.object({hydraVersion:he.string(),machine:he.string(),hydraHost:he.string().optional()}),session:qy,history:he.array(jy),promptHistory:he.array(he.string()).optional(),toolBlobs:he.record(he.string()).optional()})});import{createHash as rw}from"crypto";function md(t){if(Array.isArray(t))return t.map(md);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=md(t[n]);return e}return t}function Zs(t){let e=JSON.stringify(md(t));return rw("sha256").update(e).digest("hex").slice(0,16)}var ui=V(()=>{"use strict";_e()});import gw from"strip-ansi";function ct(t){return gw(t).replace(yw,"")}function Ie(t){return ct(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function as(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return kw(n);case"agent_thought_chunk":case"agent_thought":return xw(n);case"user_message_chunk":return Aw(n);case"prompt_received":return Cw(n);case"tool_call":return Rw(n,e);case"tool_call_update":return $w(n,e);case"plan":return Ow(n);case"current_mode_update":return Lw(n);case"current_model_update":return Bw(n);case"turn_complete":return Nw(n);case"usage_update":return Sw(n);case"available_commands_update":return vw(n);case"available_modes_update":return Iw(n);case"session_info_update":return bw(n);case"config_option_update":return ww(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function ww(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.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}:{}})}n.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:n}}function bw(t){let e=Ee(t,"title"),n=e!==void 0?Ie(e):void 0,s=t._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s["hydra-acp"];if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i.agentId;typeof a=="string"&&(r=a)}}if(n===void 0&&r===void 0)return null;let o={kind:"session-info"};return n!==void 0&&(o.title=n),r!==void 0&&(o.agentId=r),o}function wi(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:Ie(r)};typeof s.description=="string"&&(o.description=Ie(s.description)),e.push(o)}return e}function vw(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:wi(e)}:null}function Iw(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:Ie(r.id)};typeof r.name=="string"&&(o.name=Ie(r.name)),typeof r.description=="string"&&(o.description=Ie(r.description)),n.push(o)}return{kind:"available-modes",modes:n}}function Sw(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function kw(t){let e=Vr(t.content);return e===null?null:{kind:"agent-text",text:e}}function xw(t){let e=typeof t.text=="string"?ct(t.text):Vr(t.content);return e===null?null:{kind:"agent-thought",text:e}}function Aw(t){let e=t._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let n=Vr(t.content);return n===null?null:{kind:"user-text",text:n}}function Cw(t){let e=Dw(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Gu(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Yu(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function bi(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=Yu(r.oldText),i=Yu(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.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 n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Xu(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:ct(n)}function Rw(t,e={}){let n=Ee(t,"toolCallId")??Ee(t,"id");if(!n)return null;let s=Ee(t,"title")??Ee(t,"name")??Ee(t,"label")??"tool call",r=Ee(t,"name")??Ee(t,"title");if(Gu(r)){let f=Xu(t);if(f!==null){let u=Ee(t,"status"),p={kind:"exit-plan-mode",toolCallId:n,plan:f};return u!==void 0&&(p.status=u),p}}let o=ef(Ie(s),t,e),i=Ee(t,"status"),a=Ee(t,"kind"),d={kind:"tool-call",toolCallId:n,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=bi(t);c!==null&&(d.editDiff=c);let l=Zu(t);return l!==void 0&&(d.detail=l),d}function Zu(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.command=="string"&&n.command.trim().length>0){let o=Ie(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return Pw(o,Qu)}let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return Mw($e(Ie(s)),Qu)}function Ew(t){for(let e of Tw)if(t.startsWith(e))return!0;return!1}function ef(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return $e(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${t}`||i.endsWith(`/${t}`)||i===t))return $e(i)}if(Ew(t))return $e(`/${t}`);if(n.cwd&&n.cwd.length>0){let r=n.cwd.endsWith("/")?n.cwd.slice(0,-1):n.cwd;return $e(`${r}/${t}`)}return t}function Pw(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Mw(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function $w(t,e={}){let n=Ee(t,"toolCallId")??Ee(t,"id");if(!n)return null;let s=Ee(t,"title"),r=s!==void 0?ef(Ie(s),t,e):void 0,o=Ee(t,"status"),i=bi(t),a=Zu(t);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let c=Ee(t,"name")??s;if(Gu(c)){let f={kind:"exit-plan-mode",toolCallId:n},u=Xu(t);return u!==null&&(f.plan=u),o!==void 0&&(f.status=o),f}let l={kind:"tool-call-update",toolCallId:n};if(r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a),o!==void 0&&(l.status=o),i!==null&&(l.editDiff=i),o==="failed"){let f=_w(t);f!==null&&(l.errorText=f),Fw(t,f)&&(l.upstreamInterrupted=!0)}return l}function _w(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=Vr(s.content);if(o!==null&&o.length>0)return o}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return ct(s)}return null}function Fw(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Ow(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?Ie(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),n.push(i)}return{kind:"plan",entries:n}}function Lw(t){let e=Ee(t,"currentModeId")??Ee(t,"currentMode")??Ee(t,"mode");return e?{kind:"mode-changed",mode:Ie(e)}:null}function Bw(t){let e=Ee(t,"currentModel")??Ee(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Ie(e),...s&&s.length>0?{availableModels:s}:{}}}function Nw(t){let e=Ee(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Vr(t){if(typeof t=="string")return ct(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ct(e.text):null}function Dw(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Vr(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Ee(t,e){let n=t[e];return typeof n=="string"?n:void 0}var yw,Qu,Tw,ds=V(()=>{"use strict";de();yw=/[\x00-\x08\x0b-\x1f\x7f]/g;Qu=64;Tw=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function vi(t){let e=Hw(t),n=Uw(e),s=[];jw(s,t),qw(s,e,n);let r=s.join(`
|
|
49
49
|
`);return r.endsWith(`
|
|
50
50
|
`)||(r+=`
|
|
51
|
-
`),r}function
|
|
52
|
-
`)),t.push("")}function
|
|
53
|
-
`))t.push(`> ${
|
|
54
|
-
`);for(let f of l)t.push(`> _${
|
|
55
|
-
`),Mi(),await $i(t))}async function Xr(t){let n=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{return(await fetch(n,{signal:AbortSignal.timeout(500)})).ok}catch{return!1}}async function Pi(t,e=1e3){let s=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{let r=await fetch(s,{signal:AbortSignal.timeout(e)});if(!r.ok)return;let o=await r.json();return{version:typeof o.version=="string"?o.version:void 0,configDigest:typeof o.configDigest=="string"?o.configDigest:void 0}}catch{return}}function Mi(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");
|
|
51
|
+
`),r}function Hw(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=as(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Uw(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function jw(t,e){let n=e.session,s=Oe(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${cs(r)}`),t.push("");let o=[];o.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let i=[n.agentId];n.currentModel&&i.push(`model: ${n.currentModel}`),n.currentMode&&i.push(`mode: ${n.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${n.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${hd(a.size)}`:void 0;d.push(c?`${hd(a.used)} / ${c} tokens`:`${hd(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${c}`)}o.push(`- **Usage:** ${d.join(" \xB7 ")}`)}t.push(o.join(`
|
|
52
|
+
`)),t.push("")}function qw(t,e,n){if(!e.some(c=>Ww(c.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,o="",i=!1,a=()=>{o.length!==0&&(t.push(o.trimEnd()),t.push(""),o="")},d=()=>{i||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),i=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of c.text.split(`
|
|
53
|
+
`))t.push(`> ${cs(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),i=!0;break}case"agent-text":d(),o+=c.text;break;case"agent-thought":{d(),a();let l=c.text.split(`
|
|
54
|
+
`);for(let f of l)t.push(`> _${cs(f)}_`);t.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let l=n.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};t.push(`- ${Jw(l.status)} ${zw(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{d(),a(),t.push("**Plan:**"),t.push("");for(let l of c.entries){let f=l.status==="completed"?"[x]":"[ ]";t.push(`- ${f} ${cs(l.content)}`)}t.push("");break}case"mode-changed":d(),a(),t.push(`_mode: ${cs(c.mode)}_`),t.push("");break;case"model-changed":d(),a(),t.push(`_model: ${cs(c.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Ww(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function zw(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${cs(t.title)}${n}`}function Jw(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function cs(t){return t.replace(/</g,"<").replace(/>/g,">")}function hd(t){return t.toLocaleString("en-US")}var gd=V(()=>{"use strict";ds();tn()});function tr(t){let e=[],n=[],s=!1,r=o=>{if(!s){s=!0;for(let i of n)i(o)}};return t.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:0,error:{code:N.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),t.on("close",()=>r()),t.on("error",o=>r(o)),{async send(o){if(s)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{t.send(i,c=>{if(c){d(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){n.push(o)},async close(){s||(t.close(),r())}}}var xi=V(()=>{"use strict";dt()});import{spawn as jb}from"child_process";import{setTimeout as qb}from"timers/promises";async function nr(t){await Xr(t)||(process.stderr.write(`hydra-acp: daemon not running; starting it...
|
|
55
|
+
`),Mi(),await $i(t))}async function Xr(t){let n=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{return(await fetch(n,{signal:AbortSignal.timeout(500)})).ok}catch{return!1}}async function Pi(t,e=1e3){let s=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${t.daemon.port}/v1/health`;try{let r=await fetch(s,{signal:AbortSignal.timeout(e)});if(!r.ok)return;let o=await r.json();return{version:typeof o.version=="string"?o.version:void 0,configDigest:typeof o.configDigest=="string"?o.configDigest:void 0}}catch{return}}function Mi(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");jb(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function $i(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await Xr(t))return;await qb(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Zr=V(()=>{"use strict"});async function yn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await n(s.toString(),{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let o=await r.json();return Array.isArray(o.sessions)?o.sessions.map(i=>({sessionId:i.sessionId,cwd:i.cwd,updatedAt:i.updatedAt,attachedClients:i.attachedClients??0,status:i.status??"live",upstreamSessionId:i.upstreamSessionId,agentId:i.agentId,currentModel:i.currentModel,currentUsage:i.currentUsage,title:i.title,importedFromMachine:i.importedFromMachine,importedFromUpstreamSessionId:i.importedFromUpstreamSessionId,forkedFromSessionId:i.forkedFromSessionId,forkedFromMessageId:i.forkedFromMessageId,busy:i.busy,awaitingInput:i.awaitingInput,originatingClient:i.originatingClient,interactive:i.interactive})):[]}async function Uf(t,e=fetch){let n=await e(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(d=>d.installed==="yes"):[],o=0,i=0,a=0;for(let d of r)try{let c=await e(`${t.baseUrl}/v1/agents/${d.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});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 jf(t,e=fetch){let n=await e(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description})):[]}async function qf(t,e,n={},s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let o="";try{let i=await r.json();typeof i.error=="string"&&(o=`: ${i.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${o}`)}return await r.json()}async function Wf(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function zf(t,e,n,s=fetch){let r=await s(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})});if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Jf(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})});if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function Kf(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let o=await s(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`daemon returned HTTP ${o.status}`);return await o.json()}async function Vf(t,e,n=fetch){let s=await n(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function _i(t,e){let n=t.filter(o=>o.cwd===e);if(n.length===0)return null;let s=o=>o.status==="live"?1:0;return[...n].sort((o,i)=>{let a=s(i)-s(o);return a!==0?a:i.updatedAt.localeCompare(o.updatedAt)})[0]??null}var Fi=V(()=>{"use strict"});function xd(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Yf(t,e){let n=t??"?",s=xd(e);return s?`${n}${Vb}${s}`:n}function Qf(t){return t??"?"}function Gf(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Ad(e,n)}function Ad(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var Vb,Cd=V(()=>{"use strict";Vb="\u2022"});function Xf(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!Li.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Li.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function dr(t,e=Date.now()){return{session:Oe(t.sessionId),upstream:Qb(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:Gb(t.status,t.busy,t.awaitingInput),agent:Qf(t.agentId),model:xd(t.currentModel)??"-",age:Xb(t.updatedAt,e),title:t.title??"-",cwd:$e(t.cwd),cost:Gf(t.currentUsage)}}function Qb(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function Gb(t,e,n){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":"LIVE"}function cr(t,e={}){let n=e.columns??ir,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=Zb(ar[r],t.map(o=>o[r]));return s}function Xb(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let o=Math.floor(r/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 Zb(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Nn(t,e,n,s={}){let r=s.columns??ir,o=s.cwdMaxWidth??Yb,i=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((x,E)=>E===r.length-1?t[x]:i(x)).join(Oi);let a=r.map((b,x)=>({col:b,i:x})).filter(({col:b})=>Rd.has(b)),d=a.length>0?a[a.length-1].i:-1;if(d===-1){let b=r.map(i).join(Oi);return b.length>n?b.slice(0,n):b}let c=r.filter(b=>!Rd.has(b)).reduce((b,x)=>b+e[x],0),l=Math.max(0,r.length-1),f=n-c-l*Oi.length;f<0&&(f=0);let u=new Map,p=f;for(let{col:b,i:x}of a){if(x===d)continue;let E=b==="cwd"?Math.min(e[b],o):e[b],$=Math.min(E,Math.max(0,p-1));u.set(x,$),p=Math.max(0,p-$)}u.set(d,Math.max(0,p));let g=r.length-1,h=(b,x,E)=>{if(b==="cwd")return eo(t[b],x).padEnd(x);let $=ev(t[b],x);return E?$:$.padEnd(x)},v=r.map((b,x)=>Rd.has(b)?h(b,u.get(x)??0,x===g):i(b)).join(Oi);return v.length>n?v.slice(0,n):v}function ev(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function eo(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var Li,ir,Rd,ar,Oi,Yb,Bi=V(()=>{"use strict";Cd();de();tn();Li=["session","upstream","host","state","agent","model","age","cwd","title","cost"],ir=["session","state","age","cwd","title","agent","cost"],Rd=new Set(["cwd","title"]),ar={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Oi=" ",Yb=32});import*as $t from"fs/promises";import*as _t from"path";async function ep(t={}){let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=new URL(`${s}/v1/sessions`);(t.includeNonInteractive||t.all)&&r.searchParams.set("includeNonInteractive","true");let o=await fetch(r.toString(),{headers:{Authorization:`Bearer ${n}`}});o.ok||(process.stderr.write(`Daemon returned HTTP ${o.status}
|
|
56
56
|
`),process.exit(1));let i=await o.json(),a=i.sessions,d=t.host??"local",c=d==="all"?a:d==="local"?a.filter(b=>!b.importedFromMachine||!!b.upstreamSessionId):a.filter(b=>b.importedFromMachine===d&&!b.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(c,null,2)+`
|
|
57
57
|
`);return}if(c.length===0){if(d==="local"&&i.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
|
|
58
58
|
`);return}if(d!=="local"&&d!=="all"){process.stdout.write(`No sessions from ${d}.
|
|
59
59
|
`);return}process.stdout.write(`No active sessions.
|
|
60
|
-
`);return}let l=c.slice().sort((b,
|
|
61
|
-
`);for(let b of g)process.stdout.write(
|
|
60
|
+
`);return}let l=c.slice().sort((b,x)=>{let E=(x.status==="live"?1:0)-(b.status==="live"?1:0);return E!==0?E:String(x.updatedAt||"").localeCompare(String(b.updatedAt||""))}),f=l,u=0;if(!t.all){let b=l.filter(K=>K.status!=="cold").length,x=e.sessionListColdLimit,E=l.slice(b,b+x),$=l.length-b-E.length;f=[...l.slice(0,b),...E],u=$}let p=Date.now(),g=f.map(b=>dr(b,p)),h={columns:t.columns??e.tui.sessionColumns??ir,cwdMaxWidth:e.tui.cwdColumnMaxWidth},w=cr(g,h),v=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Nn(ar,w,v,h)+`
|
|
61
|
+
`);for(let b of g)process.stdout.write(Nn(b,w,v,h)+`
|
|
62
62
|
`);u>0&&process.stdout.write(`
|
|
63
63
|
... ${u} more cold session${u===1?"":"s"} hidden. Use --all to show.
|
|
64
64
|
`)}async function tp(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
|
|
@@ -70,32 +70,32 @@ Use empty arrays/strings where a field doesn't apply.`});import*as Qs from"fs/pr
|
|
|
70
70
|
`)}async function sp(t){let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=t.maxAgeDays!==void 0?t.maxAgeDays:0,o={maxAgeDays:r};t.limit!==void 0&&(o.limit=t.limit),o.selection=t.keepUndecided?"explicit":"unpromoted";let i=await fetch(`${s}/v1/sessions/collect`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(o)});i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
|
|
71
71
|
`),process.exit(1));let a=await i.json();if(t.json){process.stdout.write(`${JSON.stringify(a,null,2)}
|
|
72
72
|
`);return}let d=t.keepUndecided?"non-interactive":"unpromoted (cat one-shots + editor ghosts)";if(a.considered===0){let l=r>0?` older than ${r}d`:"";process.stdout.write(`No ${d} sessions${l} found.
|
|
73
|
-
`);return}let c=a.oldestLastUsedMs!==void 0?` (oldest: ${
|
|
73
|
+
`);return}let c=a.oldestLastUsedMs!==void 0?` (oldest: ${tv(Date.now()-a.oldestLastUsedMs)} ago)`:"";process.stdout.write(`Collected ${a.deleted} of ${a.considered} ${d} session(s)${c}.
|
|
74
74
|
`),a.failed>0&&process.stdout.write(` ${a.failed} failed (see daemon log).
|
|
75
75
|
`),a.deferred>0&&process.stdout.write(` ${a.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
|
|
76
|
-
`)}function
|
|
76
|
+
`)}function tv(t){let e=t/864e5;if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return n>=1?`${n.toFixed(n>=10?0:1)}h`:`${(t/(60*1e3)).toFixed(0)}m`}async function rp(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
|
|
77
77
|
`),process.exit(2));let s=await G(),r=await ce(),o=me(s.daemon.host,s.daemon.port,!!s.daemon.tls),i=n==="summary"?"?tools=summary":"",a=await fetch(`${o}/v1/sessions/${encodeURIComponent(t)}/export${i}`,{headers:{Authorization:`Bearer ${r}`}});if(!a.ok){let l=await a.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${a.status}: ${l}
|
|
78
78
|
`),process.exit(1)}let d=await a.text();if(!e){process.stdout.write(d),d.endsWith(`
|
|
79
79
|
`)||process.stdout.write(`
|
|
80
|
-
`);return}let c=e==="."?
|
|
80
|
+
`);return}let c=e==="."?av(a,t):e;await $t.mkdir(_t.dirname(_t.resolve(c)),{recursive:!0}),await $t.writeFile(c,d,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
|
|
81
81
|
`)}async function op(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
|
|
82
|
-
`),process.exit(2));let n,s,r=await
|
|
82
|
+
`),process.exit(2));let n,s,r=await nv(t);if(r!==null){let i=sv(r.raw);n=vi(i);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${_t.basename(t,_t.extname(t))}-${a}.md`}else{let i=await G(),a=await ce(),d=me(i.daemon.host,i.daemon.port,!!i.daemon.tls),c=await fetch(`${d}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${a}`}});if(!c.ok){let f=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${f}
|
|
83
83
|
`),process.exit(1)}n=await c.text();let l=new Date().toISOString().replace(/[:.]/g,"-");s=`hydra-${t}-${l}.md`}if(!e){process.stdout.write(n),n.endsWith(`
|
|
84
84
|
`)||process.stdout.write(`
|
|
85
85
|
`);return}let o=e==="."?s:e;await $t.mkdir(_t.dirname(_t.resolve(o)),{recursive:!0}),await $t.writeFile(o,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${o}
|
|
86
|
-
`)}async function
|
|
87
|
-
`),process.exit(1)}}function
|
|
86
|
+
`)}async function nv(t){try{if(!(await $t.stat(t)).isFile())return null}catch{return null}let e=await $t.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
|
|
87
|
+
`),process.exit(1)}}function sv(t){try{return qt(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
|
|
88
88
|
`),process.exit(1)}}async function ip(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
|
|
89
89
|
`),process.exit(2));let n;if(e.cwd!==void 0){let l=_t.resolve(e.cwd);try{(await $t.stat(l)).isDirectory()||(process.stderr.write(`--cwd ${l} is not a directory
|
|
90
90
|
`),process.exit(1))}catch{process.stderr.write(`--cwd ${l} does not exist
|
|
91
|
-
`),process.exit(1)}n=l}let s;t==="-"?s=await
|
|
92
|
-
`),process.exit(1)}if(e.info===!0){let l=await G();
|
|
91
|
+
`),process.exit(1)}n=l}let s;t==="-"?s=await iv():s=await $t.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(l){process.stderr.write(`Failed to parse bundle: ${l.message}
|
|
92
|
+
`),process.exit(1)}if(e.info===!0){let l=await G();ov(r,l.tui.cwdColumnMaxWidth);return}let o=await G(),i=await ce(),a=me(o.daemon.host,o.daemon.port,!!o.daemon.tls),d=await fetch(`${a}/v1/sessions/import`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}})});if(d.status===409){let l=await d.json().catch(()=>({}));process.stderr.write(`Bundle already imported as ${l.existingSessionId??"unknown"}. Use --replace to overwrite.
|
|
93
93
|
`),process.exit(1)}if(!d.ok){let l=await d.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${d.status}: ${l}
|
|
94
94
|
`),process.exit(1)}let c=await d.json();process.stdout.write(c.replaced?`Replaced ${c.sessionId} (from ${c.importedFromSessionId})
|
|
95
95
|
`:`Imported as ${c.sessionId} (from ${c.importedFromSessionId})
|
|
96
|
-
`)}function
|
|
97
|
-
`),process.exit(1)}let s=
|
|
98
|
-
`),process.stdout.write(
|
|
96
|
+
`)}function rv(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold"}}function ov(t,e){let n;try{n=qt(t)}catch(c){process.stderr.write(`Not a valid bundle: ${c.message}
|
|
97
|
+
`),process.exit(1)}let s=rv(n),r=dr(s),o={columns:Li,cwdMaxWidth:e},i=cr([r],o),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Nn(ar,i,a,o)+`
|
|
98
|
+
`),process.stdout.write(Nn(r,i,a,o)+`
|
|
99
99
|
`);let d=n.session.upstreamSessionId??"-";process.stdout.write(`
|
|
100
100
|
lineage: ${n.session.lineageId}
|
|
101
101
|
exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
|
|
@@ -103,156 +103,156 @@ origin session: ${n.session.sessionId}
|
|
|
103
103
|
origin upstream: ${d}
|
|
104
104
|
history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
|
|
105
105
|
`:`
|
|
106
|
-
`))}async function
|
|
107
|
-
`),process.exit(1)),s=u.sessionId}let{host:r,port:o,isFallback:i}=
|
|
106
|
+
`))}async function iv(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function av(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}function me(t,e,n){return`${n?"https":"http"}://${t}:${e}`}async function ap(t,e={}){let n=await G(),s;if(t!==void 0&&t.length>0)s=t;else{let c=await Qt(n),l=e.cwd?_t.resolve(e.cwd):process.cwd(),f=await yn(c,{cwd:l,all:!0}),u=_i(f,l);u||(process.stderr.write(`No sessions found for ${l}.
|
|
107
|
+
`),process.exit(1)),s=u.sessionId}let{host:r,port:o,isFallback:i}=dv(e.host,n),a=Oe(s),d=el({host:r,port:o,sessionId:a});process.stdout.write(d+`
|
|
108
108
|
`),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.
|
|
109
|
-
`)}function
|
|
110
|
-
`)});let d=new
|
|
111
|
-
`)});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
|
|
112
|
-
`),l=!1,f="",u=[],p=o!==" ",g=(v,b,
|
|
113
|
-
`),{language:t,theme:
|
|
109
|
+
`)}function dv(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Zf(t,443);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Zf(e.daemon.publicHost,443);return{host:n,port:s,isFallback:!1}}return mn(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 Zf(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),o=t.slice(s+1);if(o.startsWith(":")){let i=Number(o.slice(1));return{host:r,port:Number.isInteger(i)&&i>0?i:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}var Dn=V(()=>{"use strict";_e();wt();Hs();_r();tn();Fi();os();gd();Bi()});function Ni(t){let e=new Map,n=new Map;for(let r of t){let i=r.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=lv(i);if(c.length===0)continue;let l=c;if(d!==void 0){let f=e.get(d)??[],u=[];for(let p of c)f.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(d,[...f,...u]),l=u}for(let f of l)cv(n,f)}let s=[];for(let[r,o]of n)s.push({path:r,hunks:o.hunks,created:o.created});return s}function Di(t){let e=[];for(let n of t){let s=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===n.oldText){s=o;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function cv(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function lv(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=n,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,f=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||f===void 0||e.push({path:i,oldText:l,newText:f})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let o of s){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 r=bi(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Td=V(()=>{"use strict";ds()});import{spawn as uv}from"child_process";import{Writable as fv}from"stream";function Hi(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=pv(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??uv,o={...n};o.LESS===void 0&&(o.LESS="FRX");let i=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:o}),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}
|
|
110
|
+
`)});let d=new fv({write(l,f,u){if(!a.writable){u();return}a.write(l,g=>{if(g&&g.code!=="EPIPE"){u(g);return}u()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});d.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
|
|
111
|
+
`)});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 pv(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var Ed=V(()=>{"use strict"});import mv from"chalk";import{highlight as hv,supportsLanguage as gv}from"cli-highlight";import ji from"string-width";function lr(t,e={}){switch(t.kind){case"user-text":{let n=Pd(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return Pd(t.text," ","agent");case"agent-thought":return Pd(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return Lv(t,e.maxPlanItems??Fv);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function to(t,e){let n=e?.codeOpen??"^C",s=e?.boldReset??"^:",r=e?.codeReset??"^:",o=t.replace(/\^/g,"^^");return o=o.replace(/\*\*(.+?)\*\*/g,`^+$1${s}`),o=o.replace(/`([^`]+)`/g,`${n}$1${r}`),o}function cp(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function lp(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:o=" ",inlineOpts:i,maxWidth:a}=e,d=[],c=t.replace(/^\s+/,"").split(`
|
|
112
|
+
`),l=!1,f="",u=[],p=o!==" ",g=(v,b,x=" ")=>{let E={prefix:x,body:v,bodyStyle:b};r!==void 0&&(E.prefixStyle=r),d.push(E)},h=()=>p?(p=!1,o):" ",w=()=>{if(u.length!==0){if(s){let v=Cv(f,u);for(let b of v){let x={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(x.prefixStyle=r),b.ansi&&(x.ansi=!0),d.push(x)}}else for(let v of u)g(v.replace(/\^/g,"^^"),n);u=[],f=""}};for(let v=0;v<c.length;v++){let b=c[v],x=b.match(/^\s*```\s*(\w*)\s*$/);if(x){l?(w(),l=!1):(l=!0,f=x[1]??"");continue}if(l){u.push(b);continue}let E=b.match(/^(#{1,6})\s+(.*)$/);if(E){let D=E[1].length,_=E[2]??"",H=s?D===1?"heading-1":D===2?"heading-2":"heading-3":n,q=s?cp(H):i;g(to(_,q),H,h());continue}let $=c[v+1];if(b.includes("|")&&$!==void 0&&yv($)&&no(b).length===no($).length){let D=no(b),_=[],H=v+2;for(;H<c.length&&c[H].includes("|");)_.push(no(c[H])),H++;let q=xv(D,_,a);for(let z of q)r!==void 0&&(z.prefixStyle=r),d.push(z);v=H-1;continue}let K=b.match(/^(\s*)[-*+]\s+(.*)$/);if(K){let D=K[1]??"",_=K[2]??"";g(`${D}\u2022 ${to(_,i)}`,n,h());continue}let te=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(te){let D=te[1]??"",_=te[2]??"",H=te[3]??"";g(`${D}${_}. ${to(H,i)}`,n,h());continue}let J=b.trim()==="";g(to(b,i),n,J?" ":h())}return l&&w(),d}function ur(t,e){return lp(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Md(t){return lp(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function no(t){let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())}function yv(t){if(!t.includes("|"))return!1;let e=no(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Ui(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return ji(e)}function vv(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let i=n;for(;i<t.length&&(t[i]===" "||t[i]===" ");)i++;let a=t.slice(n,i);e.push({text:a,isWS:!0,width:ji(a)}),n=i;continue}let r="",o=n;for(;o<t.length;){let i=t[o];if(i===" "||i===" ")break;if(t[o]==="*"&&t[o+1]==="*"){let a=t.indexOf("**",o+2);a===-1?(r+="**",o+=2):(r+=t.slice(o,a+2),o=a+2);continue}if(i==="`"){let a=t.indexOf("`",o+1);a===-1?(r+="`",o+=1):(r+=t.slice(o,a+1),o=a+1);continue}r+=i,o+=1}e.push({text:r,isWS:!1,width:Ui(r)}),n=o}return e}function Iv(t,e){let n=[],s="",r=0;for(let o of t){let i=ji(o);r>0&&r+i>e?(n.push(s),s=o,r=i):(s+=o,r+=i)}return s.length>0&&n.push(s),n}function Sv(t,e){if(e<=0)return t.length===0?[""]:[t.map(i=>i.text).join("")];let n=[],s="",r=0,o=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let i of t){if(i.isWS){if(r===0)continue;s+=i.text,r+=i.width;continue}if(i.width>e){if(r>0&&o(),i.text.includes("**")||i.text.includes("`"))n.push(i.text);else{let d=Iv(i.text,e);for(let l=0;l<d.length-1;l++)n.push(d[l]);let c=d[d.length-1]??"";s=c,r=ji(c)}continue}if(r===0){s=i.text,r=i.width;continue}r+i.width>e?(o(),s=i.text,r=i.width):(s+=i.text,r+=i.width)}return(s.length>0||n.length===0)&&o(),n}function kv(t,e){let n=t.length;if(t.reduce((l,f)=>l+f,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,up)),o=r.reduce((l,f)=>l+f,0);if(o>=e)return r;let i=e-o,a=t.map((l,f)=>({i:f,slack:Math.max(0,l-r[f])})).filter(l=>l.slack>0),d=a.reduce((l,f)=>l+f.slack,0);if(d===0)return r;for(let l of a){let f=Math.floor(i*l.slack/d);r[l.i]=r[l.i]+Math.min(f,l.slack)}o=r.reduce((l,f)=>l+f,0);let c=e-o;for(;c>0;){let l=-1,f=0;for(let u=0;u<n;u++){let p=t[u]-r[u];p>f&&(f=p,l=u)}if(l<0)break;r[l]=r[l]+1,c--}return r}function xv(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let c=0;c<s;c++)r[c]=Ui(t[c]??"");for(let c of e)for(let l=0;l<s;l++){let f=c[l]??"",u=Ui(f);u>r[l]&&(r[l]=u)}let o=r.slice();if(n!==void 0){let c=Math.max(s*up,n-wv-(s-1)*bv);o=kv(r,c)}let i=(c,l,f)=>{let u=[],p=1;for(let h=0;h<s;h++){let w=c[h]??"",v=o[h],b=Sv(vv(w),v);u.push(b),b.length>p&&(p=b.length)}let g=[];for(let h=0;h<p;h++){let w=[];for(let v=0;v<s;v++){let b=u[v][h]??"",x=o[v],E=Ui(b),$=to(b,f);w.push($+" ".repeat(Math.max(0,x-E)))}g.push({prefix:" ",body:w.join(" \u2502 "),bodyStyle:l})}return g},a=[];a.push(...i(t,"heading-3",cp("heading-3")));let d=[];for(let c=0;c<s;c++)d.push("\u2500".repeat(o[c]));a.push({prefix:" ",body:d.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let c of e)a.push(...i(c,"agent"));return a}function Cv(t,e){if(t.length===0||!gv(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=hv(e.join(`
|
|
113
|
+
`),{language:t,theme:Av,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
|
|
114
114
|
`);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,o)=>({body:r,ansi:r!==e[o]}))}function Pd(t,e,n,s,r,o){let i=t.replace(/^\s+/,"").split(`
|
|
115
|
-
`),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let d of i){let c={prefix:e,prefixStyle:s??n,body:d,bodyStyle:n};o&&(c.fillRow=!0),a.push(c)}return a}function
|
|
115
|
+
`),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let d of i){let c={prefix:e,prefixStyle:s??n,body:d,bodyStyle:n};o&&(c.fillRow=!0),a.push(c)}return a}function Rv(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function sn(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),o=n%60;return o===0?`${r}h`:`${r}h ${o}m`}function fp(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),o=s.toLowerCase(),i;if(s===n||o.includes(r)?i=s:r.includes(o)?i=n:i=`${n} \xB7 ${s}`,t.detail){let d=t.detail,c=i.toLowerCase(),l=d.toLowerCase();(l.startsWith(`${c} `)||l.startsWith(`${c} `))&&(d=d.slice(i.length).trimStart()),d.length>0&&!i.includes(d)&&(i=`${i} \xB7 ${d}`)}if(t.startedAt!==void 0){let d=t.endedAt??e;i=`${i} \xB7 ${sn(d-t.startedAt)}`}let a=[{prefix:` ${Mv(t.status)} `,prefixStyle:$v(t.status),body:i,bodyStyle:Bv(t.status)}];return t.status==="failed"&&t.errorText&&a.push({prefix:" ",body:Ie(t.errorText),bodyStyle:"tool-status-fail"}),a}function mp(t){pp=t>=0?t:0}function $d(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,o;if(r){let c=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);o=` (~${Rv(c)})`}else{let c=Ev(t),l=[];c.added>0&&l.push(`+${c.added}`),c.removed>0&&l.push(`-${c.removed}`),o=l.length>0?` (${l.join(" ")})`:""}let i=c=>({prefix:" ",body:`${c?"\u25BE":"\u25B8"} Edited ${Ie($e(t.path))}${o}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(i(!1)),s;if(r)return t.path&&(s.push(i(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=_d(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(i(!1)),s;t.path&&s.push(i(!0));let d="```diff\n"+a+"\n```";return s.push(...ur(d)),s.length>0&&s.unshift({body:""}),s}function hp(t){let e=ct(t.oldText).split(`
|
|
116
116
|
`),n=ct(t.newText).split(`
|
|
117
|
-
`);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function
|
|
118
|
-
`)}function
|
|
117
|
+
`);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function Ev(t){let{oldLines:e,newLines:n}=hp(t),s=0,r=0;for(let o of gp(e,n))o.op==="+"?s++:o.op==="-"&&r++;return{added:s,removed:r}}function dp(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function _d(t,e={}){let n=e.maxLines??Tv,s=e.contextLines??pp,{oldLines:r,newLines:o}=hp(t),i=gp(r,o),a=[];if(Number.isFinite(s)){if(!i.some(u=>u.op!=="="))return"";let l=new Array(i.length).fill(!1);for(let u=0;u<i.length;u++)if(i[u].op!=="="){let p=Math.max(0,u-s),g=Math.min(i.length-1,u+s);for(let h=p;h<=g;h++)l[h]=!0}let f=0;for(;f<i.length;){if(l[f]){a.push(dp(i[f])),f++;continue}let u=f;for(;u<i.length&&!l[u];)u++;let p=u-f;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),f=u}}else for(let c of i)a.push(dp(c));let d=[];for(let c=0;c<a.length;c++){if(d.length>=n-1&&c<a.length-1){let f=a.length-c;d.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}d.push(a[c])}return d.join(`
|
|
118
|
+
`)}function gp(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,o=e.length;for(;r>n&&o>n&&t[r-1]===e[o-1];)r--,o--;let i=[];for(let a=0;a<n;a++)i.push({op:"=",text:t[a]});i.push(...Pv(t.slice(n,r),e.slice(n,o)));for(let a=r;a<t.length;a++)i.push({op:"=",text:t[a]});return i}function Pv(t,e){let n=t.length,s=e.length;if(n===0||s===0){let d=[];for(let c of t)d.push({op:"-",text:c});for(let c of e)d.push({op:"+",text:c});return d}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let d=n-1;d>=0;d--)for(let c=s-1;c>=0;c--)t[d]===e[c]?r[d][c]=r[d+1][c+1]+1:r[d][c]=Math.max(r[d+1][c],r[d][c+1]);let o=[],i=0,a=0;for(;i<n&&a<s;)t[i]===e[a]?(o.push({op:"=",text:t[i]}),i++,a++):r[i+1][a]>=r[i][a+1]?(o.push({op:"-",text:t[i]}),i++):(o.push({op:"+",text:e[a]}),a++);for(;i<n;)o.push({op:"-",text:t[i]}),i++;for(;a<s;)o.push({op:"+",text:e[a]}),a++;return o}function yp(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function Mv(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function $v(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function wp(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...ur(t.plan));let n=t.status;if(n!==void 0){let s=_v(n);s!==null&&e.push(s)}return e}function _v(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function Ov(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(c=>(c.status??"pending")==="in_progress"),r=t.findIndex(c=>(c.status??"pending")==="pending"),o=s>=0?s:r>=0?r:n-1,i=Math.floor((e-1)/2),a=Math.max(0,o-i),d=Math.min(n,a+e);return d-a<e&&(a=Math.max(0,d-e)),{start:a,end:d}}function Lv(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",i=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:d,end:c}=Ov(t.entries,e),l=c-d<a,f="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let g=a-p;f=g===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${g} left`}let u=[{prefix:"\u25A3 ",prefixStyle:i,body:f,bodyStyle:i}];for(let p=d;p<c;p++){let g=t.entries[p];if(!g)continue;let h=g.status??"pending",w=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",v=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=g.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,"");u.push({prefix:" ",body:`${w} ${b}`,bodyStyle:v})}return u}function Bv(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var up,wv,bv,Pe,Av,Tv,pp,Fv,so=V(()=>{"use strict";de();ds();up=6,wv=2,bv=3;Pe=new mv.Instance({level:3}),Av={keyword:Pe.blueBright,built_in:Pe.cyan,type:Pe.cyanBright,literal:Pe.blue,number:Pe.greenBright,string:Pe.yellow,regexp:Pe.red,comment:Pe.gray,function:Pe.yellow,title:Pe.yellow,class:Pe.yellowBright,attr:Pe.cyan,attribute:Pe.cyan,variable:Pe.white,params:Pe.white,meta:Pe.magenta,symbol:Pe.magenta,addition:Pe.greenBright,deletion:Pe.redBright,section:Pe.cyan,tag:Pe.cyan,name:Pe.cyanBright};Tv=40,pp=Number.POSITIVE_INFINITY;Fv=5});import{highlight as Nv,supportsLanguage as Dv}from"cli-highlight";async function vp(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
|
|
119
119
|
`),process.exit(2));let n=await G(),s=await ce(),r=me(n.daemon.host,n.daemon.port,!!n.daemon.tls),o=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let p=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${p}
|
|
120
120
|
`),process.exit(1)}let i=await o.json(),a;try{a=qt(i)}catch(p){process.stderr.write(`Failed to decode session bundle: ${p.message}
|
|
121
121
|
`),process.exit(1)}let d=Ni(a.history),c=e.fold===!0?d.map(p=>({...p,hunks:Di(p.hunks)})):d;if(e.json){process.stdout.write(JSON.stringify(c,null,2)+`
|
|
122
|
-
`);return}let l=Hi({disabled:e.noPager===!0}),f=process.stdout.isTTY===!0,u=!e.noColor&&f;l.stream.write(
|
|
123
|
-
`;let n=[],s=[...t].sort((r,o)=>r.path.localeCompare(o.path));for(let r of s){let o=
|
|
124
|
-
`:n.join("")}function
|
|
125
|
-
`))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function
|
|
122
|
+
`);return}let l=Hi({disabled:e.noPager===!0}),f=process.stdout.isTTY===!0,u=!e.noColor&&f;l.stream.write(Fd(c,u)),await l.flush()}function Fd(t,e){if(t.length===0)return`No file edits found in this session.
|
|
123
|
+
`;let n=[],s=[...t].sort((r,o)=>r.path.localeCompare(o.path));for(let r of s){let o=jv(r,e);o!==null&&n.push(o)}return n.length===0?`No file edits found in this session.
|
|
124
|
+
`:n.join("")}function Hv(t){let e=[];for(let n of t.hunks){let s=_d(n,{maxLines:1/0});Uv(s)&&e.push({body:s,oldCount:bp(n.oldText),newCount:bp(n.newText)})}return e}function Uv(t){if(t.length===0)return!1;for(let e of t.split(`
|
|
125
|
+
`))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function jv(t,e){let n=Hv(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((i,a)=>{let d=i.oldCount===0?0:1,c=i.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${d},${i.oldCount} +${c},${i.newCount} @@${l}`),s.push(i.body)});let o=s.join(`
|
|
126
126
|
`)+`
|
|
127
127
|
|
|
128
|
-
`;return!e||!
|
|
129
|
-
`);return e[e.length-1]===""&&e.pop(),e.length}var
|
|
128
|
+
`;return!e||!Dv("diff")?o:Nv(o,{language:"diff"})}function bp(t){if(t.length===0)return 0;let e=t.split(`
|
|
129
|
+
`);return e[e.length-1]===""&&e.pop(),e.length}var Od=V(()=>{"use strict";_e();wt();os();Td();so();Ed();Dn()});import*as UT from"fs/promises";async function Ip(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
|
|
130
130
|
`),process.exit(2));let n=await G(),s=await ce(),r=me(n.daemon.host,n.daemon.port,!!n.daemon.tls),o=await fetch(`${r}/v1/sessions`,{headers:{Authorization:`Bearer ${s}`}});o.ok||(process.stderr.write(`Daemon returned HTTP ${o.status}
|
|
131
131
|
`),process.exit(1));let a=(await o.json()).sessions.find(w=>w.sessionId===t)?.status,d=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export`,{headers:{Authorization:`Bearer ${s}`}});if(!d.ok){let w=await d.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${d.status}: ${w}
|
|
132
132
|
`),process.exit(1)}let c=await d.json(),l;try{l=qt(c)}catch(w){process.stderr.write(`Failed to decode session bundle: ${w.message}
|
|
133
|
-
`),process.exit(1)}let f=
|
|
133
|
+
`),process.exit(1)}let f=Nd(l,a??"cold"),u=e.diff===!0,p=null;if(u){let w=Ni(l.history);p=e.fold===!0?w.map(v=>({...v,hunks:Di(v.hunks)})):w}if(e.json){let w={...f};p!==null&&(w.diff=p),process.stdout.write(JSON.stringify(w,null,2)+`
|
|
134
134
|
`);return}let g=process.stdout.isTTY===!0,h=!e.noColor&&g;if(u){let w=Hi({disabled:e.noPager===!0});w.stream.write(qi(f,e.verbose===!0)),w.stream.write(`
|
|
135
|
-
`),w.stream.write(
|
|
135
|
+
`),w.stream.write(Fd(p??[],h)),await w.flush();return}process.stdout.write(qi(f,e.verbose===!0))}function Nd(t,e){let n=t.session,s=t.history,r=gu(s),o=Za(s),i=ed(s),a=n.currentUsage,d=Date.parse(n.createdAt),c=Date.parse(n.updatedAt),l=Number.isFinite(d)&&Number.isFinite(c)?c-d:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:o,files:i,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function qi(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${Wv(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let o=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";o.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";o.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),o.push(a.join(" / "))}if(o.length>0&&n.push(`${s("Cost:")}${o.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",d=c=>c.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${d("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${d("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${d("Rejected approaches:")}`);for(let c of t.synopsis.rejected_approaches)n.push(`${a} - ${c}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${d("Open threads:")}`);for(let c of t.synopsis.open_threads)n.push(`${a} - ${c}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,f)=>l+f.count,0);n.push(`Tools (${a} calls):`);let d=e?t.tools:t.tools.slice(0,Ld),c=Math.max(...d.map(l=>l.name.length),4);for(let l of d)n.push(` ${l.name.padEnd(c)} ${l.count}`);!e&&t.tools.length>Ld&&n.push(` ... ${t.tools.length-Ld} more (use --verbose to see all)`)}let i=e?t.files:t.files.map(a=>{let d=a.byTool.filter(l=>qv.has(l.name)),c=d.reduce((l,f)=>l+f.count,0);return{path:a.path,count:c,byTool:d}}).filter(a=>a.count>0);if(i.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${i.length}):`);let d=e?i:i.slice(0,Bd),c=Math.max(...d.map(l=>l.path.length),4);for(let l of d)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(c)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(c)} ${l.count}`);!e&&i.length>Bd&&n.push(` ... ${i.length-Bd} more (use --verbose to see all)`)}return n.join(`
|
|
136
136
|
`)+`
|
|
137
|
-
`}function
|
|
138
|
-
`)}}});function
|
|
139
|
-
`).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(
|
|
140
|
-
`)}expandPastes(e){return e.replace(
|
|
137
|
+
`}function Wv(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),o=e%60,i=[];return n>0&&i.push(`${n}d`),s>0&&i.push(`${s}h`),r>0&&i.push(`${r}m`),(i.length===0||o>0)&&i.push(`${o}s`),i.join(" ")}var Ld,Bd,qv,Dd=V(()=>{"use strict";_e();wt();os();td();Td();Ed();Od();Dn();Ld=10,Bd=15,qv=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});import{setTimeout as tI}from"timers/promises";import{WebSocket as nI}from"ws";function aI(t){return!("method"in t)&&"id"in t&&t.id!==void 0}async function dI(t,e){return new Promise((n,s)=>{let r=new nI(t,e),o=()=>{r.off("error",i),n(tr(r))},i=a=>{r.off("open",o),s(a)};r.once("open",o),r.once("error",i)})}var sI,rI,oI,iI,mr,Jd=V(()=>{"use strict";xi();dt();sI=200,rI=5e3,oI=2,iI=60,mr=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];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.outboundQueue.push(e);return}try{await this.current.send(e)}catch(n){this.outboundQueue.push(e),this.scheduleReconnect(n)}}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let n=e.id,s=new Promise((r,o)=>{this.pendingRequests.set(n,{resolve:r,reject:o})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){this.destroyed=!0,this.current&&await this.current.close().catch(()=>{});for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=sI;for(;!this.destroyed;)try{let s=await dI(this.opts.url,this.opts.subprotocols);this.bindStream(s);let r=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(r)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=iI)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await tI(n),n=Math.min(n*oI,rI)}}bindStream(e){this.current=e,e.onMessage(n=>{if(aI(n)){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}async flushQueue(){if(!this.current)return;let e=this.outboundQueue;this.outboundQueue=[];for(let n of e)try{await this.current.send(n)}catch(s){this.outboundQueue.unshift(n),this.scheduleReconnect(s);return}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
|
|
138
|
+
`)}}});function nm(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let r of e){let o=n.find(i=>typeof i=="object"&&i!==null&&i.kind===r&&typeof i.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let s=n.find(r=>typeof r=="object"&&r!==null&&typeof r.optionId=="string");if(s?.optionId!==void 0)return s.optionId}return e[0]??"allow"}function ls(t){return{outcome:{outcome:"selected",optionId:nm(t,["allow_once","allow_always"])}}}function sm(t){return{outcome:{outcome:"selected",optionId:nm(t,["reject_once","reject_always"])}}}function Vi(t){return t&&typeof t=="object"?t:void 0}function ro(t){return typeof t=="string"&&t.length>0?t:void 0}function rm(t){let e=Vi(t),n=Vi(e?.toolCall),s={paths:[]};if(!n)return s;let r=ro(n.kind);r&&(s.kind=r);let o=new Set,i=c=>{let l=ro(c);l&&!o.has(l)&&(o.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let c of a)i(Vi(c)?.path);let d=Vi(n.rawInput);if(d){i(d.file_path),i(d.filePath),i(d.path);let c=ro(d.command);c&&(s.command=c);let l=ro(d.url);l&&(s.url=l);let f=ro(d.description);f&&(s.description=f)}return s}function om(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var Yi=V(()=>{"use strict"});function aS(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function mm(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),o=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o)?null:[s,r,o]}function dS(t,e){let n=mm(t),s=mm(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let o=n[r],i=s[r];if(o>i)return!0;if(o<i)return!1}return!1}async function oo(){if(Un!==void 0)return Un;if(aS())return Un=null,Un;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:hm,version:le}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&dS(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Un={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Un=null}}catch{Un=null}return Un}function io(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${hm}`}var hm,Un,Yd=V(()=>{"use strict";jt();hm="@hydra-acp/cli"});import*as ao from"fs/promises";import*as Qd from"path";async function co(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Qd.resolve(Ht(e)),s;try{s=await ao.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function gm(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await ao.stat(r)).isDirectory())return r}catch{}return null}async function ym(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let o=Qd.resolve(Ht(r)),i;try{i=(await ao.readdir(o,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),d=i.filter(c=>c.name.startsWith(s)).filter(c=>a||!c.name.startsWith(".")).map(c=>c.isDir?`${c.name}/`:c.name).sort();return{prefix:n,basePrefix:s,matches:d}}var Gd=V(()=>{"use strict";_e()});function lS(t,e){return`[pasted #${t} +${e} lines]`}var cS,Zi,Xd,bn,Zd=V(()=>{"use strict";cS=/\[pasted #(\d+) \+\d+ lines\]/g,Zi=/\[pasted #(\d+) \+\d+ lines\]$/,Xd=/^\[pasted #(\d+) \+\d+ lines\]/;bn=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;constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return{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.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||this.attachments.splice(e,1)}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){let r=this.currentLine(),o=Math.max(0,Math.min(e,r.length)),i=Math.max(o,Math.min(n,r.length));this.setCurrentLine(r.slice(0,o)+s+r.slice(i)),this.col=o+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n]}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.insertChar(e.ch),[];if(e.type==="paste"){let n=e.text.split(`
|
|
139
|
+
`).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(lS(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.insertNewline(),[];case"shift-tab":return this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.moveLeft(),[];case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"backspace":return this.backspace(),[];case"delete":return this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.yank(),[];case"escape":return this.turnRunning?[{type:"cancel",prefill:!0}]:[]}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
|
|
140
|
+
`)}expandPastes(e){return e.replace(cS,(n,s)=>{let r=parseInt(s,10),o=this.pastes.get(r);return o!==void 0?o:n})}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=[]}insertChar(e){if(e.length===0)return;if(e.includes(`
|
|
141
141
|
`)){this.insertText(e);return}let n=this.currentLine();this.setCurrentLine(n.slice(0,this.col)+e+n.slice(this.col)),this.col+=e.length}insertText(e){let n=e.split(`
|
|
142
|
-
`);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),o=s.slice(this.col),i=n[0]??"",a=n[n.length-1]??"",d=n.slice(1,-1);this.setCurrentLine(r+i);let c=[...d,a+o];this.buffer.splice(this.row+1,0,...c),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),o=s.slice(0,this.col).match(Zi);if(o!==null){this.pastes.delete(parseInt(o[1],10)),this.setCurrentLine(s.slice(0,this.col-o[0].length)+s.slice(this.col)),this.col-=o[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(
|
|
142
|
+
`);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),o=s.slice(this.col),i=n[0]??"",a=n[n.length-1]??"",d=n.slice(1,-1);this.setCurrentLine(r+i);let c=[...d,a+o];this.buffer.splice(this.row+1,0,...c),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),o=s.slice(0,this.col).match(Zi);if(o!==null){this.pastes.delete(parseInt(o[1],10)),this.setCurrentLine(s.slice(0,this.col-o[0].length)+s.slice(this.col)),this.col-=o[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(Xd);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
|
|
143
143
|
`,this.buffer.splice(this.row,1),this.row-=1,this.col=this.currentLine().length;return}let e=this.buffer[this.row-1]??"";this.killBuffer=e+`
|
|
144
144
|
`,this.buffer.splice(this.row-1,1),this.row-=1}killToEnd(){let e=this.currentLine();if(this.col<e.length){this.killBuffer=e.slice(this.col),this.setCurrentLine(e.slice(0,this.col));return}if(this.row>=this.buffer.length-1)return;if(e.length===0){this.killBuffer=`
|
|
145
145
|
`,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
|
|
146
|
-
`+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(Zi);if(s!==null){this.killBuffer=s[0];let i=this.col-s[0].length;this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let o=e.slice(r,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(Zi);if(n!==null){this.col-=n[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(
|
|
147
|
-
`),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:o}]:[{type:"queue-edit",index:o,text:n,displayText:e,attachments:i}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=this.planMode,a=[...this.attachments],d=n.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{type:"queue-remove",index:o}]:[{type:"queue-remove",index:o},{type:"amend",text:n,displayText:e,planMode:i,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});import
|
|
148
|
-
`)}function Rm(t){Cm=t}function
|
|
149
|
-
`);return e===-1?t:`${t.slice(0,e)} \u21B5`}function
|
|
146
|
+
`+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(Zi);if(s!==null){this.killBuffer=s[0];let i=this.col-s[0].length;this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let o=e.slice(r,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(Zi);if(n!==null){this.col-=n[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(Xd);if(s!==null){this.col+=s[0].length;return}this.col+=1;return}this.row<this.buffer.length-1&&(this.row+=1,this.col=0)}moveWordBackward(){if(this.col===0){if(this.row===0)return;this.row-=1,this.col=this.currentLine().length;return}let e=this.currentLine(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(Zi);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}moveWordForward(){let e=this.currentLine();if(this.col>=e.length){if(this.row>=this.buffer.length-1)return;this.row+=1,this.col=0;return}let n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(Xd);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}handleUp(){return this.row>0?(this.row-=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.queueIndex===-1&&this.historyIndex===-1?this.queue.length===0&&this.history.length===0?[]:(this.savedDraft={buffer:[...this.buffer],row:this.row,col:this.col},this.savedAttachments=[...this.attachments],this.attachments=[],this.queue.length>0?(this.queueIndex=this.queue.length-1,this.loadEntry(this.queue[this.queueIndex]??"")):(this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??"")),[]):this.queueIndex>=0?this.queueIndex>0?(this.queueIndex-=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):this.history.length===0?[]:(this.queueIndex=-1,this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex>0&&(this.historyIndex-=1,this.loadEntry(this.history[this.historyIndex]??"")),[])}handleDown(){return this.row<this.buffer.length-1&&this.historyIndex===-1&&this.queueIndex===-1?(this.row+=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.historyIndex>=0?this.historyIndex<this.history.length-1?(this.historyIndex+=1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex=-1,this.queue.length>0?(this.queueIndex=0,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.restoreDraft(),[])):this.queueIndex>=0?this.queueIndex<this.queue.length-1?(this.queueIndex+=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.queueIndex=-1,this.restoreDraft(),[]):[]}restoreDraft(){this.savedDraft?(this.buffer=[...this.savedDraft.buffer],this.row=this.savedDraft.row,this.col=this.savedDraft.col,this.savedDraft=null,this.attachments=this.savedAttachments??[],this.savedAttachments=null):this.clearBuffer()}startHistorySearch(){let e=this.bufferText().toLowerCase();if(e.length===0)return this.historySearch={query:"",matchIndices:[],cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},[];let n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[0]]??""),[])}advanceHistorySearch(){if(this.historySearch===null)return[];let e=this.historySearch;if(e.cursor>=e.matchIndices.length-1){if(e.query.length===0)return[];let r=e.query,o=e.savedDraft;return this.historySearch=null,this.buffer=[...o.buffer],this.row=o.row,this.col=o.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}retreatHistorySearch(){if(this.historySearch===null||this.historySearch.cursor===0)return;this.historySearch.cursor-=1;let e=this.historySearch.matchIndices[this.historySearch.cursor];this.loadEntry(this.history[e]??"")}mutateHistorySearchQuery(e){if(this.historySearch===null)return[];if(e.length===0){this.historySearch.query="",this.historySearch.matchIndices=[],this.historySearch.cursor=0;let s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
|
|
147
|
+
`),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:o}]:[{type:"queue-edit",index:o,text:n,displayText:e,attachments:i}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=this.planMode,a=[...this.attachments],d=n.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{type:"queue-remove",index:o}]:[{type:"queue-remove",index:o},{type:"amend",text:n,displayText:e,planMode:i,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});import uS from"path";function lo(t){return wm[uS.extname(t).toLowerCase()]??null}function fS(t){return lo(t)!==null}function ec(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!pS.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,o=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:o}}function mS(t){return ec(t)!==null}function Ft(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function bm(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],o="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)o+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(o+=e[s+1],s+=2):(o+=e[s],s++);if(o.startsWith("data:")){if(!mS(o))return null;n.push(o);continue}let i=o;if(i.startsWith("file://")&&(i=decodeURI(i.slice(7))),!i.startsWith("/")||!fS(i))return null;n.push(i)}return n.length>0?n:null}var rn,wm,pS,ea=V(()=>{"use strict";rn=10*1024*1024,wm={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};pS=new Set(Object.values(wm))});function hS(){uo===0&&process.stdout.write("\x1B[?2026h"),uo++}function gS(){uo!==0&&(uo--,uo===0&&process.stdout.write("\x1B[?2026l"))}function Re(t){hS();try{t()}finally{gS()}}var uo,tc=V(()=>{"use strict";uo=0});import sa from"string-width";import yS from"wrap-ansi";function xS(t){let e=t.replace(/\r\n?$|\n$/,"");return kS.test(e)?e:null}function AS(t,e,n,s=null,r=null){let o=r===null?"":`a${r}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}`;let i=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${i}`}function vn(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let o=0;for(;o<r.length;){if(r.length-o<=e){n.push({bufferIdx:s,startCol:o,endCol:r.length}),o=r.length;break}let i=-1;for(let a=o+e-1;a>=o;a--){let d=r[a];if(d===" "||d===" "){i=a+1;break}}i===-1&&(i=o+e),n.push({bufferIdx:s,startCol:o,endCol:i}),o=i}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function jn(t,e,n){let s=0,r=0,o=-1;for(let d=0;d<t.length;d++){let c=t[d];if(!(!c||c.bufferIdx!==e.row)&&(o=d,e.col>=c.startCol&&e.col<c.endCol)){s=d,r=e.col-c.startCol,o=-1;break}}if(o!==-1){let d=t[o];d&&(s=o,r=e.col-d.startCol)}let i=Math.min(n,Math.max(1,t.length)),a=0;return t.length>i&&(a=Math.max(0,Math.min(t.length-i,s-(i-1))),s<a&&(a=s),s>=a+i&&(a=s-i+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:i}}function CS(t,e,n,s,r=null,o=0){if(e.length===0)return;if(s.length===0){fs(t,e,n);return}let i=e.toLowerCase(),a=0;for(;a<e.length;){let d=i.indexOf(s,a);if(d===-1){fs(t,e.slice(a),n);return}d>a&&fs(t,e.slice(a,d),n);let c=r!==null&&d===r;fs(t,e.slice(d,d+s.length),c?"search-highlight-active":"search-highlight"),a=d+s.length}}function vm(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"}function fs(t,e,n){if(e.length!==0)switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.green.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow.noFormat(e);return;case"plan-done":t.green.noFormat(e);return;case"plan-pending":t.dim.noFormat(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}function RS(t,e){return e<=0?[t]:t.length===0?[""]:yS(t,e,{hard:!0,trim:!1}).split(`
|
|
148
|
+
`)}function Rm(t){Cm=t}function ps(t){return sa(t,{ambiguousIsNarrow:!Cm})}function ac(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return TS.test(n)?{text:t.slice(e,e+2),width:0}:null}function Tm(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(ac(t,e))return!0;return!1}function*Em(t){let e=0;for(;e<t.length;){let n=ac(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(ac(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:o}of dc.segment(t.slice(e,s)))yield{text:o,width:ps(o)};e=s}}function ES(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function PS(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&Tm(t);return!s&&!Am.test(t)?MS(t,e):$S(t,e,s)}function MS(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),o=-1;for(let i=Math.min(e,r.length-1);i>=0;i--)if(r[i]===" "){o=i;break}o<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,o)),s=s.slice(o+1))}return n.push(s),n}function $S(t,e,n){let s=[],r=n?[...Em(t)]:_S(t),o=0;for(;o<r.length;){let i="",a=0,d=-1,c="";for(;o<r.length;){let l=r[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>=r.length){s.push(i);break}d>=0?(s.push(c),o=d+1):i.length===0?(s.push(r[o].text),o+=1):s.push(i)}return s}function _S(t){let e=[];for(let{segment:n}of dc.segment(t))e.push({text:n,width:ps(n)});return e}function it(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&Tm(t);if(!s&&t.length<=e&&!Am.test(t))return t;if(!s)return ps(t)<=e?t:e<=1?Im(t,e):Im(t,e-1)+"\u2026";let r=[...Em(t)],o=0;for(let i of r)o+=i.width;return o<=e?t:e<=1?Sm(r,e):Sm(r,e-1)+"\u2026"}function Im(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of dc.segment(t)){let o=ps(r);if(s+o>e)break;n+=r,s+=o}return n}function Sm(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function FS(t){let e=t.indexOf(`
|
|
149
|
+
`);return e===-1?t:`${t.slice(0,e)} \u21B5`}function OS(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${ta(t.used)}/${ta(t.size)}`):e.push(ta(t.used)):typeof t.size=="number"&&e.push(`/${ta(t.size)}`),typeof t.costAmount=="number"&&e.push(Ad(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function ta(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function oa(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function na(){let t=["\x1B[?1000l","\x1B[?1002l","\x1B[?1003l","\x1B[?1006l","\x1B[?1015l","\x1B[=0;0w","\x1B[?2004l","\x1B[>4;0m","\x1B[>5;0m","\x1B[<u","\x1B[?1l","\x1B>","\x1B[?7h","\x1B[?25h","\x1B]9;4;0\x07","\x1B[?1049l"].join("");try{process.stdout.write(t)}catch{}}function xm(t,e){let n={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":null:null}var Be,Je,Ne,nc,sc,wS,bS,vS,rc,oc,ic,IS,SS,kS,ra,Am,dc,Cm,TS,km,cc=V(()=>{"use strict";Cd();de();tn();ea();so();tc();Be=1,Je=1,Ne=1,nc=8,sc=5,wS=12,bS=12,vS=30,rc=6,oc=4,ic=2,IS=1e3,SS=1e4,kS=/^(https?|ftp):\/\/\S+$/;ra=class{term;dispatcher;onKey;onBlockClick;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;lastRepaintAt=0;throttledRepaintTimer=null;contentRepaintThrottleMs;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;pasteBuffer="";rawStdinHandler;mouseEnabled;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,this.onKey=e.onKey,this.onBlockClick=e.onBlockClick,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??IS,this.maxScrollbackLines=e.maxScrollbackLines??SS,this.mouseEnabled=e.mouse??!1,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(n,s,r)=>this.handleKey(n,r),this.mouseHandler=(n,s)=>this.handleMouse(n,s),this.rawStdinHandler=n=>this.handleRawStdin(n)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,process.stdout.write("\x1B[?7l"),this.mouseEnabled?this.term.grabInput({mouse:"button"}):this.term.grabInput(!0),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),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),this.term.hideCursor(!1),e.keepFullscreen||process.stdout.write("\x1B[?7h"),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(na(),this.term.fullscreen(!1),this.term(`
|
|
150
150
|
`)))}installBracketedPaste(){process.stdout.write("\x1B[?2004h"),process.stdout.write("\x1B[>4;2m"),process.stdout.write("\x1B[>5;1m"),process.stdout.write("\x1B[>1u");let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,process.stdout.write("\x1B[?w"),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(process.stdout.write("\x1B[=0;0w"),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>na(),this.onProcessSignal=e=>{na(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{na(),process.stderr.write(`
|
|
151
151
|
uncaught: ${e.stack??e.message}
|
|
152
152
|
`),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,process.stdout.write("\x1B[=24;1w"),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,o;for(;(o=n.exec(e))!==null;)s+=e.slice(r,o.index),o[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=o.index+o[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes("\x1B[200~")){this.handleRawStdinSegment(n);return}if(n.includes(`
|
|
153
153
|
`)){let s=n.split(`
|
|
154
154
|
`);if(s.filter(o=>o.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let o=0;o<s.length;o++)s[o].length>0&&this.handleRawStdin(Buffer.from(s[o],"binary")),o<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let o=parseInt(r[1],10),i=parseInt(r[2],10),a=xm(i,o);a!==null?this.onKey([{type:"key",name:a}]):(o===1||o===2)&&i>=32&&i<127&&this.handleRawStdinSegment(String.fromCharCode(i)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let o=parseInt(r[1],10),i=r[2]!==void 0?parseInt(r[2],10):1,a=xm(o,i);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n="\x1B[200~",s="\x1B[201~";for(;e.length>0;){if(this.pasteActive){let o=e.indexOf(s);if(o===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,o),e=e.slice(o+s.length),this.pasteActive=!1;let i=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
|
|
155
|
-
`);this.pasteBuffer="";let a=bm(i);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:i}]);continue}let r=e.indexOf(n);if(r===-1){let o=
|
|
156
|
-
`),[i,...a]=o,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=i??"",d+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:n,body:i??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(n.length);for(let l of a){let f={prefix:c,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),d+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=km(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,o=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);o!==this.lastWindowTitle&&(this.lastWindowTitle=o,process.stdout.write(`\x1B]0;${o}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Re(()=>{e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"button"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),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}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.repaint()}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),i=this.lines.splice(n.start,n.count);for(let a of i)this.forgetLine(a);this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>n.start&&(d.start-=n.count);r&&(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 n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,o]of this.keyedBlocks)r!==this.stickyBottomKey&&o.start>=n&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),o=this.lines.splice(n.start,n.count);for(let i of o)this.forgetLine(i);this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>n.start&&(i.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write("\x1B[?7l"),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){this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==null}setConfirmPrompt(e){this.confirmPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let o=this.completions[r];return o!==void 0&&o.name===s.name&&o.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let o=this.lines[r];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),s?(this.lines.splice(n.start,0,i),n.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,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=oa(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let s=this.mouseCell(n);if(e==="MOUSE_LEFT_BUTTON_PRESSED"){this.pressCell=s;return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let r=this.pressCell;if(this.pressCell=null,this.onBlockClick&&r!==null&&s!==null&&s.x===r.x&&s.y===r.y){let o=this.keyAtRow(s.y);o!==null&&this.onBlockClick(o)}}}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let o=e-s;if(o<0||o>=r)return null;let{rows:i}=this.wrapTail(n,r+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-r),c=i.slice(d,a),l=Math.max(0,r-c.length),f=o-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let o=this.lines[r];if(!o||o.body.length===0||o.ansi)continue;let i=o.body.toLowerCase(),a=[],d=0;for(;d<i.length;){let c=i.indexOf(n,d);if(c===-1)break;a.push(c),d=c+n.length}for(let c=a.length-1;c>=0;c--)s.push({lineIdx:r,col:a[c]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let g=p.body.length;if(e.col<f+g){i=l.length-1-u;break}f+=g}}let a=r+i,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Be-Ne-Je-Ne-this.chipRows()-this.queuedRows()-this.completionRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}if(this.contentRepaintThrottleMs<=0){this.repaint();return}let n=Date.now()-this.lastRepaintAt;if(n>=this.contentRepaintThrottleMs){this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),this.repaint();return}this.throttledRepaintTimer===null&&(this.throttledRepaintTimer=setTimeout(()=>{this.throttledRepaintTimer=null,this.repaint()},this.contentRepaintThrottleMs-n))}paintRow(e,n,s){this.started&&(e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter()))}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.lastRepaintAt=Date.now(),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null);let e=this.term.width,n=this.term.height;e<20||n<8||((e!==this.lastFrameW||n!==this.lastFrameH)&&(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n),Re(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Je-Ne-Be;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-Be),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=this.term.width,n=this.term.height,s=km(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),o=Yf(this.sessionbar.agent,this.sessionbar.model),i=$e(this.sessionbar.cwd),a=vS(this.sessionbar.usage),d=`sbar|${e}|${s}|${o}|${i}|${r??""}|${a??""}`;this.paintRow(n,d,()=>{let c=a?a.length+3:0,l=s.length+3+o.length+3+(r?3:0)+c,f=Math.max(8,e-l),u,p;if(r){let g=Math.min(r.length,8);u=Math.min(i.length,Math.max(8,f-g)),p=Math.max(0,f-u)}else p=0,u=f;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(o)(" \xB7 ").dim.noFormat(it(i,u)),r&&this.term(" \xB7 ").bold.noFormat(it(r,p)),this.term.eraseLineAfter(),a){let g=sa(a),h=Math.max(1,e-g);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:o}=this.wrapTail(e,s+this.scrollOffset);if(o){let u=Math.max(0,r.length-s);this.scrollOffset>u&&(this.scrollOffset=u)}let i=r.length-this.scrollOffset,a=Math.max(0,i-s),d=r.slice(a,i),c=Math.max(0,s-d.length),l=this.currentMatchInfo(),f=l?.length??0;for(let u=0;u<s;u++){let p=n+u,g=u-c,h=g>=0?d[g]:void 0,w=this.activeMatchCol(h,l),v=lS("sb",e,h,this.scrollbackHighlight,w);this.paintRow(p,v,()=>{h&&this.writeFormattedLine(h,e,w,f)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let u=new Set;for(let g of d)g.blockKey!==void 0&&u.add(g.blockKey);let p=[];for(let g of this.pendingVisibleKeys)u.has(g)&&p.push(g);for(let g of p)this.pendingVisibleKeys.delete(g),this.onBlockVisible(g)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(nc,this.queuedTexts.length)}chipRows(){return Math.min(rc,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(sc,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Be-Ne-Je,o=this.queuedRows(),i=this.chipRows(),d=r-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 f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>sc,g=this.completions.length-sc+1,h=u?p?`comp|${n}|overflow|${g}`:`comp|${n}|${c}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){this.term.dim(` + ${g} more match(es)`);return}let w=u.name.padEnd(c),v=u.description??"",b=n-w.length-4,A=b>0?it(v,b):"";this.term(" ").brightCyan(w),A.length>0&&this.term(" ").dim(A)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),i=this.term.height-s-Be-Ne-Je-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=i+d,l=d===e-1&&this.attachments.length>rc,f=this.attachments.length-rc,u=this.attachments[d],p=u?`${u.name??"image"} \xB7 ${Ft(u.sizeBytes)}`:"",g=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(c,g,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(mS(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Be-Ne-Je,o=this.chipRows(),a=r-1-o-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>nc,p=this.queuedTexts.length-nc,g=f===void 0?"":u?`+ ${p+1} more queued`:it(bS(f),n-4),h=!u&&c===d,w=f===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":u?"ovf":"row"}|${g}`;this.paintRow(l,w,()=>{if(f===void 0)return;let v=`\u23F3 ${g}`,b=v+" ".repeat(Math.max(0,n-1-v.length));h?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=vn(s.buffer,n),o=qn(r,s,tc),i=this.term.height-o.rendered-Je-Ne-Be+1;for(let a=0;a<o.rendered;a++){let d=r[o.windowStart+a],c=i+a,l="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?l="first":d.startCol===0&&(l="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let u=d?`prompt|${this.term.width}|${l}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(c,u,()=>{d&&(l==="first"?this.term.brightWhite("> "):l==="newline"?this.term.dim("\xB7 "):this.term(" "),this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-oc-Je-Ne-Be+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${it(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${it(e.hint,n-2)}`)})}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Je-Ne-Be+1,o=r,i=(d,c)=>{o>=r+s||(this.paintRow(o,d,c),o+=1)};i(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${it(e.title,n-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>=r+s-1)break;if(d===null){i(`help|sep|${n}|${o}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);i(`help|e|${n}|${c}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${it(l,n-2-a-1)}`)})}i(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${it(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(oS,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Je-Ne-Be+1,o=r,i=(d,c)=>{o>=r+s||(this.paintRow(o,d,c),o+=1)};i(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${it(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${it(a,n-2)}`)}),i(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let d=0;d<e.options.length&&!(o>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. ${it(c.label,n-8)}`;i(`perm|o|${n}|${d}|${l?"1":"0"}|${c.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}i(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-Be-Ne,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?sn(this.banner.elapsedMs):"",r=this.bannerRightContent(),o=r?`${r.kind}|${r.text}`:"",i=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${i?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+o;this.paintRow(e,a,()=>{let d=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(i?this.term.brightRed(`${d} stalled`):this.term.brightYellow(`${d} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${d} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${d} ${this.banner.status}`):this.term.brightGreen(`${d} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let c=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(c),this.term.eraseLineAfter(),r){let l=sa(r.text),f=Math.max(1,n-l);this.term.moveTo(f,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Je-Ne-Be+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Je-Ne-Be;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-Je-Ne-Be+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Je-Ne-Be;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-oc-Je-Ne-Be+1;this.term.moveTo(2,l);return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Je-Ne-Be+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=vn(s.buffer,n),o=qn(r,s,tc),a=this.term.height-o.rendered-Je-Ne-Be+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Je-Ne-Be;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return oc;if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=vn(s.buffer,n);return Math.min(tc,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(sS,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(rS,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Je-Ne-Be+1,o=r,i=(d,c)=>{o>=r+s||(this.paintRow(o,d,c),o+=1)};i(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${it(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(o>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. `,p=c.label.padEnd(a),g=n-u.length-3,h=`${u}${it(`${p} ${c.value}`,g)}`;i(`opts|o|${n}|${d}|${l?"1":"0"}|${c.value}|${c.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}i(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}wrapTail(e,n){let s=c=>this.hideThoughts&&c.bodyStyle==="thought";if(e<=4){let c=[];for(let f of this.lines)s(f)||c.push(f);let l=Math.min(n,c.length);return{rows:c.slice(c.length-l),exhausted:n>=c.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],o=0,i=0,a=!1;for(let c=this.lines.length-1;c>=0;c--){let l=this.lines[c];if(s(l)){c===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),o+=f.length,i=c,o>=n)break}let d=[];for(let c=r.length-1;c>=0;c--)d.push(...r[c]);return{rows:d,exhausted:i===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let f=this.wrapCache.get(s);if(f)return f}let r=e.prefix??"",o=ms(r),i=Math.max(1,n-o),a=vm(e.bodyStyle),d=e.ansi?fS(e.body,i):hS(e.body,i,{stripMarkup:a}),c=[],l=0;for(let f=0;f<d.length;f++){let u=d[f]??"",p={prefix:f===0?e.prefix:" ".repeat(o),body:u};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),f===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&u.length>0){let g=e.body.indexOf(u,l),h=g===-1?l:g;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+u.length}c.push(p)}return s!==void 0&&this.wrapCache.set(s,c),c}writeFormattedLine(e,n,s=null,r=0){e.prefix&&ps(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-ms(e.prefix??"")),i=vm(e.bodyStyle),a=e.ansi?e.body:it(e.body,o,{stripMarkup:i});if(this.scrollbackHighlight!==null&&!e.ansi?uS(this.term,a,e.bodyStyle,this.scrollbackHighlight,s,r):ps(this.term,a,e.bodyStyle),e.fillRow){let d=e.ansi?sa(a):ms(a),c=o-d;c>0&&ps(this.term," ".repeat(c),e.bodyStyle)}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Am=/[^\x20-\x7e]/,ac=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Cm=!1;pS=/[a-zA-Z+\-:_!#/]/;km=Oe});function yr(){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>")}function cc(t){return t.width??80}function lc(t){return t.height??24}function hs(t,e){let n=cc(t),s=lc(t),r=e.contentWidth??64,o=Math.max(10,n-4),i=Math.min(r,o),a=i+2,d=Math.max(1,Math.min(e.contentHeight,s-4)),c=d+2,l=Math.max(1,Math.floor((n-a)/2)+1),f=Math.max(1,Math.floor((s-c)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let u="\u2500".repeat(a-2),p=IS(u,e.title);t.moveTo(l,f),t.dim.noFormat("\u250C"),SS(t,p),t.dim.noFormat("\u2510");for(let g=1;g<=d;g++)t.moveTo(l,f+g),t.dim.noFormat("\u2502"),t.moveTo(l+a-1,f+g),t.dim.noFormat("\u2502");return t.moveTo(l,f+c-1),t.dim.noFormat("\u2514"+"\u2500".repeat(a-2)+"\u2518"),{x:l,y:f,w:a,h:c,contentX:l+1,contentY:f+1,contentW:i,contentH:d}}function IS(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function SS(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}var ia=V(()=>{"use strict"});function kS(t,e,n=fo){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(o=>o.hotkey.toLowerCase()===s);if(r>=0){let o=n[r];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:t}}async function Pm(t,e){yr();let n=Oe(e.sessionId),s=e.importedFromMachine??"another machine",r=$e(e.cwd),o=fo.findIndex(a=>a.key==="view");o<0&&(o=0);let i=()=>{let d=7+fo.length*2+2,c=hs(t,{contentHeight:d,title:"Imported session"}),l=c.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(uc(p.value,l-p.label.length-2)),u++;u++,t.moveTo(c.contentX,c.contentY+u),t.noFormat(" What do you want to do?"),u+=2;for(let p=0;p<fo.length;p++){let g=fo[p];if(!g)continue;let w=` ${p===o?"\u276F":" "} ${g.label}`;t.moveTo(c.contentX,c.contentY+u),p===o?t.brightWhite.bgBlue.noFormat($m(w,l)):t.noFormat(w),u++,t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(` ${g.description}`),u++}return u++,t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"),c};return i(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",u),t.off("resize",f),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=p=>{c(),a(p)},f=()=>{d||i()},u=(p,g,h)=>{let w=xS(p,h);if(!w)return;let v=kS(o,w);if(v.kind==="cancel"){l("cancel");return}if(v.kind==="back"){l("back");return}if(v.kind==="resolve"){l(v.action);return}v.selected!==o&&(o=v.selected,i())};t.grabInput({}),t.on("key",u),t.on("resize",f)})}function xS(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function Mm(t,e,n){let s=Oe(e.sessionId),r=e.title??$e(e.cwd),o=1,i=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=hs(t,{contentHeight:11,title:"Open session"}),c=d.contentW,l=0;t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" session: "),t.noFormat(uc(s,c-10)),l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" "+uc(r,c-2)),l++,l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" What do you want to do?"),l+=2;for(let f=0;f<i.length;f++){let u=i[f];if(!u)continue;let g=` ${f===o?"\u276F":" "} ${u.label}`;t.moveTo(d.contentX,d.contentY+l),f===o?t.brightWhite.bgBlue.noFormat($m(g,c)):t.noFormat(g),l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(` ${u.description}`),l++}l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back")};return a(),t.hideCursor(),await new Promise(d=>{let c=!1,l=()=>{c=!0},f=p=>{l(),n.pop(),d(p)},u=(p,g,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(o===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){o>0&&(o--,a());return}if(p==="DOWN"||p==="TAB"){o<i.length-1&&(o++,a());return}if(h?.isCharacter){let w=p.toLowerCase();if(w==="l"){f("launch");return}if(w==="v"){f("view");return}if(w==="n"){o<i.length-1&&(o++,a());return}if(w==="p"){o>0&&(o--,a());return}}};n.push({onKey:(p,g,h)=>{c||u(p,g,h)},onResize:()=>{c||a()}})})}function uc(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function $m(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var fo,fc=V(()=>{"use strict";de();tn();ia();fo=[{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 hc(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function gc(t,e){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let n=e.prefs??hc();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(P=>P.sessionId===e.currentSessionId)?.importedFromMachine&&(n.filters.hostFilter="__all");let s=Fm(e.sessions,e.cwd),r=k=>{let P=k;return n.filters.cwdOnly&&(P=P.filter(F=>F.cwd===e.cwd)),n.filters.includeNonInteractive||(P=P.filter(F=>F.interactive===!0)),P=ES(P,n.filters.hostFilter),P},o=r(s),i={columns:e.config.tui.sessionColumns??ir,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},a=o.map(k=>dr(k,Date.now())),d=cr(a,i),c=1+o.length,l=0,f=0;if(e.currentSessionId!==void 0){let k=o.findIndex(P=>P.sessionId===e.currentSessionId);k>=0&&(l=k+1)}let u=!1,p="",g=120,h=!1,w=0,v="normal",b=null,A=!1,T="input",$=new bn({history:[],collapsePastes:!1}),K=[],te=!1,J=0,D=0,_=null,H=!1,q="",z=null,be=!1,xe=new bn({history:[]});e.initialPrompt&&xe.setBuffer(e.initialPrompt);let X=e.config.tui.promptHistoryMaxEntries;Ur(R.globalTuiHistoryFile()).then(k=>{let P=k.length>X?k.slice(k.length-X):k;xe.setHistory(P)}).catch(()=>{});let Ae=mc(t),Y=gs(t),ge=0,wr="",In=0,et=[],xt=1,Sn=0,ue=0,ws=0,br="",bs=[],on=1,Wn=0,vs=[],Ye=1,kn=0,Te=0,Ot=0,lt=()=>{Ae=mc(t),Y=gs(t);let k=Math.max(10,Y-pc);In=Math.max(10,Y-_m);let P=Math.max(10,Y-8);wr=TS(e.cwd,P);let F=xe.state();et=vn(F.buffer,In);let Q=qn(et,F,aa);xt=Q.rendered,Sn=Q.windowStart,ue=Q.cursorVisualRow,ws=Q.cursorVisualCol;let ae=6+xt,we=Math.max(3,Ae-ae);ge=Math.min(o.length,we),br=Dn(ar,d,k,i).padEnd(k),bs=a.map(Ce=>Dn(Ce,d,k,i).padEnd(k))},vr=()=>{a=o.map(k=>dr(k,Date.now())),d=cr(a,i),c=1+o.length,lt()},tt=()=>{let k=r(s);u&&p.length>0?o=k.filter(P=>MS(P,p)):o=k,vr(),u?(f=0,l=o.length>0?1:0):l>c-1&&(l=Math.max(0,c-1)),f+ge>o.length&&(f=Math.max(0,o.length-ge)),Lt()},zn=k=>{if(k!==void 0){let P=o.findIndex(F=>F.sessionId===k);if(P>=0){l=P+1,Lt();return}}l=o.length>0?1:0,f=0,Lt()},Lt=()=>{if(l===0)return;let k=l-1;k<f?f=k:k>=f+ge?f=k-ge+1:f+ge>o.length&&(f=Math.max(0,o.length-ge))},Jn=()=>Math.max(2,Y-2),Is=()=>{let k=Jn(),P=`\u2500 ${wr} `,F=Math.max(1,k-P.length),Q="\u2500".repeat(F);l===0?t.brightBlue.noFormat(`\u256D${P}${Q}\u256E`):t.dim.noFormat(`\u256D${P}${Q}\u256E`)},Ss=()=>{let k=Jn(),P="\u2500".repeat(k);l===0?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},an=k=>{let P=Jn(),F=et[k],Q="";F&&(Q=(xe.state().buffer[F.bufferIdx]??"").slice(F.startCol,F.endCol));let ae=Math.max(0,P-1-Q.length),we=" ".repeat(ae);l===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${Q}${we}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${Q}${we}`),t.dim.noFormat("\u2502"))},xn=k=>{let P=bs[k]??"";l===k+1?t.brightWhite.bgBlue.noFormat(`\u276F ${P}`):t.noFormat(` ${P}`)},dn=()=>{let k=f,P=Math.max(0,o.length-f-ge),F=[];return n.filters.cwdOnly&&F.push("cwd-only"),n.filters.hostFilter!=="__all"&&F.push(n.filters.hostFilter==="__local"?"host: local":`host: ${n.filters.hostFilter}`),n.filters.includeNonInteractive&&F.push("+non-interactive"),k>0&&F.push(`\u2191 ${k} above`),P>0&&F.push(`\u2193 ${P} below`),F.length===0?"":` ${F.join(" \xB7 ")}`},Wt=k=>Oe(k),Se=()=>{Re(()=>{if(t.moveTo(1,Ir()),v==="confirm-kill"&&b)t.brightYellow.noFormat(` kill ${Wt(b.sessionId)}? [y/N]`);else if(v==="confirm-delete"&&b)b.status==="live"?t.brightRed.noFormat(` kill + delete ${Wt(b.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Wt(b.sessionId)}? [y/N]`);else if(v==="busy"&&b)t.dim.noFormat(` working on ${Wt(b.sessionId)}\u2026`);else if(v==="rename"&&b)t.brightYellow.noFormat(` title: ${q}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(z!==null)t.dim.noFormat(` ${z}`);else if(u){t.brightYellow.noFormat(` /${p}`),t.bgBrightYellow(" ");let k=o.length===0?" no matches":` ${o.length} match${o.length===1?"":"es"}`;t.dim.noFormat(`${k} \xB7 ^c clears`)}else t.dim.noFormat(dn());t.styleReset(),t.eraseLineAfter()})},nt=k=>on+1+k,At=()=>on+xt+1,ut=()=>on+xt+3,ye=k=>ut()+1+(k-f),Ir=()=>ut()+1+ge,ft=()=>{let k=ue-Sn;if(k<0||k>=xt)return;let P=3+ws;t.moveTo(P,nt(k))},ke=()=>{Re(()=>{t.hideCursor(),lt(),Lt(),on=1,t.moveTo(1,1).eraseDisplayBelow(),Is(),t(`
|
|
155
|
+
`);this.pasteBuffer="";let a=bm(i);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:i}]);continue}let r=e.indexOf(n);if(r===-1){let o=xS(e);o!==null?this.onKey([{type:"paste",text:o}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let i of n)i.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,o=0;if(s){let i=s.start+s.count;r=i>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,i)),d=n.length-s.count,c=this.lines.splice(s.start,s.count,...n);for(let l of c)this.forgetLine(l);if(this.trackLines(n),s.count=n.length,d!==0)for(let[l,f]of this.keyedBlocks)l!==e&&f.start>s.start&&(f.start+=d);o=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),o=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(o),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let o=e.split(`
|
|
156
|
+
`),[i,...a]=o,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=i??"",d+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:n,body:i??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(n.length);for(let l of a){let f={prefix:c,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),d+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=km(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,o=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);o!==this.lastWindowTitle&&(this.lastWindowTitle=o,process.stdout.write(`\x1B]0;${o}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Re(()=>{e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"button"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),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}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.repaint()}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),i=this.lines.splice(n.start,n.count);for(let a of i)this.forgetLine(a);this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>n.start&&(d.start-=n.count);r&&(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 n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,o]of this.keyedBlocks)r!==this.stickyBottomKey&&o.start>=n&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),o=this.lines.splice(n.start,n.count);for(let i of o)this.forgetLine(i);this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>n.start&&(i.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let o=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=d&&f.start<c)return!0;return!1},i=r;for(;i>0&&!o(s[i-1].start+s[i-1].count,s[i].start);)i--;let a=r;for(;a<s.length-1&&!o(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(i,a+1).map(d=>d.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let o=this.keyedBlocks.get(r),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=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0,this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write("\x1B[?7l"),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){this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==null}setConfirmPrompt(e){this.confirmPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let o=this.completions[r];return o!==void 0&&o.name===s.name&&o.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let o=this.lines[r];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),s?(this.lines.splice(n.start,0,i),n.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,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=oa(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let s=this.mouseCell(n);if(e==="MOUSE_LEFT_BUTTON_PRESSED"){this.pressCell=s;return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let r=this.pressCell;if(this.pressCell=null,this.onBlockClick&&r!==null&&s!==null&&s.x===r.x&&s.y===r.y){let o=this.keyAtRow(s.y);o!==null&&this.onBlockClick(o)}}}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let o=e-s;if(o<0||o>=r)return null;let{rows:i}=this.wrapTail(n,r+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-r),c=i.slice(d,a),l=Math.max(0,r-c.length),f=o-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let o=this.lines[r];if(!o||o.body.length===0||o.ansi)continue;let i=o.body.toLowerCase(),a=[],d=0;for(;d<i.length;){let c=i.indexOf(n,d);if(c===-1)break;a.push(c),d=c+n.length}for(let c=a.length-1;c>=0;c--)s.push({lineIdx:r,col:a[c]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let g=p.body.length;if(e.col<f+g){i=l.length-1-u;break}f+=g}}let a=r+i,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Be-Ne-Je-Ne-this.chipRows()-this.queuedRows()-this.completionRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}if(this.contentRepaintThrottleMs<=0){this.repaint();return}let n=Date.now()-this.lastRepaintAt;if(n>=this.contentRepaintThrottleMs){this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null),this.repaint();return}this.throttledRepaintTimer===null&&(this.throttledRepaintTimer=setTimeout(()=>{this.throttledRepaintTimer=null,this.repaint()},this.contentRepaintThrottleMs-n))}paintRow(e,n,s){this.started&&(e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter()))}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.lastRepaintAt=Date.now(),this.throttledRepaintTimer&&(clearTimeout(this.throttledRepaintTimer),this.throttledRepaintTimer=null);let e=this.term.width,n=this.term.height;e<20||n<8||((e!==this.lastFrameW||n!==this.lastFrameH)&&(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n),Re(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Je-Ne-Be;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-Be),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=this.term.width,n=this.term.height,s=km(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),o=Yf(this.sessionbar.agent,this.sessionbar.model),i=$e(this.sessionbar.cwd),a=OS(this.sessionbar.usage),d=`sbar|${e}|${s}|${o}|${i}|${r??""}|${a??""}`;this.paintRow(n,d,()=>{let c=a?a.length+3:0,l=s.length+3+o.length+3+(r?3:0)+c,f=Math.max(8,e-l),u,p;if(r){let g=Math.min(r.length,8);u=Math.min(i.length,Math.max(8,f-g)),p=Math.max(0,f-u)}else p=0,u=f;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(o)(" \xB7 ").dim.noFormat(it(i,u)),r&&this.term(" \xB7 ").bold.noFormat(it(r,p)),this.term.eraseLineAfter(),a){let g=sa(a),h=Math.max(1,e-g);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:o}=this.wrapTail(e,s+this.scrollOffset);if(o){let u=Math.max(0,r.length-s);this.scrollOffset>u&&(this.scrollOffset=u)}let i=r.length-this.scrollOffset,a=Math.max(0,i-s),d=r.slice(a,i),c=Math.max(0,s-d.length),l=this.currentMatchInfo(),f=l?.length??0;for(let u=0;u<s;u++){let p=n+u,g=u-c,h=g>=0?d[g]:void 0,w=this.activeMatchCol(h,l),v=AS("sb",e,h,this.scrollbackHighlight,w);this.paintRow(p,v,()=>{h&&this.writeFormattedLine(h,e,w,f)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let u=new Set;for(let g of d)g.blockKey!==void 0&&u.add(g.blockKey);let p=[];for(let g of this.pendingVisibleKeys)u.has(g)&&p.push(g);for(let g of p)this.pendingVisibleKeys.delete(g),this.onBlockVisible(g)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(sc,this.queuedTexts.length)}chipRows(){return Math.min(oc,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(rc,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Be-Ne-Je,o=this.queuedRows(),i=this.chipRows(),d=r-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 f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>rc,g=this.completions.length-rc+1,h=u?p?`comp|${n}|overflow|${g}`:`comp|${n}|${c}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){this.term.dim(` + ${g} more match(es)`);return}let w=u.name.padEnd(c),v=u.description??"",b=n-w.length-4,x=b>0?it(v,b):"";this.term(" ").brightCyan(w),x.length>0&&this.term(" ").dim(x)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),i=this.term.height-s-Be-Ne-Je-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=i+d,l=d===e-1&&this.attachments.length>oc,f=this.attachments.length-oc,u=this.attachments[d],p=u?`${u.name??"image"} \xB7 ${Ft(u.sizeBytes)}`:"",g=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(c,g,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(ES(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Be-Ne-Je,o=this.chipRows(),a=r-1-o-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>sc,p=this.queuedTexts.length-sc,g=f===void 0?"":u?`+ ${p+1} more queued`:it(FS(f),n-4),h=!u&&c===d,w=f===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":u?"ovf":"row"}|${g}`;this.paintRow(l,w,()=>{if(f===void 0)return;let v=`\u23F3 ${g}`,b=v+" ".repeat(Math.max(0,n-1-v.length));h?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=vn(s.buffer,n),o=jn(r,s,nc),i=this.term.height-o.rendered-Je-Ne-Be+1;for(let a=0;a<o.rendered;a++){let d=r[o.windowStart+a],c=i+a,l="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?l="first":d.startCol===0&&(l="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let u=d?`prompt|${this.term.width}|${l}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(c,u,()=>{d&&(l==="first"?this.term.brightWhite("> "):l==="newline"?this.term.dim("\xB7 "):this.term(" "),this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-ic-Je-Ne-Be+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${it(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${it(e.hint,n-2)}`)})}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Je-Ne-Be+1,o=r,i=(d,c)=>{o>=r+s||(this.paintRow(o,d,c),o+=1)};i(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${it(e.title,n-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>=r+s-1)break;if(d===null){i(`help|sep|${n}|${o}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);i(`help|e|${n}|${c}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${it(l,n-2-a-1)}`)})}i(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${it(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(vS,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Je-Ne-Be+1,o=r,i=(d,c)=>{o>=r+s||(this.paintRow(o,d,c),o+=1)};i(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${it(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${it(a,n-2)}`)}),i(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let d=0;d<e.options.length&&!(o>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. ${it(c.label,n-8)}`;i(`perm|o|${n}|${d}|${l?"1":"0"}|${c.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}i(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-Be-Ne,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?sn(this.banner.elapsedMs):"",r=this.bannerRightContent(),o=r?`${r.kind}|${r.text}`:"",i=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${i?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+o;this.paintRow(e,a,()=>{let d=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(i?this.term.brightRed(`${d} stalled`):this.term.brightYellow(`${d} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${d} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${d} ${this.banner.status}`):this.term.brightGreen(`${d} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let c=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(c),this.term.eraseLineAfter(),r){let l=sa(r.text),f=Math.max(1,n-l);this.term.moveTo(f,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Je-Ne-Be+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Je-Ne-Be;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-Je-Ne-Be+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Je-Ne-Be;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-ic-Je-Ne-Be+1;this.term.moveTo(2,l);return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Je-Ne-Be+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=vn(s.buffer,n),o=jn(r,s,nc),a=this.term.height-o.rendered-Je-Ne-Be+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Je-Ne-Be;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return ic;if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=vn(s.buffer,n);return Math.min(nc,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(wS,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(bS,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Je-Ne-Be+1,o=r,i=(d,c)=>{o>=r+s||(this.paintRow(o,d,c),o+=1)};i(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${it(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(o>=r+s-1);d++){let c=e.options[d];if(!c)continue;let l=d===e.selectedIndex,u=` ${l?"\u276F":" "} ${d+1}. `,p=c.label.padEnd(a),g=n-u.length-3,h=`${u}${it(`${p} ${c.value}`,g)}`;i(`opts|o|${n}|${d}|${l?"1":"0"}|${c.value}|${c.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}i(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}wrapTail(e,n){let s=c=>c.collapsed===!0||this.hideThoughts&&c.bodyStyle==="thought";if(e<=4){let c=[];for(let f of this.lines)s(f)||c.push(f);let l=Math.min(n,c.length);return{rows:c.slice(c.length-l),exhausted:n>=c.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],o=0,i=0,a=!1;for(let c=this.lines.length-1;c>=0;c--){let l=this.lines[c];if(s(l)){c===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),o+=f.length,i=c,o>=n)break}let d=[];for(let c=r.length-1;c>=0;c--)d.push(...r[c]);return{rows:d,exhausted:i===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let f=this.wrapCache.get(s);if(f)return f}let r=e.prefix??"",o=ps(r),i=Math.max(1,n-o),a=vm(e.bodyStyle),d=e.ansi?RS(e.body,i):PS(e.body,i,{stripMarkup:a}),c=[],l=0;for(let f=0;f<d.length;f++){let u=d[f]??"",p={prefix:f===0?e.prefix:" ".repeat(o),body:u};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),f===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&u.length>0){let g=e.body.indexOf(u,l),h=g===-1?l:g;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+u.length}c.push(p)}return s!==void 0&&this.wrapCache.set(s,c),c}writeFormattedLine(e,n,s=null,r=0){e.prefix&&fs(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-ps(e.prefix??"")),i=vm(e.bodyStyle),a=e.ansi?e.body:it(e.body,o,{stripMarkup:i});if(this.scrollbackHighlight!==null&&!e.ansi?CS(this.term,a,e.bodyStyle,this.scrollbackHighlight,s,r):fs(this.term,a,e.bodyStyle),e.fillRow){let d=e.ansi?sa(a):ps(a),c=o-d;c>0&&fs(this.term," ".repeat(c),e.bodyStyle)}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Am=/[^\x20-\x7e]/,dc=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Cm=!1;TS=/[a-zA-Z+\-:_!#/]/;km=Oe});function yr(){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>")}function lc(t){return t.width??80}function uc(t){return t.height??24}function ms(t,e){let n=lc(t),s=uc(t),r=e.contentWidth??64,o=Math.max(10,n-4),i=Math.min(r,o),a=i+2,d=Math.max(1,Math.min(e.contentHeight,s-4)),c=d+2,l=Math.max(1,Math.floor((n-a)/2)+1),f=Math.max(1,Math.floor((s-c)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let u="\u2500".repeat(a-2),p=LS(u,e.title);t.moveTo(l,f),t.dim.noFormat("\u250C"),BS(t,p),t.dim.noFormat("\u2510");for(let g=1;g<=d;g++)t.moveTo(l,f+g),t.dim.noFormat("\u2502"),t.moveTo(l+a-1,f+g),t.dim.noFormat("\u2502");return t.moveTo(l,f+c-1),t.dim.noFormat("\u2514"+"\u2500".repeat(a-2)+"\u2518"),{x:l,y:f,w:a,h:c,contentX:l+1,contentY:f+1,contentW:i,contentH:d}}function LS(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function BS(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}var ia=V(()=>{"use strict"});function NS(t,e,n=fo){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(o=>o.hotkey.toLowerCase()===s);if(r>=0){let o=n[r];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:t}}async function Pm(t,e){yr();let n=Oe(e.sessionId),s=e.importedFromMachine??"another machine",r=$e(e.cwd),o=fo.findIndex(a=>a.key==="view");o<0&&(o=0);let i=()=>{let d=7+fo.length*2+2,c=ms(t,{contentHeight:d,title:"Imported session"}),l=c.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(fc(p.value,l-p.label.length-2)),u++;u++,t.moveTo(c.contentX,c.contentY+u),t.noFormat(" What do you want to do?"),u+=2;for(let p=0;p<fo.length;p++){let g=fo[p];if(!g)continue;let w=` ${p===o?"\u276F":" "} ${g.label}`;t.moveTo(c.contentX,c.contentY+u),p===o?t.brightWhite.bgBlue.noFormat($m(w,l)):t.noFormat(w),u++,t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(` ${g.description}`),u++}return u++,t.moveTo(c.contentX,c.contentY+u),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"),c};return i(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",u),t.off("resize",f),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=p=>{c(),a(p)},f=()=>{d||i()},u=(p,g,h)=>{let w=DS(p,h);if(!w)return;let v=NS(o,w);if(v.kind==="cancel"){l("cancel");return}if(v.kind==="back"){l("back");return}if(v.kind==="resolve"){l(v.action);return}v.selected!==o&&(o=v.selected,i())};t.grabInput({}),t.on("key",u),t.on("resize",f)})}function DS(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function Mm(t,e,n){let s=Oe(e.sessionId),r=e.title??$e(e.cwd),o=1,i=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=ms(t,{contentHeight:11,title:"Open session"}),c=d.contentW,l=0;t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" session: "),t.noFormat(fc(s,c-10)),l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" "+fc(r,c-2)),l++,l++,t.moveTo(d.contentX,d.contentY+l),t.noFormat(" What do you want to do?"),l+=2;for(let f=0;f<i.length;f++){let u=i[f];if(!u)continue;let g=` ${f===o?"\u276F":" "} ${u.label}`;t.moveTo(d.contentX,d.contentY+l),f===o?t.brightWhite.bgBlue.noFormat($m(g,c)):t.noFormat(g),l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(` ${u.description}`),l++}l++,t.moveTo(d.contentX,d.contentY+l),t.dim.noFormat(" \u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back")};return a(),t.hideCursor(),await new Promise(d=>{let c=!1,l=()=>{c=!0},f=p=>{l(),n.pop(),d(p)},u=(p,g,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(o===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){o>0&&(o--,a());return}if(p==="DOWN"||p==="TAB"){o<i.length-1&&(o++,a());return}if(h?.isCharacter){let w=p.toLowerCase();if(w==="l"){f("launch");return}if(w==="v"){f("view");return}if(w==="n"){o<i.length-1&&(o++,a());return}if(w==="p"){o>0&&(o--,a());return}}};n.push({onKey:(p,g,h)=>{c||u(p,g,h)},onResize:()=>{c||a()}})})}function fc(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function $m(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var fo,pc=V(()=>{"use strict";de();tn();ia();fo=[{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 gc(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function yc(t,e){process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[>5;0m"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1l"),process.stdout.write("\x1B>");let n=e.prefs??gc();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(P=>P.sessionId===e.currentSessionId)?.importedFromMachine&&(n.filters.hostFilter="__all");let s=Fm(e.sessions,e.cwd),r=k=>{let P=k;return n.filters.cwdOnly&&(P=P.filter(F=>F.cwd===e.cwd)),n.filters.includeNonInteractive||(P=P.filter(F=>F.interactive===!0)),P=WS(P,n.filters.hostFilter),P},o=r(s),i={columns:e.config.tui.sessionColumns??ir,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},a=o.map(k=>dr(k,Date.now())),d=cr(a,i),c=1+o.length,l=0,f=0;if(e.currentSessionId!==void 0){let k=o.findIndex(P=>P.sessionId===e.currentSessionId);k>=0&&(l=k+1)}let u=!1,p="",g=120,h=!1,w=0,v="normal",b=null,x=!1,E="input",$=new bn({history:[],collapsePastes:!1}),K=[],te=!1,J=0,D=0,_=null,H=!1,q="",z=null,be=!1,xe=new bn({history:[]});e.initialPrompt&&xe.setBuffer(e.initialPrompt);let X=e.config.tui.promptHistoryMaxEntries;Ur(T.globalTuiHistoryFile()).then(k=>{let P=k.length>X?k.slice(k.length-X):k;xe.setHistory(P)}).catch(()=>{});let Ae=hc(t),Y=hs(t),ge=0,wr="",In=0,et=[],xt=1,Sn=0,ue=0,ys=0,br="",ws=[],on=1,qn=0,bs=[],Ye=1,kn=0,Te=0,Ot=0,lt=()=>{Ae=hc(t),Y=hs(t);let k=Math.max(10,Y-mc);In=Math.max(10,Y-_m);let P=Math.max(10,Y-8);wr=qS(e.cwd,P);let F=xe.state();et=vn(F.buffer,In);let Q=jn(et,F,aa);xt=Q.rendered,Sn=Q.windowStart,ue=Q.cursorVisualRow,ys=Q.cursorVisualCol;let ae=6+xt,we=Math.max(3,Ae-ae);ge=Math.min(o.length,we),br=Nn(ar,d,k,i).padEnd(k),ws=a.map(Ce=>Nn(Ce,d,k,i).padEnd(k))},vr=()=>{a=o.map(k=>dr(k,Date.now())),d=cr(a,i),c=1+o.length,lt()},tt=()=>{let k=r(s);u&&p.length>0?o=k.filter(P=>JS(P,p)):o=k,vr(),u?(f=0,l=o.length>0?1:0):l>c-1&&(l=Math.max(0,c-1)),f+ge>o.length&&(f=Math.max(0,o.length-ge)),Lt()},Wn=k=>{if(k!==void 0){let P=o.findIndex(F=>F.sessionId===k);if(P>=0){l=P+1,Lt();return}}l=o.length>0?1:0,f=0,Lt()},Lt=()=>{if(l===0)return;let k=l-1;k<f?f=k:k>=f+ge?f=k-ge+1:f+ge>o.length&&(f=Math.max(0,o.length-ge))},zn=()=>Math.max(2,Y-2),vs=()=>{let k=zn(),P=`\u2500 ${wr} `,F=Math.max(1,k-P.length),Q="\u2500".repeat(F);l===0?t.brightBlue.noFormat(`\u256D${P}${Q}\u256E`):t.dim.noFormat(`\u256D${P}${Q}\u256E`)},Is=()=>{let k=zn(),P="\u2500".repeat(k);l===0?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},an=k=>{let P=zn(),F=et[k],Q="";F&&(Q=(xe.state().buffer[F.bufferIdx]??"").slice(F.startCol,F.endCol));let ae=Math.max(0,P-1-Q.length),we=" ".repeat(ae);l===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${Q}${we}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${Q}${we}`),t.dim.noFormat("\u2502"))},xn=k=>{let P=ws[k]??"";l===k+1?t.brightWhite.bgBlue.noFormat(`\u276F ${P}`):t.noFormat(` ${P}`)},dn=()=>{let k=f,P=Math.max(0,o.length-f-ge),F=[];return n.filters.cwdOnly&&F.push("cwd-only"),n.filters.hostFilter!=="__all"&&F.push(n.filters.hostFilter==="__local"?"host: local":`host: ${n.filters.hostFilter}`),n.filters.includeNonInteractive&&F.push("+non-interactive"),k>0&&F.push(`\u2191 ${k} above`),P>0&&F.push(`\u2193 ${P} below`),F.length===0?"":` ${F.join(" \xB7 ")}`},Wt=k=>Oe(k),Se=()=>{Re(()=>{if(t.moveTo(1,Ir()),v==="confirm-kill"&&b)t.brightYellow.noFormat(` kill ${Wt(b.sessionId)}? [y/N]`);else if(v==="confirm-delete"&&b)b.status==="live"?t.brightRed.noFormat(` kill + delete ${Wt(b.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Wt(b.sessionId)}? [y/N]`);else if(v==="busy"&&b)t.dim.noFormat(` working on ${Wt(b.sessionId)}\u2026`);else if(v==="rename"&&b)t.brightYellow.noFormat(` title: ${q}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(z!==null)t.dim.noFormat(` ${z}`);else if(u){t.brightYellow.noFormat(` /${p}`),t.bgBrightYellow(" ");let k=o.length===0?" no matches":` ${o.length} match${o.length===1?"":"es"}`;t.dim.noFormat(`${k} \xB7 ^c clears`)}else t.dim.noFormat(dn());t.styleReset(),t.eraseLineAfter()})},nt=k=>on+1+k,At=()=>on+xt+1,ut=()=>on+xt+3,ye=k=>ut()+1+(k-f),Ir=()=>ut()+1+ge,ft=()=>{let k=ue-Sn;if(k<0||k>=xt)return;let P=3+ys;t.moveTo(P,nt(k))},ke=()=>{Re(()=>{t.hideCursor(),lt(),Lt(),on=1,t.moveTo(1,1).eraseDisplayBelow(),vs(),t(`
|
|
157
157
|
`);for(let k=0;k<xt;k++)an(Sn+k),t(`
|
|
158
|
-
`);
|
|
158
|
+
`);Is(),t(`
|
|
159
159
|
|
|
160
160
|
`),t.dim.noFormat(` ${br}`)(`
|
|
161
161
|
`);for(let k=0;k<ge;k++)xn(f+k),t(`
|
|
162
162
|
`);Se(),t(`
|
|
163
|
-
`),l===0&&(ft(),t.hideCursor(!1))})},
|
|
163
|
+
`),l===0&&(ft(),t.hideCursor(!1))})},Jn=()=>{Re(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
|
|
164
164
|
|
|
165
|
-
`);for(let k of
|
|
166
|
-
`);continue}let[P,F]=k;t.brightCyan.noFormat(` ${P.padEnd(
|
|
165
|
+
`);for(let k of jS){if(k===null){t(`
|
|
166
|
+
`);continue}let[P,F]=k;t.brightCyan.noFormat(` ${P.padEnd(US)}`),t.noFormat(F)(`
|
|
167
167
|
`)}t(`
|
|
168
168
|
`),t.dim.noFormat(" press any key to dismiss")(`
|
|
169
|
-
`)})},Qe=()=>Ye+4,S=2,De=0,cn=()=>{Ae=
|
|
170
|
-
`);Re(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),
|
|
171
|
-
`),
|
|
172
|
-
`);ln="";let we=P.slice(Q+bo.length);if(
|
|
173
|
-
`)},Ge=()=>{if(P||we.length>1||v!=="normal"||u||Q||ae)return;let M=l>0?o[l-1]?.sessionId:void 0;Q=!0,Dt(M,{silent:!0}).finally(()=>{Q=!1})},mt=()=>{P||(F&&clearInterval(F),F=setInterval(Ge,3e3))},ht=()=>(He(),k({kind:be?"exit":"abort"}),!0),
|
|
169
|
+
`)})},Qe=()=>Ye+4,S=2,De=0,cn=()=>{Ae=hc(t);let k=Math.max(2,Ae-(Ye+3)-S);return Math.max(1,Math.floor(k/2))},Sr=()=>{let k=cn();J<De?De=J:J>=De+k&&(De=J-k+1),De+k>K.length&&(De=Math.max(0,K.length-k)),De<0&&(De=0)},Kn=k=>{Y=hs(t);let P=Math.max(2,Y-2),F="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,P-F.length));k?t.brightBlue.noFormat(`\u256D${F}${Q}\u256E`):t.dim.noFormat(`\u256D${F}${Q}\u256E`),t.styleReset()},Ct=()=>{Y=hs(t),qn=Math.max(10,Y-_m);let k=$.state();bs=vn(k.buffer,qn);let P=jn(bs,k,HS);Ye=P.rendered,kn=P.windowStart,Te=P.cursorVisualRow,Ot=P.cursorVisualCol},Ss=(k,P)=>{Y=hs(t);let F=Math.max(2,Y-2),Q=bs[k],ae="";Q&&(ae=($.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let we=Math.max(0,F-1-ae.length),Ce=" ".repeat(we);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${ae}${Ce}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${ae}${Ce}`),t.dim.noFormat("\u2502")),t.styleReset()},ho=k=>{Y=hs(t);let P=Math.max(2,Y-2),F="\u2500".repeat(P);k?t.brightBlue.noFormat(`\u2570${F}\u256F`):t.dim.noFormat(`\u2570${F}\u256F`),t.styleReset()},Vn=()=>3+Ot,An=()=>2+(Te-kn),zt=()=>{let k=E==="input";Re(()=>{k&&t.hideCursor(),t.moveTo(1,1),Kn(k);for(let P=0;P<Ye;P++)t.moveTo(1,2+P),Ss(kn+P,k);t.moveTo(1,2+Ye),ho(k),k&&(t.moveTo(Vn(),An()),t.hideCursor(!1))})},kr=()=>{Re(()=>{t.hideCursor();for(let k=0;k<Ye;k++)t.moveTo(1,2+k),Ss(kn+k,!0);t.moveTo(Vn(),An()),t.hideCursor(!1)})},ua={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},go=(k,P)=>{let F=K[k];if(!F)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=hs(t),ae=Math.max(20,Q-mc),we=Oe(F.sessionId),Ce=F.title??$e(F.cwd),Nt=P&&F.snippets.length>1?` [${D+1}/${F.snippets.length}]`:P&&F.totalMatches>F.snippets.length?` [${F.snippets.length} of ${F.totalMatches}]`:"",Kt=`${we} ${F.status==="live"?"live":"cold"}`,Ve=Math.max(5,ae-Kt.length-Nt.length-2),pt=eo(Ce,Ve),He=`${Kt} ${pt}${Nt}`.padEnd(ae),Ge=F.snippets[P?D:0],mt=Ge?ua[Ge.kind]??Ge.kind:"",ht=Ge?.toolName?`${mt} \xB7 ${Ge.toolName}`:mt,Yn=Math.max(10,ae-ht.length-6),Dt=Ge?eo(Ge.text,Yn):"",Es=Ge?` ${ht} ${Dt}`:" (no snippet)";return{rowBudget:ae,line1:He,line2:Es.padEnd(ae+mc),focusedRow:P}},xr=(k,P)=>{let{line1:F,focusedRow:Q}=go(k,P);Q?t.brightWhite.bgBlue.noFormat(`\u276F ${F}`):t.noFormat(` ${F}`),t.styleReset()},Ar=(k,P)=>{let{line2:F}=go(k,P);t.dim.noFormat(F),t.styleReset()},ks=()=>{if(H)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(_!==null)t.brightRed.noFormat(` ${_}`),t.styleReset(),t.eraseLineAfter();else if(E==="input")K.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let k=K.length,P=te?" \xB7 truncated":"",F=k>0?` ${k} ${k===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${F}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},je=()=>{Ct();let k=E==="input",P=$.state().buffer.join(`
|
|
170
|
+
`);Re(()=>{t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),Kn(k);for(let Q=0;Q<Ye;Q++)t.moveTo(1,2+Q),Ss(kn+Q,k);t.moveTo(1,2+Ye),ho(k);let F=K.length;if(F===0)t.moveTo(1,Qe()),H||(_===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):_===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,Qe()+1),ks();else{Sr();let Q=cn(),ae=E!=="input";for(let we=0;we<Q;we++){let Ce=De+we;t.moveTo(1,Qe()+we*2),Ce<F?xr(Ce,ae&&Ce===J):t.eraseLineAfter(),t.moveTo(1,Qe()+we*2+1),Ce<F?Ar(Ce,ae&&Ce===J):t.eraseLineAfter()}t.moveTo(1,Qe()+Q*2),ks()}k&&(t.moveTo(Vn(),An()),t.hideCursor(!1))})},Ke=(k,P)=>{let F=k-De;F<0||F>=cn()||Re(()=>{t.moveTo(1,Qe()+F*2),xr(k,P),t.moveTo(1,Qe()+F*2+1),Ar(k,P)})},xs=()=>{Re(()=>{t.moveTo(1,Qe()+cn()*2),ks()})},Cr=()=>{Re(()=>{let k=cn(),P=K.length,F=E!=="input";for(let Q=0;Q<k;Q++){let ae=De+Q;t.moveTo(1,Qe()+Q*2),ae<P?xr(ae,F&&ae===J):t.eraseLineAfter(),t.moveTo(1,Qe()+Q*2+1),ae<P?Ar(ae,F&&ae===J):t.eraseLineAfter()}t.moveTo(1,Qe()+k*2),ks()})},As=()=>$.state().buffer.join(`
|
|
171
|
+
`),Cs=k=>{let P=Ye;$.feed({type:"paste",text:k}),Ct(),Ye!==P?je():kr()},Rr=async()=>{let k=As().trim();if(k.length!==0){if(o.length===0){_="no sessions in view to search",je();return}H=!0,_=null,je();try{let P=await Kf(e.target,k,{sessionIds:o.map(F=>F.sessionId)});K=P.results,te=P.truncated,J=0,D=0,De=0,E=P.results.length>0?"results":"input",Ct()}catch(P){_=`search failed: ${P.message}`}finally{H=!1,je()}}},Tr=()=>{},fa=()=>{Re(()=>{let k=l===0;k&&t.hideCursor(),t.moveTo(1,on),vs(),t.moveTo(1,At()),Is();for(let P=0;P<xt;P++)t.moveTo(1,nt(P)),an(Sn+P);k&&(ft(),t.hideCursor(!1))})},yo=()=>{Re(()=>{let k=xe.state();et=vn(k.buffer,In);let P=jn(et,k,aa);Sn=P.windowStart,ue=P.cursorVisualRow,ys=P.cursorVisualCol;let F=l===0;F&&t.hideCursor();for(let Q=0;Q<xt;Q++)t.moveTo(1,nt(Q)),an(Sn+Q);F&&(ft(),t.hideCursor(!1))})},Rs=k=>{k<f||k>=f+ge||Re(()=>{t.moveTo(1,ye(k)),xn(k)})},Bt=()=>{Re(()=>{for(let k=0;k<ge;k++){let P=ut()+1+k,F=f+k;F<o.length?(t.moveTo(1,P),xn(F)):t.moveTo(1,P).eraseLineAfter()}Se()})},wo=()=>{Re(()=>{t.moveTo(1,ut()),t.dim.noFormat(` ${br}`);for(let k=0;k<ge;k++){let P=ut()+1+k,F=f+k;F<o.length?(t.moveTo(1,P),xn(F)):t.moveTo(1,P).eraseLineAfter()}Se(),l===0&&(ft(),t.hideCursor(!1))})},Jt=!1,ln="",st=null,Er=null,Pr="\x1B[200~",bo="\x1B[201~",Ts=k=>{let P=k.toString("binary");if(!Jt&&P===""&&Er){Er();return}if(Jt){let Q=P.indexOf(bo);if(Q===-1){ln+=P;return}ln+=P.slice(0,Q),Jt=!1;let ae=Buffer.from(ln,"binary").toString("utf-8").replace(/\r\n?/g,`
|
|
172
|
+
`);ln="";let we=P.slice(Q+bo.length);if(x)E==="input"&&!H&&Cs(ae);else if(l===0&&!u){xe.feed({type:"paste",text:ae});let Ce=xe.state(),Nt=vn(Ce.buffer,In);jn(Nt,Ce,aa).rendered!==xt?ke():yo()}we.length>0&&st&&st(Buffer.from(we,"binary"));return}let F=P.indexOf(Pr);if(F===-1){st?.(k);return}F>0&&st?.(Buffer.from(P.slice(0,F),"binary")),P=P.slice(F+Pr.length),Jt=!0,P.length>0&&Ts(Buffer.from(P,"binary"))};return ke(),await new Promise(k=>{let P=!1,F=null,Q=!1,ae=!1,we=[],Ce=M=>{we.push(M)},Nt=()=>{we.pop(),P||we[we.length-1]?.onResize()},Kt={push:Ce,pop:Nt};Tr=()=>{$=new bn({history:[],collapsePastes:!1}),K=[],te=!1,J=0,D=0,De=0,_=null,H=!1,E="input",x=!1,Nt()};let Ve=(M,j,ee)=>{mt(),we[we.length-1]?.onKey(M,j,ee)},pt=()=>{P||we[we.length-1]?.onResize()},He=()=>{if(P)return;P=!0,we.length=0,F&&(clearInterval(F),F=null),t.off("key",Ve),t.off("resize",pt),process.stdout.write("\x1B[?2004l");let M=t;M.stdin&&st&&(M.stdin.removeListener("data",Ts),M.stdin.on("data",st),st=null),Jt=!1,ln="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,Ir()+1),t(`
|
|
173
|
+
`)},Ge=()=>{if(P||we.length>1||v!=="normal"||u||Q||ae)return;let M=l>0?o[l-1]?.sessionId:void 0;Q=!0,Dt(M,{silent:!0}).finally(()=>{Q=!1})},mt=()=>{P||(F&&clearInterval(F),F=setInterval(Ge,3e3))},ht=()=>(He(),k({kind:be?"exit":"abort"}),!0),Yn=()=>{let M=a.map(j=>`${j.session}|${j.upstream}|${j.host}|${j.state}|${j.agent}|${j.model}|${j.age}|${j.title}|${j.cwd}|${j.cost}`).join(`
|
|
174
174
|
`);return`${l}:${f}:${z??""}
|
|
175
|
-
${M}`},Dt=async(M,
|
|
175
|
+
${M}`},Dt=async(M,j={})=>{try{let ee=j.silent?Yn():"",O=c,se=await yn(e.target,{includeNonInteractive:!0}),ne=M??(l>0?o[l-1]?.sessionId:void 0);if(s=Fm(se,e.cwd),tt(),ne!==void 0){let fe=o.findIndex(Rt=>Rt.sessionId===ne);fe>=0?l=fe+1:l=0}if(l>c-1&&(l=Math.max(0,c-1)),f+ge>o.length&&(f=Math.max(0,o.length-ge)),Lt(),j.silent&&Yn()===ee)return;c===O?wo():ke()}catch(ee){if(j.silent)return;z=`refresh failed: ${ee.message}`,ke()}},Es=async M=>{if(!b)return;let j=b;v="busy",Se();try{await zf(e.target,j.sessionId,M),v="normal",b=null,q="",await Dt(j.sessionId)}catch(ee){v="normal",b=null,q="",z=`rename failed: ${ee.message}`,Se()}},pa=async M=>{try{await Jf(e.target,M.sessionId),z="title regen queued (press r to refresh)",Se()}catch(j){z=`regen failed: ${j.message}`,Se()}},vo=async()=>{if(ae)return;ae=!0;let M=l>0?o[l-1]?.sessionId:void 0;z="syncing agents\u2026",Se();try{let{synced:j,skipped:ee,agents:O}=await Uf(e.target);await Dt(M),z=`synced ${j} new (${ee} known) from ${O} agent${O===1?"":"s"}`,Se()}catch(j){z=`sync failed: ${j.message}`,Se()}finally{ae=!1}},Io=async M=>{if(!b)return;let j=b;v="busy",Se();try{M==="kill"?await Wf(e.target,j.sessionId):await Vf(e.target,j.sessionId),v="normal",b=null,j.sessionId===e.currentSessionId&&(be=!0);let ee;if(M==="kill")ee=j.sessionId;else{let O=o.findIndex(se=>se.sessionId===j.sessionId);O>=0&&(ee=o[O+1]?.sessionId??o[O-1]?.sessionId)}await Dt(ee)}catch(ee){v="normal",b=null,z=`${M} failed: ${ee.message}`,Se()}},gt=(M,j)=>{M===0!=(j===0)&&(fa(),j===0?(t.hideCursor(!1),ft()):t.hideCursor())},qe=M=>{let j=Math.min(c-1,Math.max(0,l+M));if(j===l)return;let ee=l;l=j,Lt(),Re(()=>{Bt(),gt(ee,l)})},un=()=>z===null?!1:(z=null,Se(),!0),Cn=()=>{Jn(),Ce({onKey:M=>{if(M==="CTRL_C"){He(),k({kind:"abort"});return}Nt()},onResize:()=>Jn()})},fn=M=>{let j=null,ee=null,O=!0,se=()=>{Re(()=>{if(t.hideCursor(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${Oe(M.sessionId)}`)(`
|
|
176
176
|
|
|
177
177
|
`),O)t.dim.noFormat(" loading\u2026")(`
|
|
178
178
|
`);else if(ee!==null)t.brightRed.noFormat(` ${ee}`)(`
|
|
179
|
-
`);else if(
|
|
179
|
+
`);else if(j!==null)for(let ne of j)t.noFormat(` ${ne}`)(`
|
|
180
180
|
`);t(`
|
|
181
181
|
`),t.dim.noFormat(" Esc / ^C to return")(`
|
|
182
|
-
`)})};se(),Ce({onKey:ne=>{if(ne==="ESCAPE"||ne==="CTRL_C"){Nt();return}},onResize:()=>se()}),(async()=>{try{let ne=await fetch(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(M.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`}});if(!ne.ok)throw new Error(`daemon returned HTTP ${ne.status}`);let fe=await ne.json(),Rt=qt(fe),We=
|
|
183
|
-
`)}catch(ne){ee=`failed to load info: ${ne.message}`}finally{O=!1,se()}})()},
|
|
184
|
-
`),process.once("SIGCONT",
|
|
182
|
+
`)})};se(),Ce({onKey:ne=>{if(ne==="ESCAPE"||ne==="CTRL_C"){Nt();return}},onResize:()=>se()}),(async()=>{try{let ne=await fetch(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(M.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`}});if(!ne.ok)throw new Error(`daemon returned HTTP ${ne.status}`);let fe=await ne.json(),Rt=qt(fe),We=Nd(Rt,M.status);j=qi(We,!1).replace(/\n$/,"").split(`
|
|
183
|
+
`)}catch(ne){ee=`failed to load info: ${ne.message}`}finally{O=!1,se()}})()},Qn=()=>{if(o.length===0){z="no sessions to search",Se();return}$=new bn({history:[],collapsePastes:!1}),K=[],te=!1,J=0,D=0,De=0,_=null,H=!1,E="input",x=!0,Ct(),je(),Ce({onKey:(j,ee,O)=>{if(E==="input"){if(H)return;if(j==="ESCAPE"||j==="CTRL_C"){Tr();return}if(j==="ENTER"||j==="KP_ENTER"){if(As().trim().length===0)return;Rr();return}if((j==="DOWN"||j==="TAB"||j==="CTRL_N")&&K.length>0){E="results",J=0,D=0,Re(()=>{zt(),Ke(0,!0),xs(),t.hideCursor()});return}let se=$.state(),ne=null;if(O?.isCharacter)ne={type:"char",ch:j};else{let yt=oa(j);yt!==null&&(ne={type:"key",name:yt})}if(ne===null){t.moveTo(Vn(),An());return}$.feed(ne);let fe=$.state();if(se.buffer.length===fe.buffer.length&&se.buffer.every((yt,Me)=>yt===fe.buffer[Me])&&se.row===fe.row&&se.col===fe.col){t.moveTo(Vn(),An());return}let We=Ye;Ct(),Ye!==We?je():kr();return}if(E==="results"){if(j==="ESCAPE"||j==="CTRL_C"){Tr();return}if(j==="CTRL_F"){E="input",Cr(),xs(),zt();return}if(j==="ENTER"||j==="KP_ENTER"){let ne=K[J];if(!ne)return;let fe=o.find(We=>We.sessionId===ne.sessionId);if(!!fe?.importedFromMachine&&!fe.upstreamSessionId){He();let We={kind:"attach",sessionId:ne.sessionId};fe.agentId!==void 0&&(We.agentId=fe.agentId),k(We);return}(async()=>{let We=await Mm(t,{sessionId:ne.sessionId,title:ne.title,cwd:ne.cwd},Kt);if(We==="cancel"){He(),k({kind:"abort"});return}if(We==="back")return;He();let yt={kind:"attach",sessionId:ne.sessionId,readonly:We==="view"};fe?.agentId!==void 0&&(yt.agentId=fe.agentId),k(yt)})();return}if(O?.isCharacter&&(j==="n"||j==="N")){let ne=K[J];if(!ne||ne.snippets.length<=1)return;D=(D+1)%ne.snippets.length,Ke(J,!0);return}if(O?.isCharacter&&(j==="p"||j==="P")){let ne=K[J];if(!ne||ne.snippets.length<=1)return;D=(D-1+ne.snippets.length)%ne.snippets.length,Ke(J,!0);return}let se=ne=>{if(ne<0&&J===0){E="input",Re(()=>{Ke(0,!1),xs(),zt()});return}let fe=Math.min(K.length-1,Math.max(0,J+ne));if(fe===J)return;let Rt=J,We=De;J=fe,D=0,Sr(),De!==We?Cr():(Re(()=>{Ke(Rt,!1),Ke(J,!0)}),xs())};switch(j){case"UP":case"SHIFT_TAB":case"CTRL_P":se(-1);return;case"DOWN":case"TAB":case"CTRL_N":se(1);return;case"PAGE_UP":se(-cn());return;case"PAGE_DOWN":se(cn());return;case"HOME":se(-J);return;case"END":se(K.length);return}return}},onResize:()=>je()})},pn=(M,j,ee)=>{if(v!=="busy"){if(v==="rename"){if(M==="ENTER"||M==="KP_ENTER"){let O=q.trim();if(O.length===0){v="normal",b=null,q="",Se();return}Es(O);return}if(M==="ESCAPE"||M==="CTRL_C"){v="normal",b=null,q="",Se();return}if(M==="BACKSPACE"){q.length>0&&(q=q.slice(0,-1),Se());return}if(M==="CTRL_U"){q="",Se();return}if(M==="CTRL_W"){let O=q.replace(/\s+$/,""),se=O.lastIndexOf(" ");q=se>=0?O.slice(0,se):"",Se();return}if(ee?.isCharacter){q+=M,Se();return}return}if(v==="confirm-kill"||v==="confirm-delete"){if(ee?.isCharacter&&(M==="y"||M==="Y")){Io(v==="confirm-kill"?"kill":"delete");return}if(M==="ESCAPE"||M==="CTRL_C"||M==="ENTER"||M==="KP_ENTER"||ee?.isCharacter&&(M==="n"||M==="N")){v="normal",b=null,Se();return}return}if(un(),M==="CTRL_F"){Qn();return}if(l===0&&!u){if(M==="ESCAPE"){ht();return}if(M==="ENTER"||M==="KP_ENTER"){He();let Me=xe.expandedText();Me.trim().length===0?k({kind:"new"}):k({kind:"new",prompt:Me});return}if(M==="UP"&&h){let Me=Date.now(),Vt=Me-w;if(w=Me,Vt<g){ft();return}h=!1}if(M==="DOWN"){let Me=xe.state(),Vt=Me.historyIndex!==-1||Me.queueIndex!==-1,Xn=et.length===0||ue===et.length-1;if(!Vt&&Xn&&o.length>0){qe(1);return}}if(M==="PAGE_DOWN"&&(et.length===0||ue===et.length-1)&&o.length>0){qe(1);return}if(M==="CTRL_P"){o.length>0&&qe(1);return}h=!1;let O=xe.state(),se=null;if(ee?.isCharacter)se={type:"char",ch:M};else{let Me=oa(M);Me!==null&&(se={type:"key",name:Me})}if(se===null){ft();return}let ne=xe.feed(se),fe=xe.state(),Rt=O.buffer.length===fe.buffer.length&&O.buffer.every((Me,Vt)=>Me===fe.buffer[Vt])&&O.row===fe.row&&O.col===fe.col;if(ne.some(Me=>Me.type==="exit")){ht();return}if(Rt){ft();return}let We=vn(fe.buffer,In);if(jn(We,fe,aa).rendered!==xt){ke();return}yo();return}if(!u&&ee?.isCharacter&&M==="?"){Cn();return}if(u){if(ee?.isCharacter){p+=M,tt(),ke();return}if(M==="BACKSPACE"){p.length>0?(p=p.slice(0,-1),tt(),ke()):(u=!1,tt(),ke());return}if(M==="ESCAPE"||M==="CTRL_C"){u=!1,p="",tt(),ke();return}}if(ee?.isCharacter){if(M==="/"){u=!0,p="",tt(),ke();return}if(M==="n"||M==="N"){qe(1);return}if(M==="p"||M==="P"){qe(-1);return}if(M==="c"||M==="C"){He(),k({kind:"new"});return}if(M==="q"||M==="Q"){ht();return}if(M==="o"||M==="O"){let O=l>0?o[l-1]?.sessionId:void 0;n.filters.cwdOnly=!n.filters.cwdOnly,tt(),Wn(O),ke();return}if(M==="h"||M==="H"){let O=l>0?o[l-1]?.sessionId:void 0;n.filters.hostFilter=zS(n.filters.hostFilter,s),tt(),Wn(O),ke();return}if(M==="i"&&l>0){let O=o[l-1];if(!O)return;fn(O);return}if(M==="I"){let O=l>0?o[l-1]?.sessionId:void 0;n.filters.includeNonInteractive=!n.filters.includeNonInteractive,tt(),Wn(O),ke();return}if(M==="r"||M==="R"){let O=l>0?o[l-1]?.sessionId:void 0;Dt(O);return}if(M==="s"||M==="S"){vo();return}if((M==="v"||M==="V")&&l>0){let O=o[l-1];if(!O)return;He();let se={kind:"attach",sessionId:O.sessionId,readonly:!0};O.agentId!==void 0&&(se.agentId=O.agentId),k(se);return}if((M==="f"||M==="F")&&l>0){let O=o[l-1];if(!O)return;He();let se={kind:"fork",sourceSessionId:O.sessionId,sourceCwd:O.cwd};O.agentId!==void 0&&(se.sourceAgentId=O.agentId),O.importedFromMachine!==void 0&&(se.sourceImportedFromMachine=O.importedFromMachine),O.upstreamSessionId!==void 0&&(se.sourceUpstreamSessionId=O.upstreamSessionId),k(se);return}if((M==="k"||M==="K")&&l>0){let O=o[l-1];if(!O)return;b={sessionId:O.sessionId,cwd:O.cwd,status:O.status},v="confirm-kill",Se();return}if(M==="t"&&l>0){let O=o[l-1];if(!O)return;b={sessionId:O.sessionId,cwd:O.cwd,status:O.status},q=O.title??"",v="rename",Se();return}if(M==="T"&&l>0){let O=o[l-1];if(!O||O.status!=="live")return;pa({sessionId:O.sessionId});return}if((M==="d"||M==="D")&&l>0){let O=o[l-1];if(!O)return;b={sessionId:O.sessionId,cwd:O.cwd,status:O.status},v="confirm-delete",Se();return}return}switch(M){case"UP":case"SHIFT_TAB":case"CTRL_P":M==="UP"&&(l===1&&(h=!0),w=Date.now()),qe(-1);return;case"DOWN":case"TAB":case"CTRL_N":qe(1);return;case"PAGE_UP":qe(-ge);return;case"PAGE_DOWN":qe(ge);return;case"HOME":qe(1-l);return;case"END":qe(c);return;case"ENTER":case"KP_ENTER":{if(He(),l===0){k({kind:"new"});return}let O=o[l-1];if(!O){k({kind:"abort"});return}let se={kind:"attach",sessionId:O.sessionId};O.agentId!==void 0&&(se.agentId=O.agentId),k(se);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":ht();return}}};Ce({onKey:(M,j,ee)=>pn(M,j,ee),onResize:()=>{P||ke()}});let Rn=()=>{t.grabInput({});let M=t;M.stdin&&typeof M.onStdin=="function"&&(st=M.onStdin,M.stdin.removeListener("data",M.onStdin),M.stdin.on("data",Ts),process.stdout.write("\x1B[?2004h")),t.on("key",Ve),t.on("resize",pt)},Gn=()=>{process.stdout.write("\x1B[?2004l");let M=t;M.stdin&&st&&(M.stdin.removeListener("data",Ts),M.stdin.on("data",st),st=null),Jt=!1,ln="",t.off("key",Ve),t.off("resize",pt),t.grabInput(!1),t.hideCursor(!1)};if(Rn(),process.platform!=="win32"){let M=!1,j=()=>{M&&(M=!1,process.stdout.write("\x1B[?1049h"),Rn(),P||ke())};Er=()=>{M||P||(M=!0,Gn(),process.stdout.write(`\x1B[?1049l\x1B[?7h\x1B[?25h
|
|
184
|
+
`),process.once("SIGCONT",j),process.kill(process.pid,"SIGTSTP"))}}F=setInterval(Ge,3e3)})}function hc(t){return t.height??24}function hs(t){return t.width??80}function qS(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+eo($e(t),s)}function Fm(t,e){let n=s=>s.status!=="live"?0:s.awaitingInput?3:s.busy?2:1;return[...t].sort((s,r)=>{let o=n(r)-n(s);return o!==0?o:r.updatedAt.slice(0,16).localeCompare(s.updatedAt.slice(0,16))})}function WS(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function zS(t,e){let n=new Set;for(let o of e)o.importedFromMachine&&!o.upstreamSessionId&&n.add(o.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function JS(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[Oe(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,$e(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var mc,aa,HS,_m,US,jS,Om=V(()=>{"use strict";Bi();de();tn();Fi();ei();Zd();cc();pc();tc();os();Dd();mc=2,aa=4,HS=4,_m=4,US=20,jS=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["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 live session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent (live session)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});function po(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function Lm(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),o=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",d=o.startsWith(" ")?"":" ";return a+d+o}let i=po(e);return i.length<=r.length?null:i+o}var da=V(()=>{"use strict"});import*as Bm from"os";async function mo(t,e,n={}){let s=n.defaultCwd??await gm(e.cwd)??Bm.homedir();yr();let r=Oe(e.sessionId),o=$e(e.cwd),i=n.title??"Fork locally \u2014 choose cwd",a=n.intro??"Pick a local cwd for this session:",d=[{label:"session: ",value:r},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:o}],c=s,l=null,f=!1,u=null,p=()=>{let v=d.length+6;u=ms(t,{contentHeight:v,title:i});let b=u.contentW,x=0;for(let E of d)t.moveTo(u.contentX,u.contentY+x),t.dim.noFormat(` ${E.label}`),t.noFormat(wc(E.value,b-E.label.length-2)),x++;x++,t.moveTo(u.contentX,u.contentY+x),t.noFormat(` ${a}`),x+=2,h(x),x+=2,l!==null?(t.moveTo(u.contentX,u.contentY+x),t.red.noFormat(` ${wc(l,b-2)}`)):(t.moveTo(u.contentX,u.contentY+x),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},g=()=>d.length+3,h=v=>{if(!u)return;let b=v??g();t.moveTo(u.contentX,u.contentY+b).eraseLineAfter(),t.moveTo(u.x+u.w-1,u.contentY+b),t.dim.noFormat("\u2502"),t.moveTo(u.contentX,u.contentY+b),t.bold.noFormat(" cwd: ");let x=u.contentW-6-2;t.noFormat(KS(c,x)),f||t.bgWhite(" ")},w=()=>{if(h(),!u)return;let v=g()+2;t.moveTo(u.contentX,u.contentY+v).eraseLineAfter(),t.moveTo(u.x+u.w-1,u.contentY+v),t.dim.noFormat("\u2502"),t.moveTo(u.contentX,u.contentY+v),l!==null?t.red.noFormat(` ${wc(l,u.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return p(),await new Promise(v=>{let b=!1,x=()=>{b||(b=!0,t.off("key",K),t.off("resize",$),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},E=te=>{x(),v(te)},$=()=>{b||p()},K=(te,J,D)=>{if(!f){if(te==="ENTER"||te==="KP_ENTER"){let _=c;f=!0,l=null,w(),co(_).then(H=>{if(f=!1,H.ok){E({kind:"ok",path:H.path});return}l=H.reason,w()});return}if(te==="ESCAPE"){E({kind:"back"});return}if(te==="CTRL_C"||te==="CTRL_D"){E({kind:"cancel"});return}if(te==="TAB"){f=!0,ym(c).then(_=>{if(f=!1,_.matches.length===0)return;let H;if(_.matches.length===1)H=_.prefix+_.matches[0];else{let q=po(_.matches);if(q.length<=_.basePrefix.length)return;H=_.prefix+q}H!==c&&(c=H,l=null,w())});return}if(te==="BACKSPACE"){c.length>0&&(c=c.slice(0,-1),l=null,w());return}if(te==="CTRL_U"){c="",l=null,w();return}if(te==="CTRL_W"){let _=c.replace(/[/\s]+$/,""),H=Math.max(_.lastIndexOf("/"),_.lastIndexOf(" "));c=H>=0?_.slice(0,H+1):"",l=null,w();return}if(D?.isCharacter){c+=te,l=null,w();return}}};t.grabInput({}),t.on("key",K),t.on("resize",$)})}function wc(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function KS(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var Nm=V(()=>{"use strict";de();tn();Gd();da();ia()});function GS(t){let e=t.findIndex(n=>n.id===VS);return e===-1?0:e}async function Hm(t,e){yr();let n=GS(e),s=0,r=()=>{let a=uc(t)-8;return Math.max(1,Math.min(YS,e.length,a))},o=()=>{let a=r();n<s?s=n:n>=s+a&&(s=n-a+1);let d=Math.max(0,e.length-a);s>d&&(s=d),s<0&&(s=0)},i=()=>{o();let a=r(),d=a+4,c=Math.min(QS,Math.max(40,lc(t)-8)),l=ms(t,{contentHeight:d,contentWidth:c,title:"Select agent"}),f=l.contentW,u=0;t.moveTo(l.contentX,l.contentY+u),t.noFormat(" Which agent should this session use?"),u+=2;let p=Math.min(e.length,s+a);for(let h=s;h<p;h++){let w=e[h];if(!w)continue;let v=h===n?"\u276F":" ",b=w.description??w.name,x=` ${v} ${w.id}`;if(t.moveTo(l.contentX,l.contentY+u),h===n){let E=`${x} ${b}`;t.brightWhite.bgBlue.noFormat(XS(Dm(E,f),f))}else{t.noFormat(x);let E=f-x.length-2;E>1&&t.dim.noFormat(` ${Dm(b,E)}`)}u++}u++,t.moveTo(l.contentX,l.contentY+u);let g=e.length>a?` (${n+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${g}`),l};return i(),t.hideCursor(),await new Promise(a=>{let d=!1,c=()=>{d||(d=!0,t.off("key",g),t.off("resize",f),t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,1).eraseDisplayBelow())},l=h=>{c(),a(h)},f=()=>{d||i()},u=()=>{n<e.length-1&&(n++,i())},p=()=>{n>0&&(n--,i())},g=(h,w,v)=>{if(h==="CTRL_C"||h==="CTRL_D"){l({kind:"cancel"});return}if(h==="ESCAPE"){l({kind:"back"});return}if(h==="ENTER"||h==="KP_ENTER"){let b=e[n];b&&l({kind:"select",agentId:b.id,persist:!1});return}if(h==="UP"||h==="SHIFT_TAB"){p();return}if(h==="DOWN"||h==="TAB"){u();return}if(v?.isCharacter){let b=h.toLowerCase();if(b==="s"){let x=e[n];x&&l({kind:"select",agentId:x.id,persist:!0});return}if(b==="j"){u();return}if(b==="k"){p();return}}};t.grabInput({}),t.on("key",g),t.on("resize",f)})}function Dm(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function XS(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}var VS,YS,QS,Um=V(()=>{"use strict";ia();VS="opencode",YS=20,QS=88});import{spawn as ZS}from"child_process";import bc from"fs/promises";import ek from"os";import tk from"path";async function qm(t={}){let e={...nk,...t};return e.platform==="darwin"?sk(e):e.platform==="linux"?rk(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function sk(t){let e=tk.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await zm(t.spawn,"osascript",s);let r=await ck(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await bc.unlink(e).catch(()=>{})}try{let r=await ca(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Wm(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function rk(t){let e=await ok(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await dk(t,e),s=ak(n);if(s)try{let r=await ca(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>rn?{ok:!1,reason:`clipboard image is ${Ft(r.length)}, max ${Ft(rn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await ca(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Wm(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function ok(t){return t.env.WAYLAND_DISPLAY&&await jm(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await jm(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function ak(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of ik)if(e.has(n))return n;return null}async function dk(t,e){try{return(await ca(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
|
|
185
185
|
`).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Wm(t){return t.replace(/\r\n?/g,`
|
|
186
|
-
`)}async function jm(t,e){try{return await zm(t.spawn,"which",[e]),!0}catch{return!1}}async function
|
|
187
|
-
`))};d();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let f=t;try{for(;f!==null;)f=await
|
|
188
|
-
`),process.stdout.isTTY){let p=await Pi(e);if(p?.version!==void 0){let g=p.version!==le,h=Zs(e),w=p.configDigest!==void 0&&p.configDigest!==h;if(g||w){let v=g?`daemon ${p.version} \u2260 cli ${le}`:"config changed since daemon started",b=
|
|
189
|
-
`)}}}if(r.sessionId&&process.stdout.isTTY){let p=Oe(r.sessionId),g=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${
|
|
190
|
-
`)}}async function dk(t,e,n,s,r,o,i){let a=await ck(t,e,n,s,i);if(!a)return t.grabInput(!1),null;let d=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",c=fk(t,d);c.write(d);let l=n.wsUrl,f=["acp.v1",`hydra-acp-token.${n.token}`],u=null,p=null,g=new mr({url:l,subprotocols:f,onConnect:async m=>{m||u&&await u()},onDisconnect:m=>{p&&p(m)},log:()=>{}}),h=new Zt(g);await g.start(),h.onNotification(Uo,m=>{let y=ql.safeParse(m);y.success&&c.applyProgress(y.data)});let w=[],v=null,b=!1,A=!1,T=m=>{m&&(v?v(m):w.push(m))},$=0,K=!1,te,J=null,D=null,_=null,H=!1,q=m=>{let y=$;$=Math.max(0,$+m);let I=typeof z<"u"&&z!==null;y===0&&$>0?(K=!1,J=Date.now(),_=Date.now(),be?.setTurnRunning(!0),I&&z.setBanner({status:"busy",elapsedMs:0,stalled:!1}),D===null&&I&&(D=setInterval(()=>{if(J===null||z===null)return;let E=_===null?0:Date.now()-_;z.setBanner({elapsedMs:Date.now()-J,stalled:E>=ok}),Tt()},1e3))):y>0&&$===0?(K=!1,J=null,_=null,be?.setTurnRunning(!1),D!==null&&(clearInterval(D),D=null),I&&z.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):$>0&&K&&(K=!1,I&&z.setBanner({status:"busy",stalled:!1}))},z=null,be=null,xe,X=null,Ae=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]),Y=m=>{let{update:y}=m??{},I=ds(y,{cwd:lt});lk(y,I),_=Date.now();let E=y?.sessionUpdate;if(typeof E=="string"&&!Ae.has(E)){let C=y??{};typeof C.messageId=="string"&&(xe=C.messageId)}if(E==="prompt_received"?q(1):I?.kind==="turn-complete"&&q(-1),E==="permission_resolved"){Sn(y);return}T(I),br(y)};h.onNotification("session/update",m=>{if(!b){if(X!==null){X.push(m);return}Y(m)}}),h.onNotification("hydra-acp/session/closed",()=>{if(b)return;$>0&&q(-$),typeof z<"u"&&z!==null&&z.setBanner({status:"cold",elapsedMs:void 0})});let ge=new Map,wr=200,In=0,et=!1,xt=4e3;h.onNotification("hydra-acp/prompt_queue/added",m=>{if(b)return;let y=m??{};if(typeof y.messageId!="string")return;if(typeof y._meta?.["hydra-acp"]?.amending=="string"){let E=y.messageId,C=y.prompt,j=setTimeout(()=>{ge.delete(E),Ve.set(E,Kt(E,C)),z&&be&&ht()},wr);ge.set(E,j)}else Ve.set(y.messageId,Kt(y.messageId,y.prompt)),z&&be&&ht();if(tt!==void 0&&y.originator?.clientId===tt){let E=pt.shift();E&&(E.messageId=y.messageId,He.set(y.messageId,E))}}),h.onNotification("hydra-acp/prompt_queue/updated",m=>{if(b)return;let y=m??{};if(typeof y.messageId!="string"||!Ve.has(y.messageId))return;Ve.set(y.messageId,Kt(y.messageId,y.prompt));let I=He.get(y.messageId);if(I){let E=Array.isArray(y.prompt)?y.prompt:[],C="",j=[];for(let W of E){if(!W||typeof W!="object")continue;let B=W;B.type==="text"&&typeof B.text=="string"?C+=B.text:B.type==="image"&&typeof B.data=="string"&&typeof B.mimeType=="string"&&j.push({data:B.data,mimeType:B.mimeType,sizeBytes:Math.floor(B.data.length*3/4)})}I.text=C,I.attachments=j}z&&be&&ht()}),h.onNotification("hydra-acp/prompt_queue/removed",m=>{if(b)return;let y=m??{};if(typeof y.messageId!="string")return;y.reason==="started"&&(te=y.messageId);let I=ge.get(y.messageId);I!==void 0&&(clearTimeout(I),ge.delete(y.messageId)),Ve.delete(y.messageId)&&z&&be&&ht();let C=He.get(y.messageId);C&&(He.delete(y.messageId),y.reason==="started"&&(C.flushed=!0,T({kind:"user-text",text:C.displayText,attachments:C.attachments}),mt=C))}),h.onNotification("hydra-acp/cancel_failed",m=>{if(b)return;let y=m??{};if(!(typeof z<"u"&&z!==null))return;In=Date.now(),et=!0;let E=typeof y.code=="number"?` (${y.code})`:"",C=typeof y.message=="string"&&y.message.length>0?`: ${y.message}`:"";z.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${E}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",m=>{if(b)return;let y=m??{};if(typeof y.cancelledMessageId!="string")return;let I=y.cancelledMessageId;Ge.add(I),mt!==null&&mt.messageId!==void 0&&mt.messageId===I&&(T({kind:"turn-complete",stopReason:"cancelled",amended:!0}),mt=null,Ge.delete(I))});let Sn=m=>{let y=m??{},I=typeof y.toolCallId=="string"?y.toolCallId:void 0,E;y.outcome&&typeof y.outcome=="object"?E=y.outcome:typeof y.chosenOptionId=="string"&&(E={kind:"selected",optionId:y.chosenOptionId}),ws(I,E?{outcome:E}:void 0)},ue=null,ws=(m,y)=>{if(!ue||ue.toolCallId&&m&&ue.toolCallId!==m)return;let I=ue.resolve;ue=null,S.setPermissionPrompt(null),I(y??{outcome:{outcome:"cancelled"}})},br=m=>{if(!ue?.toolCallId)return;let y=m??{};y.sessionUpdate!=="tool_call"&&y.sessionUpdate!=="tool_call_update"||y.toolCallId===ue.toolCallId&&(!y.status||y.status==="pending"||ws(y.toolCallId,void 0))},bs=()=>{if(!ue){S.setPermissionPrompt(null);return}S.setPermissionPrompt({title:ue.title,detail:ue.detail,options:ue.options.map(m=>({label:m.name})),selectedIndex:ue.selectedIndex})},on=m=>{if(!ue)return;let{options:y,resolve:I}=ue;if(ue=null,S.setPermissionPrompt(null),m===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:m}})};h.onRequest("session/request_permission",async m=>{if(b)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return us(m);let y=m??{},E=(Array.isArray(y.options)?y.options:[]).map(Z=>({optionId:Z.optionId,name:Ie(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),C=y.toolCall?.title??y.toolCall?.name??"tool",j=Ie(C),W=Ie(im(om(m))),B=y.toolCall?.toolCallId;return E.length===0?(S.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${j} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Z=>{ue={title:j,detail:W,options:E,selectedIndex:0,resolve:Z,toolCallId:B},bs()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Wn,vs,Ye=!0,kn=!1;try{let m=await h.request("initialize",{protocolVersion:It,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:le}});vs=m?.agentInfo?.name,m?.agentCapabilities?.promptCapabilities?.image===!1&&(Ye=!1),kn=St(m?._meta??void 0).prompt?.amending===!0}catch{}let Te=a.sessionId,Ot=a.agentId,lt=a.cwd,vr,tt,zn,Lt,Jn,Is,Ss,an,xn,dn;if(a.sessionId==="__new__"){let m={};s.agentId&&(m.agentId=s.agentId),s.name&&(m.title=s.name),s.model&&(m.model=s.model);let y=await h.request("session/new",{cwd:a.cwd,...Object.keys(m).length>0?{_meta:{[Mt]:m}}:{}});Te=y.sessionId,r.sessionId=Te,r.readonly=!1;let I=St(y._meta??void 0);I.clientId&&(tt=I.clientId),Wn=I.upstreamSessionId,I.agentId&&(Ot=I.agentId),I.cwd&&(lt=I.cwd),I.title&&(vr=I.title),zn=I.currentModel,Lt=I.currentMode,xn=I.currentUsage,dn=I.turnStartedAt,I.availableCommands&&(Jn=wi(I.availableCommands)),I.availableModes&&(Is=I.availableModes),Ss=rh(y.configOptions),an=I.queue}else{let m={};s.readonly===!0&&(m.readonly=!0),e.tui.toolContent==="references"&&(m.toolContent="references"),s.drip===!0&&(m.replayMode="drip",s.dripSpeed!==void 0&&(m.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(m.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let y=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:le},...Object.keys(m).length>0?{_meta:{[Mt]:m}}:{}});Te=y.sessionId,y.clientId&&(tt=y.clientId),r.sessionId=Te,r.readonly=s.readonly===!0;let I=St(y._meta??void 0);Wn=I.upstreamSessionId,I.agentId&&(Ot=I.agentId),I.cwd&&(lt=I.cwd),I.title&&(vr=I.title),zn=I.currentModel,Lt=I.currentMode,xn=I.currentUsage,dn=I.turnStartedAt,I.availableCommands&&(Jn=wi(I.availableCommands)),I.availableModes&&(Is=I.availableModes),Ss=rh(y.configOptions),an=I.queue}let Wt=R.tuiHistoryFile(Te),Se=R.globalTuiHistoryFile(),nt=await Ur(Wt).catch(()=>[]),At=await Ur(Se).catch(()=>[]);At.length>e.tui.promptHistoryMaxEntries&&(At=At.slice(At.length-e.tui.promptHistoryMaxEntries));let ut=[...nt],ye=new bn({history:Zo(At,ut)});be=ye;let Ir=!1,ft=(m,y)=>{let I=m.replace(/\n+$/,"");if(I.length===0)return;let E=(y??m).replace(/\n+$/,""),C=jr(nt,I),j=C!==nt;nt=C,ut=jr(ut,E);let W=jr(At,I,e.tui.promptHistoryMaxEntries),B=W!==At;At=W,ye.setHistory(Zo(At,ut)),j&&os(Wt,nt).catch(()=>{}),B&&Cu(Se,I).catch(()=>{})};$>0&&ye.setTurnRunning(!0);let ke=null,Kn=null;Rm(e.tui.ambiguousWidth==="wide"),hp(e.tui.diffContextLines);let Qe=!1,S,De=()=>{Qe&&(Qe=!1,S.start())},cn=()=>{Qe||(Qe=!0,S.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",De),S=new ra({term:t,dispatcher:ye,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:o.mouseEnabled,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?cn:void 0,onBlockClick:m=>{Eh(m)},onBlockVisible:m=>{Rh(m)},onKey:m=>{for(let y of m){if(ue&&Ar(y)||yo(y)||Es(y)||xr(y)||ua(y))continue;if(y.type==="attachment-paths"){we(y.paths);continue}let I=ye.feed(y);for(let E of I)s.readonly===!0&&ik(E)||ae(E)}kr(),S.setBannerSearchIndicator(ye.state().historySearchQuery),S.setAttachments(ye.state().attachments),S.refreshPrompt()}}),z=S,S.setStickyBottomKey("plan");let Sr=[{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:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/demo-plan",description:"Inject synthetic plan events (UI test)"},{name:"/demo-tool",description:"Inject a synthetic tool-call sequence (UI test)"}],Vn=Jn??[],Ct=Is??[],ks=Ss??[],ho=()=>ks.find(m=>m.id==="agent"),Yn=()=>{let m=new Set,y=[];for(let I of[...Sr,...Vn])m.has(I.name)||(m.add(I.name),y.push(I));return y},An=()=>{let m=ye.state().buffer,y=m[0]??"";if(!y.startsWith("/"))return[];if(m.length>1)return[];let I=y.indexOf(" "),E=I===-1?y:y.slice(0,I);if(E.lastIndexOf("/")>0)return[];let C=Yn().filter(j=>j.name.startsWith(E));return C.length===1&&C[0]?.name===E&&I===-1?[]:C},zt=[],kr=()=>{let m=An();if(m.length>0){zt=[],S.setCompletions(m);return}S.setCompletions(zt)},ua=m=>{if(m.type!=="key"||m.name!=="tab")return zt.length>0&&(zt=[]),!1;let y=An();if(y.length>0){zt=[];let I=ye.state().buffer[0]??"",E=Lm({matches:y.map(C=>C.name),firstLine:I});return E===null||ye.replaceFirstLine(E),!0}return go()},go=()=>{let m=ye.state(),y=m.buffer[m.row]??"",I=Qm(y,m.col);if(I===null)return!1;let E=Gm(I.token,lt);return E===null?!1:(E.replacement!==I.token&&ye.replaceRangeOnCurrentLine(I.start,m.col,E.replacement),zt=E.candidates.length>1?E.candidates.map(C=>({name:C})):[],!0)},xr=m=>{if(!S.isScrollbackSearchActive())return m.type==="key"&&m.name==="ctrl-r"&&S.isScrolledBack()?(S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(""),!0):!1;if(m.type==="char"){let y=S.scrollbackSearchTerm()+m.ch;return S.updateScrollbackSearchTerm(y),!0}if(m.type==="paste"){let y=S.scrollbackSearchTerm()+m.text.replace(/\n/g," ");return S.updateScrollbackSearchTerm(y),!0}if(m.type==="key")switch(m.name){case"ctrl-r":return S.advanceScrollbackSearch(),!0;case"ctrl-s":return S.retreatScrollbackSearch(),!0;case"backspace":{let y=S.scrollbackSearchTerm();return y.length===0?S.cancelScrollbackSearch():S.updateScrollbackSearchTerm(y.slice(0,-1)),!0}case"enter":return S.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return S.cancelScrollbackSearch(),!0;default:return!0}return!0},Ar=m=>{if(!ue)return!1;let y=ue.options;if(m.type==="key")switch(m.name){case"up":return ue.selectedIndex=Math.max(0,ue.selectedIndex-1),bs(),!0;case"down":return ue.selectedIndex=Math.min(y.length-1,ue.selectedIndex+1),bs(),!0;case"enter":{let I=y[ue.selectedIndex];return I&&on(I.optionId),!0}case"escape":case"ctrl-c":return on(null),!0;default:return!0}if(m.type==="char"&&/^[1-9]$/.test(m.ch)){let I=parseInt(m.ch,10)-1,E=y[I];return E&&on(E.optionId),!0}return!0},xs=Ot||vs||"?",je={...xn??{}};c.finalize(),S.start({skipFullscreen:!0}),S.setHideThoughts(!o.showThoughts),S.setSessionbar({agent:xs,cwd:lt,sessionId:Te,title:vr,model:zn,usage:{...je}}),Lt&&S.setBanner({currentMode:Lt}),oo().then(m=>{m&&S.notify(`\u2728 ${io(m)}`,3e4)});let Ke=null,As=new Promise(m=>{Ke=m}),Cr=()=>{h.notify("session/cancel",{sessionId:Te}).catch(()=>{})},Cs=()=>{z!==null&&$===1&&(K=!0,z.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Rs=()=>{if(ke){ke.cancel(),Cs();return}if($>0){Cr(),Cs();return}Rr()},Rr=()=>{P(0)},Tr=()=>{let m="enqueue prompt (sends now, or queues during a turn)",y="amend the in-flight turn (cancel + replace)";return[...o.defaultEnterAction==="amend"?[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",m]]:[["Enter",m],["Ctrl+Enter / Shift+Enter / ^S",y]],...ak]},fa=()=>{if(S.isHelpPromptActive()){S.setHelpPrompt(null);return}S.setHelpPrompt({title:"Hotkeys",entries:Tr(),hint:"any key dismisses \xB7 /help lists commands"})},yo=m=>S.isHelpPromptActive()?(m.type==="key"&&m.name==="ctrl-g",S.setHelpPrompt(null),!0):!1,Ts=["tools","plan","thoughts","diffs","mouse","enter"],Bt=0,wo=m=>{switch(m){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}},Jt=m=>{switch(m){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"}},ln=()=>({title:"Session options",options:Ts.map(m=>({label:Jt(m),value:wo(m)})),selectedIndex:Bt}),st=()=>{S.isOptionsPromptActive()&&S.setOptionsPrompt(ln())},Er=()=>{if(S.isOptionsPromptActive()){S.setOptionsPrompt(null);return}Bt=0,S.setOptionsPrompt(ln())},Pr=m=>{switch(m){case"tools":o.toolsExpanded=!o.toolsExpanded,Xn.clear(),Ah();break;case"plan":o.planExpanded=!o.planExpanded,fe=null,Me();break;case"thoughts":o.showThoughts=!o.showThoughts,S.setHideThoughts(!o.showThoughts);break;case"diffs":o.showFileUpdates=o.showFileUpdates==="diff"?"edit":"diff",un.clear(),Th();break;case"mouse":{let y=!S.isMouseEnabled();S.setMouseEnabled(y),o.mouseEnabled=y;break}case"enter":o.defaultEnterAction=o.defaultEnterAction==="amend"?"enqueue":"amend";break}st()},bo=m=>{(async()=>{try{switch(m){case"tools":case"plan":S.notify(`${Jt(m)} is session-only \u2014 not saved`);return;case"thoughts":await $r("showThoughts",o.showThoughts);break;case"diffs":await $r("showFileUpdates",o.showFileUpdates);break;case"mouse":await $r("mouse",o.mouseEnabled);break;case"enter":await $r("defaultEnterAction",o.defaultEnterAction);break}S.notify(`saved default: ${Jt(m)} ${wo(m)}`)}catch(y){S.notify(`save failed: ${y instanceof Error?y.message:String(y)}`)}})()},Es=m=>{if(!S.isOptionsPromptActive())return!1;if(m.type==="key")switch(m.name){case"up":return Bt=Math.max(0,Bt-1),st(),!0;case"down":return Bt=Math.min(Ts.length-1,Bt+1),st(),!0;case"enter":{let y=Ts[Bt];return y&&Pr(y),!0}case"ctrl-o":case"escape":case"ctrl-c":return S.setOptionsPrompt(null),!0;case"ctrl-d":return S.setOptionsPrompt(null),!1;default:return!0}if(m.type==="char"){if(/^[1-9]$/.test(m.ch)){let y=parseInt(m.ch,10)-1,I=Ts[y];return I&&(Bt=y,Pr(I)),!0}if(m.ch==="s"||m.ch==="S"){let y=Ts[Bt];return y&&bo(y),!0}}return!0},k=()=>{b=!0,process.off("SIGINT",Rs),process.platform!=="win32"&&process.off("SIGCONT",De),D!==null&&(clearInterval(D),D=null),S.clearWindowTitle(),S.stop({keepFullscreen:!0}),os(Wt,nt).catch(()=>{}),g.close().catch(()=>{})},P=(m=0)=>{k(),Ke&&(Ke(null),Ke=null),m!==0&&process.exit(m)},F=async()=>{if(!Ke)return;let m=ye.state().buffer.join(`
|
|
191
|
-
`);m.replace(/\s+$/,"").length>0&&ft(m),S.pauseRepaint(),S.stop({keepFullscreen:!0}),
|
|
192
|
-
`))return!1;let I=y.indexOf(" ");switch(I===-1?y:y.slice(0,I)){case"/quit":case"/exit":return Rr(),!0;case"/clear":return gt.clear(),Cn.clear(),fn.length=0,ee=null,O=null,se=null,qe.clear(),un.clear(),Rn.clear(),Xn.clear(),M.clear(),U.clear(),S.clearScrollback(),!0;case"/demo-plan":{S.clearKey("plan");let C=["Step 1","Step 2","Step 3","Step 4","Step 5"],j=[["pending","pending","pending","pending","pending"],["in_progress","pending","pending","pending","pending"],["completed","in_progress","pending","pending","pending"],["completed","completed","in_progress","pending","pending"],["completed","completed","completed","in_progress","pending"],["completed","completed","completed","completed","in_progress"],["completed","completed","completed","completed","completed"]],W=0,B=()=>{let Z=j[W];Z&&(T({kind:"plan",entries:C.map((Et,ve)=>({content:Et,status:Z[ve]??"pending"}))}),W+=1,setTimeout(B,600))};return B(),!0}case"/demo-tool":{let C=`demo-${Date.now()}`;return T({kind:"tool-call",toolCallId:C,title:"Terminal",status:"pending"}),setTimeout(()=>{T({kind:"tool-call-update",toolCallId:C,title:"echo hello world",status:"in_progress"})},500),setTimeout(()=>{T({kind:"tool-call-update",toolCallId:C,status:"completed"})},1500),!0}case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let j of Sr)C.push({prefix:" ",body:` ${j.name.padEnd(12)} ${j.description??""}`,bodyStyle:"info"});if(Vn.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let j of Vn)C.push({prefix:" ",body:` ${j.name.padEnd(12)} ${j.description??""}`,bodyStyle:"info"})}return S.appendLines(C),!0}case"/agent":{let C=I===-1?"":y.slice(I+1).trim(),j=ho();if(!j)return S.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let W=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let B of j.options){let Z=B.value===j.currentValue?"* ":" ";W.push({prefix:" ",body:`${Z}${B.value.padEnd(16)} ${B.name}`,bodyStyle:"info"})}return S.appendLines(W),!0}return j.options.some(W=>W.value===C)?C===j.currentValue?(S.notify(`already on agent ${C}`),!0):(S.notify(`switching to ${C}\u2026`),h.request("session/set_config_option",{sessionId:Te,configId:"agent",value:C}).catch(W=>{S.notify(`set_config_option failed: ${W.message}`)}),!0):(S.notify(`unknown agent: ${C}`),!0)}case"/sessions":return S.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;default:return!1}},Io=async(m,y,I)=>{let E=[];m.length>0&&E.push({type:"text",text:m});for(let ve of y)E.push({type:"image",data:ve.data,mimeType:ve.mimeType});q(1);let C={text:m,displayText:I??m,attachments:y,flushed:!1};pt.push(C),et=!1;let j=!1,W=null,B=ve=>{typeof z<"u"&&z!==null&&z.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:ve,bodyStyle:"tool-status-fail"}])},Z=!1;ke={text:m,attachments:y,cancel:()=>{if(et){et=!1,Z=!0,B("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Te}).catch(Fe=>{B(`force-stop failed: ${Fe.message}`)});return}if(j)return;j=!0,h.notify("session/cancel",{sessionId:Te}).catch(()=>{});let ve=Date.now();W=setTimeout(()=>{ke!==null&&(In>=ve||(et=!0,B("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},xt)}};let Et;try{let ve=await h.request("session/prompt",{sessionId:Te,prompt:E});ve&&typeof ve.stopReason=="string"&&(Et=ve.stopReason)}catch(ve){let Fe=pt.indexOf(C);Fe>=0&&pt.splice(Fe,1),C.messageId!==void 0&&He.delete(C.messageId),Z?S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):S.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:ve.message,bodyStyle:"tool-status-fail"}])}finally{if(ke=null,W!==null&&(clearTimeout(W),W=null),q(-1),C.flushed&&mt===C){let ve=C.messageId!==void 0&&Ge.has(C.messageId);ve&&C.messageId!==void 0&&Ge.delete(C.messageId);let Fe={kind:"turn-complete"};Et!==void 0&&(Fe.stopReason=Et),ve&&(Fe.amended=!0),T(Fe),mt=null}if(Kn!==null){let{text:ve,attachments:Fe}=Kn;Kn=null,ye.state().buffer.every(at=>at==="")&&(ye.setBuffer(ve,Fe),S.refreshPrompt())}}},gt=new Map,qe=new Map,un=new Map,Cn=new Map,fn=[],Gn=0,pn=`tools:${Gn}`,Rn=new Map,Xn=new Map,M=new Map,U=new Set,ee=null,O=null,se=null,ne=null,fe=null,Rt=e.tui.maxToolItems,We=e.tui.maxPlanItems,yt=()=>({maxPlanItems:fe??o.planExpanded?1/0:We}),Me=()=>{if(ne===null)return;let m=lr(ne,yt());m.length>0&&S.upsertLines("plan",[{body:""},...m])},Vt="",Zn=null,Sc=0,Ih=()=>{if(Zn===null)return;let m=S.width(),y=ur(Vt,m>0?{maxWidth:m}:void 0);y.length!==0&&S.upsertLines(Zn,y)},Sh=m=>{m.length!==0&&(Zn===null&&(S.ensureSeparator(),Zn=`agent:${Sc}`,Sc+=1,Vt=""),Vt+=m,Ih())},Tn=()=>{Zn=null,Vt=""},Ms="",En=null,kc=0,xc=(m,y)=>y?[{prefix:" ",body:"\u25B8 Thinking",bodyStyle:"thought"}]:up(m),Ac=()=>{if(En===null||Ms.length===0)return;M.set(En,Ms);let m=xc(Ms,U.has(En));m.length!==0&&S.upsertLines(En,m)},kh=m=>{let y=M.get(m);if(y===void 0)return;let I=xc(y,U.has(m));I.length!==0&&S.upsertLines(m,I)},xh=m=>{m.length!==0&&(En===null&&(S.ensureSeparator("thought"),En=`thought:${kc}`,kc+=1,Ms=""),Ms+=m,Ac())},Pn=()=>{En=null,Ms=""},Cc=m=>{let{order:y,states:I,startedAt:E,endedAt:C,stopReason:j}=m,W=y.length,B=Rt>0,Z=!B||m.expanded?y:y.slice(Math.max(0,W-Rt)),Et=W-Z.length,ve=C===null,Fe=C??Date.now(),Ue=Fe-E,at=!ve&&j!==null&&j!=="end_turn"?j:null,Oc=at==="amended",Lc=Oc?`amended \xB7 ${sn(Ue)}`:`stopped (${at}) \xB7 ${sn(Ue)}`,Ao;if(W===0)at!==null?Ao=Lc:Ao=ve?`thinking \xB7 ${sn(Ue)}`:`thought \xB7 ${sn(Ue)}`;else{let ha=W===1?"tool":"tools",Co=at!==null?Lc:ve?sn(Ue):`took ${sn(Ue)}`,Hc=[`${W} ${ha}`,Co];ve&&B&&Et>0&&Hc.push(`${Et} hidden`),Ao=Hc.join(" \xB7 ")}let Bc=W===0&&ve,Nc=Oc?"tool-status-cancelled":"tool-status-fail",Dc=[{prefix:"\u2699 ",prefixStyle:Bc?"tool-status-running":at!==null?Nc:"tool",body:Ao,bodyStyle:Bc?"tool-status-running":at!==null?Nc:"dim"}];for(let ha of Z){let Co=I.get(ha);Co&&Dc.push(...pp(Co,Fe))}return Dc},Rc=m=>Xn.get(m)??o.toolsExpanded,Tt=()=>{if(ee===null)return;let m=Cc({order:fn,states:gt,startedAt:ee,endedAt:O,stopReason:se,expanded:Rc(pn)});S.upsertLines(pn,m)},Tc=m=>{let y=Rn.get(m);if(!y)return;let I=Cc({order:y.order,states:y.states,startedAt:y.startedAt,endedAt:y.endedAt,stopReason:y.stopReason,expanded:Rc(m)});S.upsertLines(m,I)},Ah=()=>{ee!==null&&!Rn.has(pn)&&Tt();for(let m of Rn.keys())Tc(m)},ma=()=>{ee!==null&&Rn.set(pn,{order:[...fn],states:new Map(gt),startedAt:ee,endedAt:O??Date.now(),stopReason:se})},Ec=()=>{Gn+=1,pn=`tools:${Gn}`,ee=Date.now(),O=null,se=null,Tt()},Pc=(m,y,I,E,C,j)=>{let W=!gt.has(m),B=gt.get(m),Z=B??{initialTitle:y??"tool",latestTitle:y??"tool",status:I??"pending",startedAt:Date.now()};B&&y!==void 0&&(Z.latestTitle=y),j!==void 0&&Z.detail===void 0&&(Z.detail=j),B&&I!==void 0&&(Z.status=I),B||(Z.status=I??"pending"),Z.endedAt===void 0&&wp(Z.status)&&(Z.endedAt=Date.now()),E!==void 0&&(Z.errorText=E),C!==void 0&&(Z.editDiff=C),gt.set(m,Z),W&&(ee===null&&(Gn+=1,pn=`tools:${Gn}`,ee=Date.now(),O=null,se=null),fn.push(m))},Mc=async m=>{try{let y=await h.request("hydra-acp/session/tool_content",{sessionId:Te,hash:m});return typeof y?.content=="string"?y.content:null}catch{return null}},So=new Set,Ch=(m,y)=>{So.has(m)||y.oldRef===void 0&&y.newRef===void 0||(So.add(m),(async()=>{let[I,E]=await Promise.all([y.oldRef?Mc(y.oldRef.hash):Promise.resolve(y.oldText),y.newRef?Mc(y.newRef.hash):Promise.resolve(y.newText)]);if(y.oldRef!==void 0&&I===null||y.newRef!==void 0&&E===null){So.delete(m);let Et=Md(y,"diff",{deferredStatus:"error"});Et.length>0&&(S.upsertLines(`editdiff:${m}`,Et),S.repaintNow());return}let j={...y.path!==void 0?{path:y.path}:{},oldText:I??"",newText:E??""};qe.set(m,j);let W=gt.get(m);W?.editDiff&&(W.editDiff=j),So.delete(m);let B=un.get(m),Z=B===void 0?o.showFileUpdates:B?"diff":"edit";Z!=="none"&&(ko(m,j,Z==="diff"?"diff":"edit"),S.repaintNow())})())},ko=(m,y,I)=>{let E=`editdiff:${m}`,C=Md(y,I);if(C.length===0){S.removeKey(E);return}S.upsertLines(E,C),I==="diff"&&(y.oldRef!==void 0||y.newRef!==void 0)&&S.notifyWhenVisible(E)},Rh=m=>{if(!m.startsWith("editdiff:"))return;let y=m.slice(9),I=qe.get(y);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&Ch(y,I)},$c=m=>{let y=`editdiff:${m}`,I=o.showFileUpdates,E=gt.get(m),C;if(I==="none"||!E?.editDiff||E.status!=="completed")C=null;else{let W=un.get(m);C=W!==void 0?W?"diff":"edit":I==="diff"?"diff":"edit"}if(C===null){S.removeKey(y);return}let j=E.editDiff;qe.set(m,j),ko(m,j,C)},Th=()=>{let m=o.showFileUpdates;for(let[y,I]of qe){let E=`editdiff:${y}`,C=un.get(y),j=C===void 0?m:C?"diff":"edit";if(j==="none"){S.removeKey(E);continue}ko(y,I,j==="diff"?"diff":"edit")}},Eh=m=>{if(m.startsWith("editdiff:")){let y=m.slice(9),I=qe.get(y);if(!I)return;let E=un.get(y)??o.showFileUpdates==="diff";un.set(y,!E),ko(y,I,E?"edit":"diff"),S.repaintNow();return}if(m==="plan"){if(ne===null)return;fe=!(fe??o.planExpanded),Me(),S.repaintNow();return}if(m.startsWith("tools:")){let y=Xn.get(m)??o.toolsExpanded;Xn.set(m,!y),m===pn&&ee!==null?Tt():Tc(m),S.repaintNow();return}if(m.startsWith("thought:")){if(!M.has(m))return;U.has(m)?U.delete(m):U.add(m),m===En?Ac():kh(m),S.repaintNow();return}};v=m=>{if(m.kind==="available-commands"){Vn=m.commands,kr();return}if(m.kind==="available-modes"){Ct=m.modes;return}if(m.kind==="config-options"){ks=m.options;let I=m.options.find(C=>C.id==="agent");I&&I.currentValue&&I.currentValue!==Ot&&(Ot=I.currentValue,S.setSessionbar({agent:I.currentValue}));let E=m.options.find(C=>C.id==="mode");E&&(Ct=E.options.map(C=>({id:C.value,name:C.name??C.value,...C.description!==void 0?{description:C.description}:{}})));return}if(m.kind==="mode-changed"){S.setBanner({currentMode:m.mode||void 0});return}if(m.kind==="session-info"){m.title!==void 0&&S.setSessionbar({title:m.title}),m.agentId!==void 0&&m.agentId!==Ot&&(Ot=m.agentId,S.setSessionbar({agent:m.agentId}));return}if(m.kind==="usage-update"){let I=!1;m.used!==void 0&&je.used!==m.used&&(je.used=m.used,I=!0),m.size!==void 0&&je.size!==m.size&&(je.size=m.size,I=!0),m.costAmount!==void 0&&je.costAmount!==m.costAmount&&(je.costAmount=m.costAmount,I=!0),m.costCurrency!==void 0&&je.costCurrency!==m.costCurrency&&(je.costCurrency=m.costCurrency,I=!0),I&&S.setSessionbar({usage:{...je}});return}if(m.kind==="user-text"){Ir&&ft(m.text),Tn(),Pn(),ee!==null&&(O=Date.now(),Tt()),mt=null,S.ensureSeparator();let I=lr(m);I.length>0&&S.appendLines(I),ma(),S.clearKey("plan"),ne=null,fe=null,gt.clear(),Cn.clear(),fn.length=0,O=null,Ec(),S.redraw();return}if(m.kind==="agent-text"){Pn(),Sh(m.text);return}if(m.kind==="agent-thought"){Tn(),xh(m.text);return}if(m.kind==="exit-plan-mode"){Tn(),Pn();let I=Cn.get(m.toolCallId),E={plan:m.plan??I?.plan??"",status:m.status??I?.status};if(Cn.set(m.toolCallId,E),E.plan.length===0)return;let C=bp(E);C.length>0&&S.upsertLines(m.toolCallId,C);return}if(m.kind==="tool-call"){Tn(),Pn(),Pc(m.toolCallId,m.title,m.status,void 0,m.editDiff,m.detail),Tt(),$c(m.toolCallId);return}if(m.kind==="plan"){Tn(),Pn(),ne=m;let I=lr(m,yt());I.length>0&&S.upsertLines("plan",[{body:""},...I]);let E=m.entries.length>0&&m.entries.every(C=>(C.status??"pending")==="completed");S.setStickyBottomKey(E?null:"plan");return}if(m.kind==="tool-call-update"){Tn(),Pn(),Pc(m.toolCallId,m.title,m.status,m.errorText,m.editDiff,m.detail),m.upstreamInterrupted&&(H=!0),Tt(),$c(m.toolCallId);return}m.kind==="model-changed"&&S.setSessionbar({model:m.model});let y=lr(m);if(y.length>0&&S.appendLines(y),m.kind==="turn-complete"){te=void 0,Tn(),Pn();let I=m.amended?"amended":m.stopReason;if(!m.amended&&H&&(I===void 0||I==="end_turn")&&(I="error"),ne!==null&&I!==void 0&&I!=="end_turn"){let E=lr({...ne,stopped:!0,amended:m.amended===!0},yt());E.length>0&&S.upsertLines("plan",[{body:""},...E])}ne=null,fe=null,S.clearKey("plan"),S.setStickyBottomKey("plan"),ee!==null?(O=Date.now(),se=I??null,Tt(),ma()):I!==void 0&&I!=="end_turn"&&I!=="amended"&&S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${I}`,bodyStyle:"tool-status-fail"}]),gt.clear(),Cn.clear(),fn.length=0,ee=null,O=null,se=null,H=!1,S.ensureSeparator(),eh({pendingTurns:$,queueSize:Ve.size,ownTurnInFlight:ke!==null,hasInFlightHead:te!==void 0,replayDraining:A,amended:m.amended===!0})&&q(-$)}};let _c=w;w=[];let xo=[];for(let m of _c)m.kind==="user-text"&&typeof m.text=="string"&&xo.push(m.text);S.pauseRepaint(),A=!0;try{for(let m of _c)v(m)}finally{A=!1,S.resumeRepaint()}if(xo.length>0){let m=dd(nt,xo);m!==nt&&(nt=m,ut=dd(ut,xo),ye.setHistory(Zo(At,ut)),os(Wt,nt).catch(()=>{}))}Ir=!0,dn!==void 0&&$>0?(J=dn,S.setBanner({status:"busy",elapsedMs:Date.now()-dn}),D===null&&(D=setInterval(()=>{J===null||z===null||(z.setBanner({elapsedMs:Date.now()-J}),Tt())},1e3)),ee===null&&Ec(),ee=dn,Tt()):dn===void 0&&$>0&&q(-$);let Ph=()=>{if(ue){let m=ue.resolve;ue=null,S.setPermissionPrompt(null),m({outcome:{outcome:"cancelled"}})}Tn(),Pn()},Fc=()=>{ee!==null&&(O=Date.now(),se="reconnect-recovery-failed",Tt(),ma(),gt.clear(),Cn.clear(),fn.length=0,ee=null,O=null,se=null)};return p=()=>{S.setBanner({status:"disconnected",elapsedMs:void 0})},u=async()=>{Ph();let m={jsonrpc:"2.0",id:`tui-reinit-${sh()}`,method:"initialize",params:{protocolVersion:It,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:le}}};try{await g.request(m)}catch{}let y=xe!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${sh()}`,method:"session/attach",params:{sessionId:Te,historyPolicy:y?"after_message":"none",...y?{afterMessageId:xe}:{},clientInfo:{name:"hydra-acp-tui",version:le},...(()=>{let B={};return Wn!==void 0&&(B.resume={upstreamSessionId:Wn,agentId:Ot,cwd:lt}),e.tui.toolContent==="references"&&(B.toolContent="references"),Object.keys(B).length>0?{_meta:{[Mt]:B}}:{}})()}};X=[];let E,C,j;try{let B=await g.request(I);if(B.error)throw new Error(B.error.message);j=Zm(B.result),E=j.appliedPolicy,j.clientId!==void 0&&(tt=j.clientId)}catch(B){C=B}let W=X??[];if(X=null,C)Fc(),S.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(y&&E!=="after_message")Fc(),S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{A=!0;try{for(let B of W)Y(B)}finally{A=!1}}if(j){let B=th({daemonTurnStartedAt:j.turnStartedAt,pendingTurns:$});B.pendingTurnsDelta!==0&&q(B.pendingTurnsDelta),B.banner==="busy"&&B.busySince!==void 0?(J=B.busySince,S.setBanner({status:"busy",elapsedMs:Date.now()-B.busySince}),D===null&&(D=setInterval(()=>{J===null||z===null||(z.setBanner({elapsedMs:Date.now()-J}),Tt())},1e3))):S.setBanner({status:"ready",elapsedMs:void 0})}else S.setBanner({status:$>0?"busy":"ready",elapsedMs:$>0?0:void 0})},h.onClose(m=>{m&&t.red(`
|
|
186
|
+
`)}async function jm(t,e){try{return await zm(t.spawn,"which",[e]),!0}catch{return!1}}async function ck(t,e){try{let n=await bc.readFile(t);return e&&await bc.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>rn?{ok:!1,reason:`clipboard image is ${Ft(n.length)}, max ${Ft(rn)}`}:{ok:!0,kind:"image",attachment:{mimeType:lo(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function zm(t,e,n){return new Promise((s,r)=>{let o=t(e,n);o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",r),o.on("close",i=>{i===0?s():r(new Error(`${e} exited ${i}`))})})}function ca(t,e,n){return new Promise((s,r)=>{let o=t(e,n),i=[],a=o.stdout===null,d=null,c=!1,l=()=>{c||!a||d===null||(c=!0,d===0?s(Buffer.concat(i)):r(new Error(`${e} exited ${d}`)))};o.stdout?.on("data",f=>{i.push(typeof f=="string"?Buffer.from(f):f)}),o.stdout?.on("end",()=>{a=!0,l()}),o.stderr?.on("data",()=>{}),o.on("error",f=>{c||(c=!0,r(f))}),o.on("close",f=>{d=f??0,l()})})}var nk,ik,Jm=V(()=>{"use strict";ea();nk={platform:process.platform,env:process.env,spawn:ZS,tmpdir:ek.tmpdir};ik=["image/png","image/jpeg","image/gif","image/webp"]});import*as Vm from"fs";import*as Ym from"os";import*as la from"path";function Qm(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function lk(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function uk(t){return t.replace(/\\ /g," ")}function Km(t){return t.replace(/ /g,"\\ ")}function fk(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function pk(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Ym.homedir()+n.slice(1)),la.isAbsolute(n)?n:la.resolve(e,n)}function mk(t){let e;try{e=Vm.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Gm(t,e,n=mk){if(!lk(t))return null;let s=uk(t),{dirPrefix:r,base:o}=fk(s),i=pk(r,e),a=n(i);if(a===null)return null;let d=o.startsWith("."),c=a.filter(u=>u.name.startsWith(o)&&(d||!u.name.startsWith(".")));if(c.length===0)return null;let l=c.map(u=>u.isDir?u.name+"/":u.name);if(c.length===1){let u=c[0],p=u.isDir?u.name+"/":u.name;return{replacement:Km(r+p),candidates:l}}let f=po(c.map(u=>u.name));return{replacement:Km(r+f),candidates:l}}var Xm=V(()=>{"use strict";da()});function Zm(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let o=r.turnStartedAt;typeof o=="number"&&(e.turnStartedAt=o)}}return e}function eh(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function th(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var nh=V(()=>{"use strict"});import{appendFileSync as hk,statSync as gk,renameSync as yk}from"fs";import{nanoid as sh}from"nanoid";import wk from"terminal-kit";import bk from"fs/promises";import vc from"path";function rh(t){if(!Array.isArray(t))return;let e=as({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Ik(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}async function ah(t){let e=await G(),n=t.target??await Qt(e);lh=e.tui.logMaxBytes,n.isLocal&&!t.target&&await nr(e);let s=wk.terminal,r={},o={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,defaultEnterAction:e.tui.defaultEnterAction},i=gc(),a=!1,d=()=>{a||(s.fullscreen(!0),a=!0)},c=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
|
|
187
|
+
`))};d();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let f=t;try{for(;f!==null;)f=await kk(s,e,n,f,r,o,i)}finally{c(),process.off("exit",l)}let u=await oo();if(u&&process.stderr.write(`\u2728 ${io(u)}
|
|
188
|
+
`),process.stdout.isTTY){let p=await Pi(e);if(p?.version!==void 0){let g=p.version!==le,h=Zs(e),w=p.configDigest!==void 0&&p.configDigest!==h;if(g||w){let v=g?`daemon ${p.version} \u2260 cli ${le}`:"config changed since daemon started",b=x=>`\x1B[33m${x}\x1B[0m`;process.stderr.write(b(`! ${v} \u2014 run \`${Pn()} daemon restart\` to apply.`)+`
|
|
189
|
+
`)}}}if(r.sessionId&&process.stdout.isTTY){let p=Oe(r.sessionId),g=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Pn()} --session ${p}${g}
|
|
190
|
+
`)}}async function kk(t,e,n,s,r,o,i){let a=await xk(t,e,n,s,i);if(!a)return t.grabInput(!1),null;let d=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",c=Rk(t,d);c.write(d);let l=n.wsUrl,f=["acp.v1",`hydra-acp-token.${n.token}`],u=null,p=null,g=new mr({url:l,subprotocols:f,onConnect:async m=>{m||u&&await u()},onDisconnect:m=>{p&&p(m)},log:()=>{}}),h=new Zt(g);await g.start(),h.onNotification(Uo,m=>{let y=ql.safeParse(m);y.success&&c.applyProgress(y.data)});let w=[],v=null,b=!1,x=!1,E=m=>{m&&(v?v(m):w.push(m))},$=0,K=!1,te,J=null,D=null,_=null,H=!1,q=m=>{let y=$;$=Math.max(0,$+m);let I=typeof z<"u"&&z!==null;y===0&&$>0?(K=!1,J=Date.now(),_=Date.now(),be?.setTurnRunning(!0),I&&z.setBanner({status:"busy",elapsedMs:0,stalled:!1}),D===null&&I&&(D=setInterval(()=>{if(J===null||z===null)return;let R=_===null?0:Date.now()-_;z.setBanner({elapsedMs:Date.now()-J,stalled:R>=vk}),Tt()},1e3))):y>0&&$===0?(K=!1,J=null,_=null,be?.setTurnRunning(!1),D!==null&&(clearInterval(D),D=null),I&&z.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):$>0&&K&&(K=!1,I&&z.setBanner({status:"busy",stalled:!1}))},z=null,be=null,xe,X=null,Ae=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]),Y=m=>{let{update:y}=m??{},I=as(y,{cwd:lt});Ak(y,I),_=Date.now();let R=y?.sessionUpdate;if(typeof R=="string"&&!Ae.has(R)){let C=y??{};typeof C.messageId=="string"&&(xe=C.messageId)}if(R==="prompt_received"?q(1):I?.kind==="turn-complete"&&q(-1),R==="permission_resolved"){Sn(y);return}E(I),br(y)};h.onNotification("session/update",m=>{if(!b){if(X!==null){X.push(m);return}Y(m)}}),h.onNotification("hydra-acp/session/closed",()=>{if(b)return;$>0&&q(-$),typeof z<"u"&&z!==null&&z.setBanner({status:"cold",elapsedMs:void 0})});let ge=new Map,wr=200,In=0,et=!1,xt=4e3;h.onNotification("hydra-acp/prompt_queue/added",m=>{if(b)return;let y=m??{};if(typeof y.messageId!="string")return;if(typeof y._meta?.["hydra-acp"]?.amending=="string"){let R=y.messageId,C=y.prompt,U=setTimeout(()=>{ge.delete(R),Ve.set(R,Kt(R,C)),z&&be&&ht()},wr);ge.set(R,U)}else Ve.set(y.messageId,Kt(y.messageId,y.prompt)),z&&be&&ht();if(tt!==void 0&&y.originator?.clientId===tt){let R=pt.shift();R&&(R.messageId=y.messageId,He.set(y.messageId,R))}}),h.onNotification("hydra-acp/prompt_queue/updated",m=>{if(b)return;let y=m??{};if(typeof y.messageId!="string"||!Ve.has(y.messageId))return;Ve.set(y.messageId,Kt(y.messageId,y.prompt));let I=He.get(y.messageId);if(I){let R=Array.isArray(y.prompt)?y.prompt:[],C="",U=[];for(let W of R){if(!W||typeof W!="object")continue;let B=W;B.type==="text"&&typeof B.text=="string"?C+=B.text:B.type==="image"&&typeof B.data=="string"&&typeof B.mimeType=="string"&&U.push({data:B.data,mimeType:B.mimeType,sizeBytes:Math.floor(B.data.length*3/4)})}I.text=C,I.attachments=U}z&&be&&ht()}),h.onNotification("hydra-acp/prompt_queue/removed",m=>{if(b)return;let y=m??{};if(typeof y.messageId!="string")return;y.reason==="started"&&(te=y.messageId);let I=ge.get(y.messageId);I!==void 0&&(clearTimeout(I),ge.delete(y.messageId)),Ve.delete(y.messageId)&&z&&be&&ht();let C=He.get(y.messageId);C&&(He.delete(y.messageId),y.reason==="started"&&(C.flushed=!0,E({kind:"user-text",text:C.displayText,attachments:C.attachments}),mt=C))}),h.onNotification("hydra-acp/cancel_failed",m=>{if(b)return;let y=m??{};if(!(typeof z<"u"&&z!==null))return;In=Date.now(),et=!0;let R=typeof y.code=="number"?` (${y.code})`:"",C=typeof y.message=="string"&&y.message.length>0?`: ${y.message}`:"";z.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${R}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",m=>{if(b)return;let y=m??{};if(typeof y.cancelledMessageId!="string")return;let I=y.cancelledMessageId;Ge.add(I),mt!==null&&mt.messageId!==void 0&&mt.messageId===I&&(E({kind:"turn-complete",stopReason:"cancelled",amended:!0}),mt=null,Ge.delete(I))});let Sn=m=>{let y=m??{},I=typeof y.toolCallId=="string"?y.toolCallId:void 0,R;y.outcome&&typeof y.outcome=="object"?R=y.outcome:typeof y.chosenOptionId=="string"&&(R={kind:"selected",optionId:y.chosenOptionId}),ys(I,R?{outcome:R}:void 0)},ue=null,ys=(m,y)=>{if(!ue||ue.toolCallId&&m&&ue.toolCallId!==m)return;let I=ue.resolve;ue=null,S.setPermissionPrompt(null),I(y??{outcome:{outcome:"cancelled"}})},br=m=>{if(!ue?.toolCallId)return;let y=m??{};y.sessionUpdate!=="tool_call"&&y.sessionUpdate!=="tool_call_update"||y.toolCallId===ue.toolCallId&&(!y.status||y.status==="pending"||ys(y.toolCallId,void 0))},ws=()=>{if(!ue){S.setPermissionPrompt(null);return}S.setPermissionPrompt({title:ue.title,detail:ue.detail,options:ue.options.map(m=>({label:m.name})),selectedIndex:ue.selectedIndex})},on=m=>{if(!ue)return;let{options:y,resolve:I}=ue;if(ue=null,S.setPermissionPrompt(null),m===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:m}})};h.onRequest("session/request_permission",async m=>{if(b)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ls(m);let y=m??{},R=(Array.isArray(y.options)?y.options:[]).map(Z=>({optionId:Z.optionId,name:Ie(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),C=y.toolCall?.title??y.toolCall?.name??"tool",U=Ie(C),W=Ie(om(rm(m))),B=y.toolCall?.toolCallId;return R.length===0?(S.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${U} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Z=>{ue={title:U,detail:W,options:R,selectedIndex:0,resolve:Z,toolCallId:B},ws()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let qn,bs,Ye=!0,kn=!1;try{let m=await h.request("initialize",{protocolVersion:It,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:le}});bs=m?.agentInfo?.name,m?.agentCapabilities?.promptCapabilities?.image===!1&&(Ye=!1),kn=St(m?._meta??void 0).prompt?.amending===!0}catch{}let Te=a.sessionId,Ot=a.agentId,lt=a.cwd,vr,tt,Wn,Lt,zn,vs,Is,an,xn,dn;if(a.sessionId==="__new__"){let m={};s.agentId&&(m.agentId=s.agentId),s.name&&(m.title=s.name),s.model&&(m.model=s.model);let y=await h.request("session/new",{cwd:a.cwd,...Object.keys(m).length>0?{_meta:{[Mt]:m}}:{}});Te=y.sessionId,r.sessionId=Te,r.readonly=!1;let I=St(y._meta??void 0);I.clientId&&(tt=I.clientId),qn=I.upstreamSessionId,I.agentId&&(Ot=I.agentId),I.cwd&&(lt=I.cwd),I.title&&(vr=I.title),Wn=I.currentModel,Lt=I.currentMode,xn=I.currentUsage,dn=I.turnStartedAt,I.availableCommands&&(zn=wi(I.availableCommands)),I.availableModes&&(vs=I.availableModes),Is=rh(y.configOptions),an=I.queue}else{let m={};s.readonly===!0&&(m.readonly=!0),e.tui.toolContent==="references"&&(m.toolContent="references"),s.drip===!0&&(m.replayMode="drip",s.dripSpeed!==void 0&&(m.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(m.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let y=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:le},...Object.keys(m).length>0?{_meta:{[Mt]:m}}:{}});Te=y.sessionId,y.clientId&&(tt=y.clientId),r.sessionId=Te,r.readonly=s.readonly===!0;let I=St(y._meta??void 0);qn=I.upstreamSessionId,I.agentId&&(Ot=I.agentId),I.cwd&&(lt=I.cwd),I.title&&(vr=I.title),Wn=I.currentModel,Lt=I.currentMode,xn=I.currentUsage,dn=I.turnStartedAt,I.availableCommands&&(zn=wi(I.availableCommands)),I.availableModes&&(vs=I.availableModes),Is=rh(y.configOptions),an=I.queue}let Wt=T.tuiHistoryFile(Te),Se=T.globalTuiHistoryFile(),nt=await Ur(Wt).catch(()=>[]),At=await Ur(Se).catch(()=>[]);At.length>e.tui.promptHistoryMaxEntries&&(At=At.slice(At.length-e.tui.promptHistoryMaxEntries));let ut=[...nt],ye=new bn({history:Zo(At,ut)});be=ye;let Ir=!1,ft=(m,y)=>{let I=m.replace(/\n+$/,"");if(I.length===0)return;let R=(y??m).replace(/\n+$/,""),C=jr(nt,I),U=C!==nt;nt=C,ut=jr(ut,R);let W=jr(At,I,e.tui.promptHistoryMaxEntries),B=W!==At;At=W,ye.setHistory(Zo(At,ut)),U&&rs(Wt,nt).catch(()=>{}),B&&Cu(Se,I).catch(()=>{})};$>0&&ye.setTurnRunning(!0);let ke=null,Jn=null;Rm(e.tui.ambiguousWidth==="wide"),mp(e.tui.diffContextLines);let Qe=!1,S,De=()=>{Qe&&(Qe=!1,S.start())},cn=()=>{Qe||(Qe=!0,S.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",De),S=new ra({term:t,dispatcher:ye,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:o.mouseEnabled,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?cn:void 0,onBlockClick:m=>{Ph(m)},onBlockVisible:m=>{Th(m)},onKey:m=>{for(let y of m){if(ue&&Ar(y)||yo(y)||Ts(y)||xr(y)||ua(y))continue;if(y.type==="attachment-paths"){we(y.paths);continue}let I=ye.feed(y);for(let R of I)s.readonly===!0&&Ik(R)||ae(R)}kr(),S.setBannerSearchIndicator(ye.state().historySearchQuery),S.setAttachments(ye.state().attachments),S.refreshPrompt()}}),z=S,S.setStickyBottomKey("plan");let Sr=[{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:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/demo-plan",description:"Inject synthetic plan events (UI test)"},{name:"/demo-tool",description:"Inject a synthetic tool-call sequence (UI test)"}],Kn=zn??[],Ct=vs??[],Ss=Is??[],ho=()=>Ss.find(m=>m.id==="agent"),Vn=()=>{let m=new Set,y=[];for(let I of[...Sr,...Kn])m.has(I.name)||(m.add(I.name),y.push(I));return y},An=()=>{let m=ye.state().buffer,y=m[0]??"";if(!y.startsWith("/"))return[];if(m.length>1)return[];let I=y.indexOf(" "),R=I===-1?y:y.slice(0,I);if(R.lastIndexOf("/")>0)return[];let C=Vn().filter(U=>U.name.startsWith(R));return C.length===1&&C[0]?.name===R&&I===-1?[]:C},zt=[],kr=()=>{let m=An();if(m.length>0){zt=[],S.setCompletions(m);return}S.setCompletions(zt)},ua=m=>{if(m.type!=="key"||m.name!=="tab")return zt.length>0&&(zt=[]),!1;let y=An();if(y.length>0){zt=[];let I=ye.state().buffer[0]??"",R=Lm({matches:y.map(C=>C.name),firstLine:I});return R===null||ye.replaceFirstLine(R),!0}return go()},go=()=>{let m=ye.state(),y=m.buffer[m.row]??"",I=Qm(y,m.col);if(I===null)return!1;let R=Gm(I.token,lt);return R===null?!1:(R.replacement!==I.token&&ye.replaceRangeOnCurrentLine(I.start,m.col,R.replacement),zt=R.candidates.length>1?R.candidates.map(C=>({name:C})):[],!0)},xr=m=>{if(!S.isScrollbackSearchActive())return m.type==="key"&&m.name==="ctrl-r"&&S.isScrolledBack()?(S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(""),!0):!1;if(m.type==="char"){let y=S.scrollbackSearchTerm()+m.ch;return S.updateScrollbackSearchTerm(y),!0}if(m.type==="paste"){let y=S.scrollbackSearchTerm()+m.text.replace(/\n/g," ");return S.updateScrollbackSearchTerm(y),!0}if(m.type==="key")switch(m.name){case"ctrl-r":return S.advanceScrollbackSearch(),!0;case"ctrl-s":return S.retreatScrollbackSearch(),!0;case"backspace":{let y=S.scrollbackSearchTerm();return y.length===0?S.cancelScrollbackSearch():S.updateScrollbackSearchTerm(y.slice(0,-1)),!0}case"enter":return S.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return S.cancelScrollbackSearch(),!0;default:return!0}return!0},Ar=m=>{if(!ue)return!1;let y=ue.options;if(m.type==="key")switch(m.name){case"up":return ue.selectedIndex=Math.max(0,ue.selectedIndex-1),ws(),!0;case"down":return ue.selectedIndex=Math.min(y.length-1,ue.selectedIndex+1),ws(),!0;case"enter":{let I=y[ue.selectedIndex];return I&&on(I.optionId),!0}case"escape":case"ctrl-c":return on(null),!0;default:return!0}if(m.type==="char"&&/^[1-9]$/.test(m.ch)){let I=parseInt(m.ch,10)-1,R=y[I];return R&&on(R.optionId),!0}return!0},ks=Ot||bs||"?",je={...xn??{}};c.finalize(),S.start({skipFullscreen:!0}),S.setHideThoughts(!o.showThoughts),S.setSessionbar({agent:ks,cwd:lt,sessionId:Te,title:vr,model:Wn,usage:{...je}}),Lt&&S.setBanner({currentMode:Lt}),oo().then(m=>{m&&S.notify(`\u2728 ${io(m)}`,3e4)});let Ke=null,xs=new Promise(m=>{Ke=m}),Cr=()=>{h.notify("session/cancel",{sessionId:Te}).catch(()=>{})},As=()=>{z!==null&&$===1&&(K=!0,z.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Cs=()=>{if(ke){ke.cancel(),As();return}if($>0){Cr(),As();return}Rr()},Rr=()=>{P(0)},Tr=()=>{let m="enqueue prompt (sends now, or queues during a turn)",y="amend the in-flight turn (cancel + replace)";return[...o.defaultEnterAction==="amend"?[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",m]]:[["Enter",m],["Ctrl+Enter / Shift+Enter / ^S",y]],...Sk]},fa=()=>{if(S.isHelpPromptActive()){S.setHelpPrompt(null);return}S.setHelpPrompt({title:"Hotkeys",entries:Tr(),hint:"any key dismisses \xB7 /help lists commands"})},yo=m=>S.isHelpPromptActive()?(m.type==="key"&&m.name==="ctrl-g",S.setHelpPrompt(null),!0):!1,Rs=["tools","plan","thoughts","diffs","mouse","enter"],Bt=0,wo=m=>{switch(m){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}},Jt=m=>{switch(m){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"}},ln=()=>({title:"Session options",options:Rs.map(m=>({label:Jt(m),value:wo(m)})),selectedIndex:Bt}),st=()=>{S.isOptionsPromptActive()&&S.setOptionsPrompt(ln())},Er=()=>{if(S.isOptionsPromptActive()){S.setOptionsPrompt(null);return}Bt=0,S.setOptionsPrompt(ln())},Pr=m=>{switch(m){case"tools":o.toolsExpanded=!o.toolsExpanded,Gn.clear(),Ch();break;case"plan":o.planExpanded=!o.planExpanded,fe=null,Me();break;case"thoughts":o.showThoughts=!o.showThoughts,S.setHideThoughts(!o.showThoughts);break;case"diffs":o.showFileUpdates=o.showFileUpdates==="diff"?"edit":"diff",un.clear(),Eh();break;case"mouse":{let y=!S.isMouseEnabled();S.setMouseEnabled(y),o.mouseEnabled=y;break}case"enter":o.defaultEnterAction=o.defaultEnterAction==="amend"?"enqueue":"amend";break}st()},bo=m=>{(async()=>{try{switch(m){case"tools":case"plan":S.notify(`${Jt(m)} is session-only \u2014 not saved`);return;case"thoughts":await $r("showThoughts",o.showThoughts);break;case"diffs":await $r("showFileUpdates",o.showFileUpdates);break;case"mouse":await $r("mouse",o.mouseEnabled);break;case"enter":await $r("defaultEnterAction",o.defaultEnterAction);break}S.notify(`saved default: ${Jt(m)} ${wo(m)}`)}catch(y){S.notify(`save failed: ${y instanceof Error?y.message:String(y)}`)}})()},Ts=m=>{if(!S.isOptionsPromptActive())return!1;if(m.type==="key")switch(m.name){case"up":return Bt=Math.max(0,Bt-1),st(),!0;case"down":return Bt=Math.min(Rs.length-1,Bt+1),st(),!0;case"enter":{let y=Rs[Bt];return y&&Pr(y),!0}case"ctrl-o":case"escape":case"ctrl-c":return S.setOptionsPrompt(null),!0;case"ctrl-d":return S.setOptionsPrompt(null),!1;default:return!0}if(m.type==="char"){if(/^[1-9]$/.test(m.ch)){let y=parseInt(m.ch,10)-1,I=Rs[y];return I&&(Bt=y,Pr(I)),!0}if(m.ch==="s"||m.ch==="S"){let y=Rs[Bt];return y&&bo(y),!0}}return!0},k=()=>{b=!0,process.off("SIGINT",Cs),process.platform!=="win32"&&process.off("SIGCONT",De),D!==null&&(clearInterval(D),D=null),S.clearWindowTitle(),S.stop({keepFullscreen:!0}),rs(Wt,nt).catch(()=>{}),g.close().catch(()=>{})},P=(m=0)=>{k(),Ke&&(Ke(null),Ke=null),m!==0&&process.exit(m)},F=async()=>{if(!Ke)return;let m=ye.state().buffer.join(`
|
|
191
|
+
`);m.replace(/\s+$/,"").length>0&&ft(m),S.pauseRepaint(),S.stop({keepFullscreen:!0}),rs(Wt,nt).catch(()=>{});let y=null,I=null;for(;y===null;){let W=await yn(n,{includeNonInteractive:!0}),B=await yc(t,{cwd:lt,sessions:W,config:e,target:n,currentSessionId:Te,prefs:i});if(B.kind==="abort"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(B.kind==="exit"){P(0);return}if(B.kind==="new"){y={choice:B,sessions:W};break}if(B.kind==="fork"){let Ue=await ch(t,n,B,W);if(Ue.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(Ue.kind==="back")continue;y={choice:{kind:"attach",sessionId:Ue.ctx.sessionId,...Ue.ctx.agentId?{agentId:Ue.ctx.agentId}:{}},sessions:W},I={readonly:!1,cwd:Ue.ctx.cwd},Ue.ctx.resumeHint!==void 0&&(I.resumeHint=Ue.ctx.resumeHint);break}let Z=W.find(Ue=>Ue.sessionId===B.sessionId);if(!(Z!==void 0&&!!Z.importedFromMachine&&!Z.upstreamSessionId&&B.readonly!==!0)){if(n.isLocal&&Z&&!Z.importedFromMachine&&B.readonly!==!0&&!(await co(Z.cwd)).ok){let at=await mo(t,Z,{defaultCwd:Ht(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(at.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}if(at.kind==="back")continue;y={choice:B,sessions:W},I={readonly:!1,cwd:at.path,resumeHint:{agentId:B.agentId??Z.agentId??"",cwd:at.path,upstreamSessionId:""}};break}y={choice:B,sessions:W};break}let ve={...s,readonly:!1},Fe=await dh(t,Z,B,ve);if(Fe.kind==="cancel"){S.start({skipFullscreen:!0}),S.resumeRepaint();return}Fe.kind!=="back"&&(y={choice:B,sessions:W},I={readonly:ve.readonly===!0,cwd:Fe.ctx.cwd},Fe.ctx.resumeHint!==void 0&&(I.resumeHint=Fe.ctx.resumeHint))}let{choice:R}=y,C=Ke;if(Ke=null,process.off("SIGINT",Cs),g.close().catch(()=>{}),R.kind==="new"){let{sessionId:W,...B}=s,Z={...B,cwd:lt,forceNew:!0,readonly:!1};R.prompt!==void 0&&(Z.initialPrompt=R.prompt),C(Z);return}if(R.kind!=="attach")return;let U={...s,sessionId:R.sessionId,cwd:I?.cwd??lt,readonly:I?.readonly??R.readonly===!0};R.agentId!==void 0&&(U.agentId=R.agentId),I?.resumeHint!==void 0?U.resumeHint=I.resumeHint:delete U.resumeHint,C(U)},Q=async()=>{if(!Ke)return;let y=(await yn(n)).filter(W=>W.status==="live");if(y.length<=1)return;let I=y.findIndex(W=>W.sessionId===Te),R=y[(I+1)%y.length],C=Ke;Ke=null,process.off("SIGINT",Cs),g.close().catch(()=>{});let U={...s,sessionId:R.sessionId,cwd:lt,readonly:!1};R.agentId!==void 0&&(U.agentId=R.agentId),C(U)},ae=m=>{switch(m.type){case"send":o.defaultEnterAction==="amend"?Es(m.text,m.attachments,m.displayText):Dt(m.text,m.attachments,m.displayText);return;case"amend":o.defaultEnterAction==="amend"?Dt(m.text,m.attachments,m.displayText):Es(m.text,m.attachments,m.displayText);return;case"queue-edit":{let y=Yn(m.index);if(!y)return;let I=[];m.text.length>0&&I.push({type:"text",text:m.text});for(let R of m.attachments)I.push({type:"image",data:R.data,mimeType:R.mimeType});h.request("hydra-acp/prompt/update",{sessionId:Te,messageId:y,prompt:I}).then(R=>{let C=R;!C.updated&&C.reason!=="ok"&&S.notify(`queue edit skipped (${C.reason})`)}).catch(R=>{S.notify(`queue edit failed: ${R.message}`)});return}case"queue-remove":{let y=Yn(m.index);if(!y)return;h.request("hydra-acp/prompt/cancel",{sessionId:Te,messageId:y}).then(I=>{let R=I;!R.cancelled&&R.reason!=="ok"&&S.notify(`queue cancel skipped (${R.reason})`)}).catch(I=>{S.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(m.prefill&&ke){let y=Ve.size===0,I=ye.state().buffer.every(R=>R==="");y&&I&&(Jn={text:ke.text,attachments:ke.attachments})}ke?ke.cancel():$>0&&Cr(),As();return}case"exit":Rr();return;case"plan-toggle":pa(m.on);return;case"redraw-banner":S.setBanner({});return;case"redraw":S.fullRedraw();return;case"scroll-to-top":S.scrollToTop();return;case"scroll-to-bottom":S.scrollToBottom();return;case"switch-session":F();return;case"next-live-session":Q();return;case"toggle-options":Er();return;case"toggle-thoughts":o.showThoughts=!o.showThoughts,S.setHideThoughts(!o.showThoughts),S.notify(o.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let y=!S.isMouseEnabled();S.setMouseEnabled(y),o.mouseEnabled=y,S.notify(y?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":fa();return;case"escalate-search":S.enterScrollbackSearch(),S.updateScrollbackSearchTerm(m.query);return;case"attachment-request":Ce();return}},we=async m=>{if(!Ye){S.notify("agent does not accept image attachments");return}let y=0;for(let I of m){if(I.startsWith("data:")){let C=ec(I);if(!C){S.notify("unsupported data: URI");continue}if(C.sizeBytes>rn){S.notify(`image too large (${Ft(C.sizeBytes)}, max ${Ft(rn)})`);continue}ye.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),y++;continue}let R=lo(I);if(!R){S.notify(`unsupported image type: ${vc.basename(I)}`);continue}try{let C=await bk.readFile(I);if(C.length>rn){S.notify(`image too large (${Ft(C.length)}, max ${Ft(rn)})`);continue}ye.addAttachment({mimeType:R,data:C.toString("base64"),name:vc.basename(I),sizeBytes:C.length}),y++}catch(C){S.notify(`cannot read ${vc.basename(I)}: ${C.message}`)}}y>0&&(S.setAttachments(ye.state().attachments),S.refreshPrompt())},Ce=async()=>{let m=await qm();if(!m.ok){S.notify(m.reason);return}if(m.kind==="image"){if(!Ye){S.notify("agent does not accept image attachments");return}ye.addAttachment(m.attachment),S.setAttachments(ye.state().attachments),S.refreshPrompt();return}let y=ye.feed({type:"paste",text:m.text});for(let I of y)ae(I);S.refreshPrompt()},Nt=m=>m.attachmentCount>0?`${m.text} \xB7 \u{1F4CE}\xD7${m.attachmentCount}`:m.text,Kt=(m,y)=>{let I=Array.isArray(y)?y:[],R="",C=0;for(let U of I){if(!U||typeof U!="object")continue;let W=U;W.type==="text"&&typeof W.text=="string"?R+=W.text:W.type==="image"&&(C+=1)}return{messageId:m,text:Ie(R),attachmentCount:C}},Ve=new Map,pt=[],He=new Map,Ge=new Set,mt=null,ht=()=>{let m=[...Ve.values()],y=m.map(Nt);S.setQueuedPrompts(y),S.setBanner({queued:m.length}),ye.setQueue(m.map(I=>I.text))},Yn=m=>[...Ve.values()][m]?.messageId;if(an&&an.length>0){for(let m of an){if(m.position===0){te=m.messageId;continue}Ve.set(m.messageId,Kt(m.messageId,m.prompt))}Ve.size>0&&ht()}let Dt=(m,y,I)=>{S.scrollToBottom(),!vo(m)&&(ft(m,I),Io(m,y,I))},Es=(m,y,I)=>{if(S.scrollToBottom(),vo(m))return;if(ft(m,I),!kn||te===void 0){Io(m,y,I);return}let R=te,C=[];m.length>0&&C.push({type:"text",text:m});for(let B of y)C.push({type:"image",data:B.data,mimeType:B.mimeType});let U={text:m,displayText:I??m,attachments:y,flushed:!1};pt.push(U);let W=()=>{let B=pt.indexOf(U);B>=0&&pt.splice(B,1),U.messageId!==void 0&&He.delete(U.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:Te,targetMessageId:R,prompt:C}).then(B=>{let Z=B;if(Z.amended&&Z.reason==="ok"){q(1);return}if(W(),Z.reason==="target_completed"){S.notify("previous response finished \u2014 press Enter to send as a new turn"),ye.setBuffer(m,y),S.refreshPrompt();return}if(Z.reason==="target_cancelled"){S.notify("amend skipped \u2014 previous turn was cancelled"),ye.setBuffer(m,y),S.refreshPrompt();return}if(Z.reason==="target_not_found"){S.notify("amend skipped \u2014 no matching prompt"),ye.setBuffer(m,y),S.refreshPrompt();return}}).catch(B=>{W(),S.notify(`amend failed: ${B.message}`),ye.setBuffer(m,y),S.refreshPrompt()})},pa=async m=>{if(Ct.length===0){S.notify("no modes advertised by agent");return}let y=S.currentModeId(),I=Ct.findIndex(U=>U.id===y),R=I===-1?0:(I+1)%Ct.length,C=Ct[R]?.id;if(C){S.setBanner({currentMode:C});try{await h.request("session/set_mode",{sessionId:Te,modeId:C})}catch(U){S.notify(`set_mode failed: ${U.message}`)}}},vo=m=>{let y=m.replace(/\s+$/,"");if(!y.startsWith("/")||y.includes(`
|
|
192
|
+
`))return!1;let I=y.indexOf(" ");switch(I===-1?y:y.slice(0,I)){case"/quit":case"/exit":return Rr(),!0;case"/clear":return gt.clear(),Cn.clear(),fn.length=0,ee=null,O=null,se=null,qe.clear(),un.clear(),Rn.clear(),Gn.clear(),M.clear(),j.clear(),S.clearScrollback(),!0;case"/demo-plan":{S.clearKey("plan");let C=["Step 1","Step 2","Step 3","Step 4","Step 5"],U=[["pending","pending","pending","pending","pending"],["in_progress","pending","pending","pending","pending"],["completed","in_progress","pending","pending","pending"],["completed","completed","in_progress","pending","pending"],["completed","completed","completed","in_progress","pending"],["completed","completed","completed","completed","in_progress"],["completed","completed","completed","completed","completed"]],W=0,B=()=>{let Z=U[W];Z&&(E({kind:"plan",entries:C.map((Et,ve)=>({content:Et,status:Z[ve]??"pending"}))}),W+=1,setTimeout(B,600))};return B(),!0}case"/demo-tool":{let C=`demo-${Date.now()}`;return E({kind:"tool-call",toolCallId:C,title:"Terminal",status:"pending"}),setTimeout(()=>{E({kind:"tool-call-update",toolCallId:C,title:"echo hello world",status:"in_progress"})},500),setTimeout(()=>{E({kind:"tool-call-update",toolCallId:C,status:"completed"})},1500),!0}case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let U of Sr)C.push({prefix:" ",body:` ${U.name.padEnd(12)} ${U.description??""}`,bodyStyle:"info"});if(Kn.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let U of Kn)C.push({prefix:" ",body:` ${U.name.padEnd(12)} ${U.description??""}`,bodyStyle:"info"})}return S.appendLines(C),!0}case"/agent":{let C=I===-1?"":y.slice(I+1).trim(),U=ho();if(!U)return S.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let W=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let B of U.options){let Z=B.value===U.currentValue?"* ":" ";W.push({prefix:" ",body:`${Z}${B.value.padEnd(16)} ${B.name}`,bodyStyle:"info"})}return S.appendLines(W),!0}return U.options.some(W=>W.value===C)?C===U.currentValue?(S.notify(`already on agent ${C}`),!0):(S.notify(`switching to ${C}\u2026`),h.request("session/set_config_option",{sessionId:Te,configId:"agent",value:C}).catch(W=>{S.notify(`set_config_option failed: ${W.message}`)}),!0):(S.notify(`unknown agent: ${C}`),!0)}case"/sessions":return S.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;default:return!1}},Io=async(m,y,I)=>{let R=[];m.length>0&&R.push({type:"text",text:m});for(let ve of y)R.push({type:"image",data:ve.data,mimeType:ve.mimeType});q(1);let C={text:m,displayText:I??m,attachments:y,flushed:!1};pt.push(C),et=!1;let U=!1,W=null,B=ve=>{typeof z<"u"&&z!==null&&z.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:ve,bodyStyle:"tool-status-fail"}])},Z=!1;ke={text:m,attachments:y,cancel:()=>{if(et){et=!1,Z=!0,B("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Te}).catch(Fe=>{B(`force-stop failed: ${Fe.message}`)});return}if(U)return;U=!0,h.notify("session/cancel",{sessionId:Te}).catch(()=>{});let ve=Date.now();W=setTimeout(()=>{ke!==null&&(In>=ve||(et=!0,B("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},xt)}};let Et;try{let ve=await h.request("session/prompt",{sessionId:Te,prompt:R});ve&&typeof ve.stopReason=="string"&&(Et=ve.stopReason)}catch(ve){let Fe=pt.indexOf(C);Fe>=0&&pt.splice(Fe,1),C.messageId!==void 0&&He.delete(C.messageId),Z?S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):S.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:ve.message,bodyStyle:"tool-status-fail"}])}finally{if(ke=null,W!==null&&(clearTimeout(W),W=null),q(-1),C.flushed&&mt===C){let ve=C.messageId!==void 0&&Ge.has(C.messageId);ve&&C.messageId!==void 0&&Ge.delete(C.messageId);let Fe={kind:"turn-complete"};Et!==void 0&&(Fe.stopReason=Et),ve&&(Fe.amended=!0),E(Fe),mt=null}if(Jn!==null){let{text:ve,attachments:Fe}=Jn;Jn=null,ye.state().buffer.every(at=>at==="")&&(ye.setBuffer(ve,Fe),S.refreshPrompt())}}},gt=new Map,qe=new Map,un=new Map,Cn=new Map,fn=[],Qn=0,pn=`tools:${Qn}`,Rn=new Map,Gn=new Map,M=new Map,j=new Map,ee=null,O=null,se=null,ne=null,fe=null,Rt=e.tui.maxToolItems,We=e.tui.maxPlanItems,yt=()=>({maxPlanItems:fe??o.planExpanded?1/0:We}),Me=()=>{if(ne===null)return;let m=lr(ne,yt());m.length>0&&S.upsertLines("plan",[{body:""},...m])},Vt="",Xn=null,xc=0,vh=()=>{if(Xn===null)return;let m=S.width(),y=ur(Vt,m>0?{maxWidth:m}:void 0);y.length!==0&&S.upsertLines(Xn,y)},Ih=m=>{m.length!==0&&(Xn===null&&(S.ensureSeparator(),Xn=`agent:${xc}`,xc+=1,Vt=""),Vt+=m,vh())},Tn=()=>{Xn=null,Vt=""},Ps="",Ms=null,Ac=0,Sh=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),kh=()=>{if(Ms===null||Ps.length===0)return;M.set(Ms,Ps);let m=Md(Ps);m.length!==0&&S.upsertLines(Ms,m)},xh=m=>{let y=M.get(m);return y===void 0?[]:Md(y)},Ah=m=>{m.length!==0&&(Ms===null&&(S.ensureSeparator("thought"),Ms=`thought:${Ac}`,Ac+=1,Ps=""),Ps+=m,kh())},En=()=>{Ms=null,Ps=""},Cc=m=>{let{order:y,states:I,startedAt:R,endedAt:C,stopReason:U}=m,W=y.length,B=Rt>0,Z=!B||m.expanded?y:y.slice(Math.max(0,W-Rt)),Et=W-Z.length,ve=C===null,Fe=C??Date.now(),Ue=Fe-R,at=!ve&&U!==null&&U!=="end_turn"?U:null,Oc=at==="amended",Lc=Oc?`amended \xB7 ${sn(Ue)}`:`stopped (${at}) \xB7 ${sn(Ue)}`,Ao;if(W===0)at!==null?Ao=Lc:Ao=ve?`thinking \xB7 ${sn(Ue)}`:`thought \xB7 ${sn(Ue)}`;else{let ha=W===1?"tool":"tools",Co=at!==null?Lc:ve?sn(Ue):`took ${sn(Ue)}`,Hc=[`${W} ${ha}`,Co];ve&&B&&Et>0&&Hc.push(`${Et} hidden`),Ao=Hc.join(" \xB7 ")}let Bc=W===0&&ve,Nc=Oc?"tool-status-cancelled":"tool-status-fail",Dc=[{prefix:"\u2699 ",prefixStyle:Bc?"tool-status-running":at!==null?Nc:"tool",body:Ao,bodyStyle:Bc?"tool-status-running":at!==null?Nc:"dim"}];for(let ha of Z){let Co=I.get(ha);Co&&Dc.push(...fp(Co,Fe))}return Dc},Rc=m=>Gn.get(m)??o.toolsExpanded,Tt=()=>{if(ee===null)return;let m=Cc({order:fn,states:gt,startedAt:ee,endedAt:O,stopReason:se,expanded:Rc(pn)});S.upsertLines(pn,m)},Tc=m=>{let y=Rn.get(m);if(!y)return;let I=Cc({order:y.order,states:y.states,startedAt:y.startedAt,endedAt:y.endedAt,stopReason:y.stopReason,expanded:Rc(m)});S.upsertLines(m,I)},Ch=()=>{ee!==null&&!Rn.has(pn)&&Tt();for(let m of Rn.keys())Tc(m)},ma=()=>{ee!==null&&Rn.set(pn,{order:[...fn],states:new Map(gt),startedAt:ee,endedAt:O??Date.now(),stopReason:se})},Ec=()=>{Qn+=1,pn=`tools:${Qn}`,ee=Date.now(),O=null,se=null,Tt()},Pc=(m,y,I,R,C,U)=>{let W=!gt.has(m),B=gt.get(m),Z=B??{initialTitle:y??"tool",latestTitle:y??"tool",status:I??"pending",startedAt:Date.now()};B&&y!==void 0&&(Z.latestTitle=y),U!==void 0&&Z.detail===void 0&&(Z.detail=U),B&&I!==void 0&&(Z.status=I),B||(Z.status=I??"pending"),Z.endedAt===void 0&&yp(Z.status)&&(Z.endedAt=Date.now()),R!==void 0&&(Z.errorText=R),C!==void 0&&(Z.editDiff=C),gt.set(m,Z),W&&(ee===null&&(Qn+=1,pn=`tools:${Qn}`,ee=Date.now(),O=null,se=null),fn.push(m))},Mc=async m=>{try{let y=await h.request("hydra-acp/session/tool_content",{sessionId:Te,hash:m});return typeof y?.content=="string"?y.content:null}catch{return null}},So=new Set,Rh=(m,y)=>{So.has(m)||y.oldRef===void 0&&y.newRef===void 0||(So.add(m),(async()=>{let[I,R]=await Promise.all([y.oldRef?Mc(y.oldRef.hash):Promise.resolve(y.oldText),y.newRef?Mc(y.newRef.hash):Promise.resolve(y.newText)]);if(y.oldRef!==void 0&&I===null||y.newRef!==void 0&&R===null){So.delete(m);let Et=$d(y,"diff",{deferredStatus:"error"});Et.length>0&&(S.upsertLines(`editdiff:${m}`,Et),S.repaintNow());return}let U={...y.path!==void 0?{path:y.path}:{},oldText:I??"",newText:R??""};qe.set(m,U);let W=gt.get(m);W?.editDiff&&(W.editDiff=U),So.delete(m);let B=un.get(m),Z=B===void 0?o.showFileUpdates:B?"diff":"edit";Z!=="none"&&(ko(m,U,Z==="diff"?"diff":"edit"),S.repaintNow())})())},ko=(m,y,I)=>{let R=`editdiff:${m}`,C=$d(y,I);if(C.length===0){S.removeKey(R);return}S.upsertLines(R,C),I==="diff"&&(y.oldRef!==void 0||y.newRef!==void 0)&&S.notifyWhenVisible(R)},Th=m=>{if(!m.startsWith("editdiff:"))return;let y=m.slice(9),I=qe.get(y);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&Rh(y,I)},$c=m=>{let y=`editdiff:${m}`,I=o.showFileUpdates,R=gt.get(m),C;if(I==="none"||!R?.editDiff||R.status!=="completed")C=null;else{let W=un.get(m);C=W!==void 0?W?"diff":"edit":I==="diff"?"diff":"edit"}if(C===null){S.removeKey(y);return}let U=R.editDiff;qe.set(m,U),ko(m,U,C)},Eh=()=>{let m=o.showFileUpdates;for(let[y,I]of qe){let R=`editdiff:${y}`,C=un.get(y),U=C===void 0?m:C?"diff":"edit";if(U==="none"){S.removeKey(R);continue}ko(y,I,U==="diff"?"diff":"edit")}},Ph=m=>{if(m.startsWith("editdiff:")){let y=m.slice(9),I=qe.get(y);if(!I)return;let R=un.get(y)??o.showFileUpdates==="diff";un.set(y,!R),ko(y,I,R?"edit":"diff"),S.repaintNow();return}if(m==="plan"){if(ne===null)return;fe=!(fe??o.planExpanded),Me(),S.repaintNow();return}if(m.startsWith("tools:")){let y=Gn.get(m)??o.toolsExpanded;Gn.set(m,!y),m===pn&&ee!==null?Tt():Tc(m),S.repaintNow();return}if(m.startsWith("thought:")){if(!M.has(m))return;let y=j.get(m);if(y!==void 0){j.delete(m),S.setRunCollapsed(y,!1,xh(m)),S.repaintNow();return}let I=S.contiguousRun(m,new Set(M.keys()));if(I.length===0)return;let R=I[0];j.set(R,I),S.setRunCollapsed(I,!0,[Sh()]),S.repaintNow();return}};v=m=>{if(m.kind==="available-commands"){Kn=m.commands,kr();return}if(m.kind==="available-modes"){Ct=m.modes;return}if(m.kind==="config-options"){Ss=m.options;let I=m.options.find(C=>C.id==="agent");I&&I.currentValue&&I.currentValue!==Ot&&(Ot=I.currentValue,S.setSessionbar({agent:I.currentValue}));let R=m.options.find(C=>C.id==="mode");R&&(Ct=R.options.map(C=>({id:C.value,name:C.name??C.value,...C.description!==void 0?{description:C.description}:{}})));return}if(m.kind==="mode-changed"){S.setBanner({currentMode:m.mode||void 0});return}if(m.kind==="session-info"){m.title!==void 0&&S.setSessionbar({title:m.title}),m.agentId!==void 0&&m.agentId!==Ot&&(Ot=m.agentId,S.setSessionbar({agent:m.agentId}));return}if(m.kind==="usage-update"){let I=!1;m.used!==void 0&&je.used!==m.used&&(je.used=m.used,I=!0),m.size!==void 0&&je.size!==m.size&&(je.size=m.size,I=!0),m.costAmount!==void 0&&je.costAmount!==m.costAmount&&(je.costAmount=m.costAmount,I=!0),m.costCurrency!==void 0&&je.costCurrency!==m.costCurrency&&(je.costCurrency=m.costCurrency,I=!0),I&&S.setSessionbar({usage:{...je}});return}if(m.kind==="user-text"){Ir&&ft(m.text),Tn(),En(),ee!==null&&(O=Date.now(),Tt()),mt=null,S.ensureSeparator();let I=lr(m);I.length>0&&S.appendLines(I),ma(),S.clearKey("plan"),ne=null,fe=null,gt.clear(),Cn.clear(),fn.length=0,O=null,Ec(),S.redraw();return}if(m.kind==="agent-text"){En(),Ih(m.text);return}if(m.kind==="agent-thought"){Tn(),Ah(m.text);return}if(m.kind==="exit-plan-mode"){Tn(),En();let I=Cn.get(m.toolCallId),R={plan:m.plan??I?.plan??"",status:m.status??I?.status};if(Cn.set(m.toolCallId,R),R.plan.length===0)return;let C=wp(R);C.length>0&&S.upsertLines(m.toolCallId,C);return}if(m.kind==="tool-call"){Tn(),En(),Pc(m.toolCallId,m.title,m.status,void 0,m.editDiff,m.detail),Tt(),$c(m.toolCallId);return}if(m.kind==="plan"){Tn(),En(),ne=m;let I=lr(m,yt());I.length>0&&S.upsertLines("plan",[{body:""},...I]);let R=m.entries.length>0&&m.entries.every(C=>(C.status??"pending")==="completed");S.setStickyBottomKey(R?null:"plan");return}if(m.kind==="tool-call-update"){Tn(),En(),Pc(m.toolCallId,m.title,m.status,m.errorText,m.editDiff,m.detail),m.upstreamInterrupted&&(H=!0),Tt(),$c(m.toolCallId);return}m.kind==="model-changed"&&S.setSessionbar({model:m.model});let y=lr(m);if(y.length>0&&S.appendLines(y),m.kind==="turn-complete"){te=void 0,Tn(),En();let I=m.amended?"amended":m.stopReason;if(!m.amended&&H&&(I===void 0||I==="end_turn")&&(I="error"),ne!==null&&I!==void 0&&I!=="end_turn"){let R=lr({...ne,stopped:!0,amended:m.amended===!0},yt());R.length>0&&S.upsertLines("plan",[{body:""},...R])}ne=null,fe=null,S.clearKey("plan"),S.setStickyBottomKey("plan"),ee!==null?(O=Date.now(),se=I??null,Tt(),ma()):I!==void 0&&I!=="end_turn"&&I!=="amended"&&S.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${I}`,bodyStyle:"tool-status-fail"}]),gt.clear(),Cn.clear(),fn.length=0,ee=null,O=null,se=null,H=!1,S.ensureSeparator(),eh({pendingTurns:$,queueSize:Ve.size,ownTurnInFlight:ke!==null,hasInFlightHead:te!==void 0,replayDraining:x,amended:m.amended===!0})&&q(-$)}};let _c=w;w=[];let xo=[];for(let m of _c)m.kind==="user-text"&&typeof m.text=="string"&&xo.push(m.text);S.pauseRepaint(),x=!0;try{for(let m of _c)v(m)}finally{x=!1,S.resumeRepaint()}if(xo.length>0){let m=dd(nt,xo);m!==nt&&(nt=m,ut=dd(ut,xo),ye.setHistory(Zo(At,ut)),rs(Wt,nt).catch(()=>{}))}Ir=!0,dn!==void 0&&$>0?(J=dn,S.setBanner({status:"busy",elapsedMs:Date.now()-dn}),D===null&&(D=setInterval(()=>{J===null||z===null||(z.setBanner({elapsedMs:Date.now()-J}),Tt())},1e3)),ee===null&&Ec(),ee=dn,Tt()):dn===void 0&&$>0&&q(-$);let Mh=()=>{if(ue){let m=ue.resolve;ue=null,S.setPermissionPrompt(null),m({outcome:{outcome:"cancelled"}})}Tn(),En()},Fc=()=>{ee!==null&&(O=Date.now(),se="reconnect-recovery-failed",Tt(),ma(),gt.clear(),Cn.clear(),fn.length=0,ee=null,O=null,se=null)};return p=()=>{S.setBanner({status:"disconnected",elapsedMs:void 0})},u=async()=>{Mh();let m={jsonrpc:"2.0",id:`tui-reinit-${sh()}`,method:"initialize",params:{protocolVersion:It,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:le}}};try{await g.request(m)}catch{}let y=xe!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${sh()}`,method:"session/attach",params:{sessionId:Te,historyPolicy:y?"after_message":"none",...y?{afterMessageId:xe}:{},clientInfo:{name:"hydra-acp-tui",version:le},...(()=>{let B={};return qn!==void 0&&(B.resume={upstreamSessionId:qn,agentId:Ot,cwd:lt}),e.tui.toolContent==="references"&&(B.toolContent="references"),Object.keys(B).length>0?{_meta:{[Mt]:B}}:{}})()}};X=[];let R,C,U;try{let B=await g.request(I);if(B.error)throw new Error(B.error.message);U=Zm(B.result),R=U.appliedPolicy,U.clientId!==void 0&&(tt=U.clientId)}catch(B){C=B}let W=X??[];if(X=null,C)Fc(),S.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(y&&R!=="after_message")Fc(),S.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{x=!0;try{for(let B of W)Y(B)}finally{x=!1}}if(U){let B=th({daemonTurnStartedAt:U.turnStartedAt,pendingTurns:$});B.pendingTurnsDelta!==0&&q(B.pendingTurnsDelta),B.banner==="busy"&&B.busySince!==void 0?(J=B.busySince,S.setBanner({status:"busy",elapsedMs:Date.now()-B.busySince}),D===null&&(D=setInterval(()=>{J===null||z===null||(z.setBanner({elapsedMs:Date.now()-J}),Tt())},1e3))):S.setBanner({status:"ready",elapsedMs:void 0})}else S.setBanner({status:$>0?"busy":"ready",elapsedMs:$>0?0:void 0})},h.onClose(m=>{m&&t.red(`
|
|
193
193
|
connection lost: ${m.message}
|
|
194
|
-
`),P(m?1:0)}),process.on("SIGINT",
|
|
195
|
-
`),null)}for(;;){let i=await yn(n,{includeNonInteractive:!0}),a=await
|
|
194
|
+
`),P(m?1:0)}),process.on("SIGINT",Cs),s.initialPrompt&&a.sessionId==="__new__"&&Dt(s.initialPrompt,[]),await xs}async function xk(t,e,n,s,r){let o=s.cwd??process.cwd();if(s.sessionId){let i={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(i.resumeHint=s.resumeHint),i}if(s.forceNew)return await ih(t,n,s)!=="ok"?null:oh(s,o,e);if(s.resume){let i=await yn(n,{cwd:o,all:!0}),a=_i(i,o);return a?{sessionId:a.sessionId,agentId:a.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
|
|
195
|
+
`),null)}for(;;){let i=await yn(n,{includeNonInteractive:!0}),a=await yc(t,{cwd:o,sessions:i,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(a.kind==="abort"||a.kind==="exit")return null;if(a.kind==="new"){a.prompt!==void 0&&(s.initialPrompt=a.prompt);let l=await ih(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return oh(s,o,e)}if(a.kind==="fork"){let l=await ch(t,n,a,i);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}s.readonly=a.readonly===!0;let d=i.find(l=>l.sessionId===a.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let l=await dh(t,d,a,s);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await co(d.cwd)).ok){let f=await mo(t,d,{defaultCwd:Ht(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let u=a.agentId??d.agentId??"";return{sessionId:a.sessionId,agentId:u,cwd:f.path,resumeHint:{agentId:u,cwd:f.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:o}}}async function dh(t,e,n,s){for(;;){let r=await Pm(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let o=await mo(t,e);if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let i=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:i,cwd:o.path,resumeHint:{agentId:i,cwd:o.path,upstreamSessionId:""}}}}}async function ch(t,e,n,s){let r=s.find(d=>d.sessionId===n.sourceSessionId),o=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,i=n.sourceCwd;if(o){if(!r)return{kind:"back"};let d=await mo(t,r);if(d.kind==="cancel")return{kind:"cancel"};if(d.kind==="back")return{kind:"back"};i=d.path}let a;try{a=await qf(e,n.sourceSessionId,o?{cwd:i}:{})}catch(d){return t.red(`
|
|
196
196
|
fork failed: ${d.message}
|
|
197
|
-
`),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:i,...o?{resumeHint:{agentId:n.sourceAgentId??"",cwd:i,upstreamSessionId:""}}:{}}}}function oh(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function ih(t,e,n){if(n.agentId||await Zc())return"ok";let s;try{s=await jf(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await Hm(t,s);if(r.kind==="cancel")return"cancel";if(r.kind==="back")return"back";if(n.agentId=r.agentId,r.persist)try{await Eo(r.agentId)}catch{}return"ok"}function
|
|
198
|
-
`)}catch{}}function
|
|
199
|
-
`))}}}function
|
|
197
|
+
`),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:i,...o?{resumeHint:{agentId:n.sourceAgentId??"",cwd:i,upstreamSessionId:""}}:{}}}}function oh(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function ih(t,e,n){if(n.agentId||await Zc())return"ok";let s;try{s=await jf(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await Hm(t,s);if(r.kind==="cancel")return"cancel";if(r.kind==="back")return"back";if(n.agentId=r.agentId,r.persist)try{await Eo(r.agentId)}catch{}return"ok"}function Ak(t,e){Ck({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function Ck(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?T.tuiLogFile():e;if(n.length!==0)try{Tk(n);let s=JSON.stringify({t:new Date().toISOString(),...t});hk(n,`${s}
|
|
198
|
+
`)}catch{}}function Rk(t,e){let n=!1,s="",r=!1,o=d=>{n||d===3&&r||d===0&&!r||(r=d===3,process.stdout.write(`\x1B]9;4;${d}\x1B\\`))},i=d=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(d),s=d)},a=d=>{let c=`${d.agentId}@${d.version}`;if(d.source==="npm")return d.phase==="install_start"||d.phase==="download_start"?`${e} installing ${c} via npm\u2026`:d.phase==="installed"?`${e} ${c} installed`:`${e} installing ${c} via npm\u2026`;if(d.phase==="download_start"||d.phase==="download_progress"){let l=d.receivedBytes??0,f=d.totalBytes??0,u=(l/1e6).toFixed(1);if(f>0){let p=(f/1e6).toFixed(1),g=Math.min(100,Math.floor(l/f*100));return`${e} downloading ${c} ${u}/${p} MB (${g}%)`}return`${e} downloading ${c} ${u} MB`}return d.phase==="download_done"?`${e} downloaded ${c}, verifying\u2026`:d.phase==="extract"?`${e} extracting ${c}\u2026`:d.phase==="installed"?`${e} ${c} installed`:s||e};return{write(d){n||(t.brightYellow(d),s=d)},applyProgress(d){if(n)return;d.phase==="download_start"||d.phase==="download_progress"||d.phase==="install_start"||d.phase==="extract"||d.phase==="download_done"?o(3):d.phase==="installed"&&o(0),i(a(d))},finalize(){n||(n=!0,o(0),process.stdout.write(`
|
|
199
|
+
`))}}}function Tk(t){try{if(gk(t).size<lh)return;yk(t,`${t}.0`)}catch{}}var vk,Sk,lh,uh=V(()=>{"use strict";Fr();dt();Jd();_e();Gd();Hs();Zr();ui();$o();tn();de();jt();Yi();Yd();ei();Fi();Om();Nm();pc();Um();cc();Zd();ea();Jm();da();Xm();nh();ds();so();vk=12e4;Sk=[["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 live session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];lh=5*1024*1024});var fh={};_h(fh,{runTui:()=>ah});var ph=V(()=>{"use strict";uh()});import{readFileSync as Ek}from"fs";import{fileURLToPath as Pk}from"url";import{dirname as Mk,resolve as $k}from"path";var Uc=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),Fh=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function jc(t){for(let e of Object.keys(t))if(!Uc.has(e)&&!Fh.has(e))return e}function ga(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let o=r.indexOf("=");if(o!==-1){let d=r.slice(2,o);n[d]=r.slice(o+1),s+=1;continue}let i=r.slice(2);if(Uc.has(i)){n[i]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[i]=a,s+=2;continue}n[i]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function Oh(t,e){let n=t[e];if(typeof n=="string")return n}function $s(t,e){return t[e]===!0||t[e]==="true"}var Lh="HYDRA_ACP_";function Bh(t){return Lh+t.toUpperCase().replace(/-/g,"_")}function ze(t,e){let n=Oh(t,e);return n!==void 0?n:process.env[Bh(e)]}_e();Hs();async function dl(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let o=Ia(n);return{target:await il(o,{allowPrompt:e.allowPrompt}),sessionId:o.sessionId,fromUrl:!0}}let s=await G();return{target:await Qt(s),sessionId:n,fromUrl:!1}}function Ra(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}de();_e();wt();import*as cl from"fs/promises";async function ll(t){if(await cl.mkdir(T.home(),{recursive:!0}),await To(),!await Os()){let n=Fs();await Ls(n),process.stdout.write(`Initialized ${T.authToken()}
|
|
200
200
|
Service token: ${n}
|
|
201
|
-
`);return}if($s(t,"rotate-token")){let n=Fs();await Ls(n),process.stdout.write(`Rotated token in ${
|
|
201
|
+
`);return}if($s(t,"rotate-token")){let n=Fs();await Ls(n),process.stdout.write(`Rotated token in ${T.authToken()}
|
|
202
202
|
New token: ${n}
|
|
203
|
-
`);return}process.stdout.write(`Service token already exists at ${
|
|
203
|
+
`);return}process.stdout.write(`Service token already exists at ${T.authToken()}.
|
|
204
204
|
`),process.stdout.write(`Pass --rotate-token to generate a new service token.
|
|
205
|
-
`)}de();_e();wt();import*as Of from"fs/promises";import{setTimeout as
|
|
205
|
+
`)}de();_e();wt();import*as Of from"fs/promises";import{setTimeout as Jb}from"timers/promises";import Ff from"chalk";import*as Mf from"fs";import*as Ln from"fs/promises";import Bb from"fastify";import Nb from"@fastify/websocket";var ul="acp.v1";function fl(t,e){return t.has(ul)?ul:!1}_e();import Pf from"pino";import Db from"pino-roll";de();import*as Xe from"fs/promises";import{createHash as ng}from"crypto";import{gzip as sg,gunzip as rg}from"zlib";import{promisify as pl}from"util";var ml=pl(sg),og=pl(rg),hl=/^[A-Za-z0-9_-]+$/,ig=/^[a-f0-9]{64}$/,Ta=!0;function gl(t){Ta=t}function _o(t,e){return hl.test(t)?e===void 0||ig.test(e):!1}function Fo(t,e){return`${T.toolBlobFile(t,e)}.gz`}async function Ea(t,e){if(!_o(t))return null;let n=ng("sha256").update(e,"utf8").digest("hex"),s=Fo(t,n),r=T.toolBlobFile(t,n);for(let a of[s,r])try{return await Xe.access(a),n}catch{}await Xe.mkdir(T.toolsDir(t),{recursive:!0});let o=Ta?s:r,i=Ta?await ml(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Xe.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Oo(t,e){if(!_o(t,e))return null;try{let n=await Xe.readFile(Fo(t,e));return(await og(n)).toString("utf8")}catch{}try{return await Xe.readFile(T.toolBlobFile(t,e),"utf8")}catch{return null}}async function yl(t,e){if(!_o(t,e))return null;try{return await Xe.readFile(Fo(t,e))}catch{}try{let n=await Xe.readFile(T.toolBlobFile(t,e));return await ml(n)}catch{return null}}async function wl(t,e,n){if(!_o(t,e))return;let s=Fo(t,e);try{await Xe.access(s);return}catch{}await Xe.mkdir(T.toolsDir(t),{recursive:!0}),await Xe.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function bl(t){hl.test(t)&&await Xe.rm(T.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}de();Zn();import*as Pl from"fs/promises";import*as Bo from"path";import{z as oe}from"zod";de();import*as Il from"fs";import*as rt from"fs/promises";import*as Mn from"path";import{spawn as Sl}from"child_process";import{Readable as ag}from"stream";function Gt(){let t=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!t||!e))return`${t}-${e}`}function $a(t,e=Gt()){if(e)return t[e]}var Us=t=>{process.stderr.write(t+`
|
|
206
206
|
`)};function _a(t){Us=t??(e=>process.stderr.write(e+`
|
|
207
|
-
`))}async function kl(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Gt()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Gt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=
|
|
207
|
+
`))}async function kl(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Gt()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Gt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=T.agentInstallDir(t.agentId,e,t.version),s=Mn.resolve(n,t.target.cmd);if(await Ma(s))return s;if(await dg({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Ma(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await rt.chmod(s,493).catch(()=>{}),s}async function dg(t){await rt.mkdir(Mn.dirname(t.installDir),{recursive:!0});let e=await rt.mkdtemp(`${t.installDir}.partial-`);try{Us(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await cg({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});Us(`hydra-acp: extracting ${t.agentId}`),js(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await ug(n,e),await rt.unlink(n).catch(()=>{});try{await rt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Ma(t.installDir)){await rt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),js(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Us(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),js(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await rt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function js(t,e){if(t)try{t(e)}catch{}}async function cg(t){let e=lg(t.url),n=Mn.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),o=Il.createWriteStream(n),i=ag.fromWeb(s.body);js(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,d=Date.now(),c=0,l=2e3,f=150;return i.on("data",u=>{a+=u.length;let p=Date.now();p-c>=f&&(c=p,js(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-d>=l&&(d=p,Us(vl(t.agentId,a,r)))}),await new Promise((u,p)=>{i.on("error",p),o.on("error",p),o.on("finish",()=>u()),i.pipe(o)}),Us(vl(t.agentId,a,r,!0)),js(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function vl(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let i=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function lg(t){let e=new URL(t);return Mn.posix.basename(e.pathname)||"archive"}async function ug(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Pa("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await fg("unzip")){await Pa("unzip",["-q",t,"-d",e]);return}await Pa("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Pa(t,e){return new Promise((n,s)=>{let r=Sl(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(o,i)=>{if(o===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function fg(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Sl(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Ma(t){try{return await rt.access(t),!0}catch{return!1}}de();import*as vt from"fs/promises";import*as Xt from"path";import{spawn as pg}from"child_process";var Oa=t=>{process.stderr.write(t+`
|
|
208
208
|
`)};function La(t){Oa=t??(e=>process.stderr.write(e+`
|
|
209
|
-
`))}async function Al(t){let e=Gt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=
|
|
210
|
-
stderr: ${l}`:`npm install ${t.packageSpec} failed (${c})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<
|
|
209
|
+
`))}async function Al(t){let e=Gt();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=T.agentNpmInstallDir(t.agentId,e,t.version),s=wg(t.packageSpec),r=bg(s),o={installDir:n,packageName:s,hint:t.bin,basename:r},i=Xt.join(n,"node_modules",".bin",t.bin);if(await es(i))return i;if(await es(n)){let f=await xl(o);if(f)return f.binPath}await mg({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await xl(o);if(a)return a.binPath;let d=await Rl(n,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],l=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function mg(t){await vt.mkdir(Xt.dirname(t.installDir),{recursive:!0});let e=await vt.mkdtemp(`${t.installDir}.partial-`);try{Oa(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Fa(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await yg({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await vt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await es(t.installDir)){await vt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Fa(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Oa(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Fa(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await vt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Fa(t,e){if(t)try{t(e)}catch{}}var hg=5,gg=25;function yg(t){return Cl(t,0)}async function Cl(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],o;try{o=pg("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),o.on("exit",(a,d)=>{if(a===0){n();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,l=i.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${c})
|
|
210
|
+
stderr: ${l}`:`npm install ${t.packageSpec} failed (${c})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<hg)return await new Promise(r=>setTimeout(r,gg*(e+1))),Cl(t,e+1);throw n}}function wg(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function bg(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Rl(t,e){let n=Xt.join(t,"node_modules",e,"package.json");try{let s=await vt.readFile(n,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function xl(t){let e=Xt.join(t.installDir,"node_modules",".bin"),n=Xt.join(e,t.hint);if(await es(n))return{binName:t.hint,binPath:n};let s=await Rl(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let o=r[0],i=Xt.join(e,o);if(await es(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[t.hint,t.basename])if(r.includes(o)){let i=Xt.join(e,o);if(await es(i))return{binName:o,binPath:i}}}}if(t.basename!==t.hint){let r=Xt.join(e,t.basename);if(await es(r))return{binName:t.basename,binPath:r}}}async function es(t){try{return await vt.access(t),!0}catch{return!1}}var vg=oe.object({package:oe.string(),bin:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),qs=oe.object({archive:oe.string().url().optional(),cmd:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),Ig=oe.object({"darwin-aarch64":qs.optional(),"darwin-x86_64":qs.optional(),"linux-aarch64":qs.optional(),"linux-x86_64":qs.optional(),"windows-x86_64":qs.optional(),"windows-aarch64":qs.optional()}),Sg=oe.object({package:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),kg=oe.object({command:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),xg=oe.object({npx:vg.optional(),binary:Ig.optional(),uvx:Sg.optional(),exec:kg.optional()}),Ag=oe.object({id:oe.string(),name:oe.string(),version:oe.string().optional(),description:oe.string().optional(),authors:oe.array(oe.string()).optional(),license:oe.string().optional(),icon:oe.string().optional(),repository:oe.string().optional(),website:oe.string().optional(),distribution:xg}),Tl=oe.object({version:oe.string(),agents:oe.array(Ag),extensions:oe.array(oe.unknown()).optional()}),Lo=class{constructor(e,n={}){this.config=e;this.options=n}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let n=this.localAgents().find(i=>i.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(i=>i.id===e);if(r)return this.applyOverride(r);let o=s.agents.find(i=>Ba(i)===e);return o?this.applyOverride(o):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:n.command??e,args:n.args,env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:Cg(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=Tl.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(s)).catch(()=>{}),r}async readDiskCache(){let e=await Pt(T.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Tl.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await bt(T.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Cg(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Ba(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ws(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(i){if(e.length===0)throw i;n={version:"local-only",agents:[]}}let s=new Set(e.map(i=>i.id)),r=[...e,...n.agents.filter(i=>!s.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await Na(i),source:s.has(i.id)?"local":"registry"})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:o}}async function Na(t){let e=Gt();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=$a(t.distribution.binary,e);if(s?.cmd){let r=Bo.resolve(T.agentInstallDir(t.id,e,n),s.cmd);if(await El(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Ba(t)??s.package,o=T.agentNpmInstallDir(t.id,e,n),i=Bo.join(o,"node_modules",".bin",r);if(await El(i))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function El(t){try{return await Pl.access(t),!0}catch{return!1}}async function $n(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:s};let i=r.bin??Ba(t)??r.package,a=n.onInstallProgress;return{command:await Al({agentId:t.id,version:s,packageSpec:r.package,bin:i,registry:n.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:o,env:r.env??{},version:s}}if(t.distribution.binary){let r=$a(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Gt()??"this platform"}.`);let o=n.onInstallProgress,i=await kl({agentId:t.id,version:s,target:r,onProgress:o?d=>o({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:s}}if(t.distribution.uvx){let r=t.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as Mg}from"child_process";import*as qo from"fs";import*as Wl from"path";dt();function jo(t,e){let n="",s=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let d of r)d(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let d=n.indexOf(`
|
|
211
211
|
`);for(;d!==-1;){let c=n.slice(0,d).trim();if(n=n.slice(d+1),c.length>0)try{let l=JSON.parse(c);for(let f of s)f(l)}catch(l){for(let f of s)f({jsonrpc:"2.0",id:0,error:{code:N.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}d=n.indexOf(`
|
|
212
212
|
`)}}),t.on("end",()=>i()),t.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)+`
|
|
213
|
-
`;await new Promise((c,l)=>{e.write(d,f=>{if(f){l(f);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}Fr();de();var
|
|
213
|
+
`;await new Promise((c,l)=>{e.write(d,f=>{if(f){l(f);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}Fr();de();var $g=4096,_n=class t{agentId;version;cwd;connection;child;exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??$g,this.killEscalationMs=e.killEscalationMs??_g,this.logger=e.logger,this.fileLog=Fg(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
|
|
214
214
|
`),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=jo(n.stdout,n.stdin);this.connection=new Zt(s),n.stderr?.setEncoding("utf8"),n.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),n.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
|
|
215
215
|
`),this.connection.fail(new Error(o))}),n.on("exit",(r,o)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${o} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
|
|
216
216
|
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${n.pid} exited after kill code=${r} signal=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${r} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${n.pid} exited unexpectedly code=${r} signal=${o}`)}for(let i of this.exitHandlers)i(r,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let n=this.stderrTail.trim();return n?`${e}
|
|
217
|
-
stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=
|
|
217
|
+
stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=Mg(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
|
|
218
218
|
`),this.logger?.info(`agent ${this.agentId} pid=${this.child.pid} kill requested signal=${e}`),await this.connection.close().catch(()=>{}),this.signalProcessGroup(e),await this.waitForExit(this.killEscalationMs),!this.exited&&(this.writeLog(`--- kill escalating signal=SIGKILL time=${new Date().toISOString()} ---
|
|
219
|
-
`),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}}
|
|
220
|
-
`,
|
|
221
|
-
`),n)}function
|
|
219
|
+
`),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},_g=2e3;function Fg(t){try{let e=T.agentLogFile(t);qo.mkdirSync(Wl.dirname(e),{recursive:!0});let n=qo.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as is from"fs/promises";import*as ri from"os";import*as Wr from"path";import{customAlphabet as zy}from"nanoid";tn();Xa();de();Zn();import*as gn from"fs/promises";import{z as nn}from"zod";var wy=nn.object({version:nn.literal(1),agentId:nn.string(),upstreamSessionId:nn.string(),deletedAt:nn.string(),upstreamUpdatedAt:nn.string().optional(),cwd:nn.string().optional(),title:nn.string().optional(),reason:nn.enum(["user","expired"]).optional(),interactive:nn.boolean().optional()}),Yo=class{async add(e){let n={version:1,...e};await bt(T.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await gn.access(T.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=T.tombstoneFile(e,n),r=await Pt(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return wy.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await gn.unlink(T.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await gn.rmdir(T.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let n;try{n=await gn.readdir(T.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let o;try{o=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(o))}return s}async listForAgent(e){let n;try{n=await gn.readdir(T.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&s.push(i)}return s}};function au(t,e){return e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as wu from"fs/promises";dt();jt();Ko();var du=`[older history truncated]
|
|
220
|
+
`,Iy=["file_path","path","command","pattern","query"];function cu(t,e={}){let n=e.maxChars??4e5,s=[],r="",o=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let i of t){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"){o();let l=Ay(d.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(c==="agent_message_chunk"){let l=Cy(d.content);l.length>0&&(r+=l)}else c==="tool_call"?(o(),s.push(Sy(d))):c==="turn_complete"&&o()}return o(),Ty(s.join(`
|
|
221
|
+
`),n)}function Sy(t){let e=ky(t),n=xy(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function ky(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function xy(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of Iy){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${Ry(r,200)}`)}return n}function Ay(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function Cy(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function Ry(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function Ty(t,e){if(t.length<=e)return t;let n=t.split(`
|
|
222
222
|
`);for(;n.length>0;){let s=du+n.join(`
|
|
223
|
-
`);if(s.length<=e)return s;n.shift()}return du}var
|
|
223
|
+
`);if(s.length<=e)return s;n.shift()}return du}var Ey=12e4;async function uu(t){let e=t.timeoutMs??Ey,n,s,r=!1;try{let o=(async()=>{n=_n.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let i=await n.connection.request("initialize",{protocolVersion:It,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:le}}),a=await n.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),d=a.sessionId;if(typeof d!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`);return}if(t.modelId){let g=My(a);if(g.size===0||g.has(t.modelId))try{await n.connection.request("session/set_model",{sessionId:d,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let c=[];n.connection.onNotification("session/update",g=>{let h=Py(g);h.length>0&&c.push(h)});let l=cu(t.history,{maxChars:t.maxTranscriptChars}),f=l.length>0?`${l}
|
|
224
224
|
|
|
225
|
-
${za}`:za;await n.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:f}]});let u=c.join(""),p=iu(u);return p||t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse as snapshot JSON (replyLen=${u.length} preview=${JSON.stringify(u.slice(0,200))})`),p})();return await new Promise((i,a)=>{s=setTimeout(()=>{r=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${e}ms`),i(void 0)},e),s.unref?.(),o.then(d=>{s&&clearTimeout(s),r||i(d)},d=>{s&&clearTimeout(s),r||a(d)})})}catch(o){t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${o.message}`);return}finally{s&&clearTimeout(s),n&&await n.kill().catch(()=>{})}}function
|
|
226
|
-
`;await ot.appendFile(
|
|
225
|
+
${za}`:za;await n.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:f}]});let u=c.join(""),p=iu(u);return p||t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse as snapshot JSON (replyLen=${u.length} preview=${JSON.stringify(u.slice(0,200))})`),p})();return await new Promise((i,a)=>{s=setTimeout(()=>{r=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${e}ms`),i(void 0)},e),s.unref?.(),o.then(d=>{s&&clearTimeout(s),r||i(d)},d=>{s&&clearTimeout(s),r||a(d)})})}catch(o){t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${o.message}`);return}finally{s&&clearTimeout(s),n&&await n.kill().catch(()=>{})}}function Py(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function My(t){let e=new Set;lu(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&lu(e,n.availableModels),e}function lu(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}td();de();var $y=2,Go=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??$y}opts;queued=new Set;inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.queued.has(e)||this.inflight.has(e)||(this.queued.add(e),this.drain())}size(){return{queued:this.queued.size,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;this.queued.size>0||this.inflight.size>0;){let s=n-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued.clear(),await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&this.queued.size>0;){let e=this.queued.values().next().value;if(!e)return;this.queued.delete(e);let n=this.runOne(e).finally(()=>{this.inflight.delete(e),this.drain()});this.inflight.set(e,n)}}async runOne(e){try{let n=await this.opts.store.read(e);if(!n){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let s=await this.opts.histories.load(e),r=n.summarizedThroughEntry;if(r!==void 0&&s.length<=r){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${s.length})`);return}let o=this.opts.synopsisAgent??n.agentId,i=await this.opts.registry.getAgent(o);if(!i){this.opts.logger?.warn(`synopsis: agent ${o} not in registry for session ${e}; skipping`);return}let a=await $n(i,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=T.sessionDir(e);await wu.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${o} historyLen=${s.length} model=${JSON.stringify(d??"(default)")} cwd=${c}`);let l=await uu({agentId:o,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!l){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}l.title&&await this.opts.persistTitle(e,l.title);let f=_y(l.synopsis,s);f&&Fy(f)?(await this.opts.persistSynopsis(e,f,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!l.title)} fields=${Oy(f)}`)):l.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(n){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${n.message}`)}}};function _y(t,e){let n=hu(e),s=mu(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function Fy(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function Oy(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}de();import*as ot from"fs/promises";function bu(t){return t==="summary"?"summary":"inline"}var nd=256;function vu(t,e){return e!=="summary"?t:t.map(Ly)}function Ly(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(Iu));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=sd(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),o.rawOutput=d}return{...t,params:{...n,update:o}}}function By(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Iu(t){if(By(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=sd(e.text)),typeof e.content=="string"?n.content=sd(e.content):e.content&&typeof e.content=="object"&&(n.content=Iu(e.content)),n}function sd(t){if(typeof t=="string"&&t.length>nd){let e=t.length-nd;return`${t.slice(0,nd)}\u2026[+${e} chars omitted from summary export]`}return t}var Ny=2048;function Su(t){let e=new Set,n=s=>{if(ku(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function ku(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Dy(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function id(t,e){if(!Dy(t))return t;let n=t.params,s=n.update,r=await rd(s,e);return{...t,params:{...n,update:r}}}async function rd(t,e){if(typeof t=="string"){if(t.length<=Ny)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await rd(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await rd(r,e);return n}return t}async function xu(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await od(n,e);return s===n?t:{...t,params:s}}async function od(t,e){if(ku(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let o=await od(r,e);o!==r&&(n=!0),s.push(o)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,o]of Object.entries(t)){let i=await od(o,e);i!==o&&(n=!0),s[r]=i}return n?s:t}return t}var Dr=/^[A-Za-z0-9_-]+$/,Hy=1e3,Xo=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Hy}async append(e,n){if(Dr.test(e))return this.enqueue(e,async()=>{await ot.mkdir(T.sessionDir(e),{recursive:!0});let s=await id(n,o=>Ea(e,o)),r=JSON.stringify(s)+`
|
|
226
|
+
`;await ot.appendFile(T.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Dr.test(e))return this.enqueue(e,async()=>{await ot.mkdir(T.sessionDir(e),{recursive:!0});let s=[];for(let o of n)s.push(await id(o,i=>Ea(e,i)));let r=s.length===0?"":s.map(o=>JSON.stringify(o)).join(`
|
|
227
227
|
`)+`
|
|
228
|
-
`;await ot.writeFile(
|
|
229
|
-
`).filter(i=>i.length>0);if(r.length<=n)return;let o=r.slice(-n);await ot.writeFile(
|
|
228
|
+
`;await ot.writeFile(T.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Dr.test(e))return this.enqueue(e,async()=>{let s;try{s=await ot.readFile(T.historyFile(e),"utf8")}catch(i){if(i.code==="ENOENT")return;throw i}let r=s.split(`
|
|
229
|
+
`).filter(i=>i.length>0);if(r.length<=n)return;let o=r.slice(-n);await ot.writeFile(T.historyFile(e),o.join(`
|
|
230
230
|
`)+`
|
|
231
|
-
`,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Dr.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await ot.readFile(
|
|
232
|
-
`)){if(f.length===0)continue;let u;try{u=JSON.parse(f)}catch{continue}if(!u||typeof u!="object"||Array.isArray(u))continue;let p=u;typeof p.method=="string"&&typeof p.recordedAt=="number"&&i.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=i.length>this.maxEntries?i.slice(-this.maxEntries):i;if(!s)return a;let d=new Map,c=async f=>{let u=d.get(f);if(u!==void 0)return u;let p=await Oo(e,f);return d.set(f,p),p},l=[];for(let f of a)l.push(await xu(f,c));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Dr.test(e))return this.enqueue(e,async()=>{try{await ot.unlink(
|
|
233
|
-
`),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=$u(a??{}),c=e.agentModes??Eu(Mu(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(h=>h.id))}`);let l=await _u({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=Tu(a??{}),u=Eu(Pu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Fu({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let h=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new Vs({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:h=>this.bootstrapAgent({...h,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:u,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:[],onInstallProgress:e.onInstallProgress,model:e.currentModel}),r=e.agentModes??s.initialModes,o=await _u({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await Fu({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Vs({sessionId:e.hydraSessionId,cwd:n,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await as.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Ht(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=N.AgentNotInstalled,p}let s=await _n(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:ri.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:It,clientCapabilities:{},clientInfo:{name:"hydra",version:le}})}catch(p){throw await r.kill().catch(()=>{}),p}if((o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=R.sessionsDir(),f=[],u=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){u+=1;continue}if(Jy(p.cwd,l)){u+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!au(h,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let w=`${hn}${ti()}`,v=new Date().toISOString(),b=p.updatedAt??v,A={sessionId:w,lineageId:Br(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(A.title=p.title);let T=Ga(A);await this.store.write(T),f.push({version:1,...T})}return{synced:f,skipped:u}}async collectAgentSessions(e){let n=[],s;for(let r=0;r<100;r+=1){let o={};s!==void 0&&(o.cursor=s);let i=await e.connection.request("session/list",o),a=Array.isArray(i.sessions)?i.sessions:[];for(let d of a){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let c={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(c.title=d.title),typeof d.updatedAt=="string"&&(c.updatedAt=d.updatedAt),n.push(c)}if(typeof i.nextCursor!="string"||i.nextCursor.length===0)break;s=i.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let n=await this.registry.getAgent(e.agentId);if(!n){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=N.AgentNotInstalled,o}let s=await _n(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let i=(await r.connection.request("initialize",{protocolVersion:It,clientCapabilities:{},clientInfo:{name:"hydra",version:le}})).agentCapabilities,a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=Tu(a),l=Pu(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==c){let g=Js(f,l),h=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,f,h)&&(c=f);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${h} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let w=l.map(v=>v.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${w}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let u=Mu(a),p=$u(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:i,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await r.kill().catch(()=>{}),o}}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let s=ni({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}e.firstPromptSeeded&&this.synopsisOnClose&&this.synopsisCoordinator.schedule(e.sessionId)}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:Lu(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=Ky(e,n);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return Oo(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:Vy(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId}}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=ns(r.update.prompt),i=Wa(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let n of this.sessions.values()){let s=n.agent.agentId,r=n.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(hn))return;let n=hn+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=N.SessionNotFound,s}return n}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(n);i&&i.promise===o&&this.listCache.delete(n)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=i=>e.includeNonInteractive?!0:i===!0;for(let i of this.sessions.values()){if(e.cwd&&i.cwd!==e.cwd)continue;s.add(i.sessionId);let a=await cd(i.sessionId),d=ni({interactive:i.interactive,...i.originatingClient?{originatingClient:i.originatingClient}:{}},a.hasContent);if(!r(d))continue;let c=a.mtime??new Date(i.updatedAt).toISOString();n.push({sessionId:i.sessionId,upstreamSessionId:i.upstreamSessionId,cwd:i.cwd,title:i.title,agentId:i.agentId,currentModel:i.currentModel,currentUsage:i.currentUsage,parentSessionId:i.parentSessionId,forkedFromSessionId:i.forkedFromSessionId,forkedFromMessageId:i.forkedFromMessageId,originatingClient:i.originatingClient,interactive:d,updatedAt:c,attachedClients:i.attachedCount,status:"live",busy:i.turnStartedAt!==void 0,awaitingInput:i.awaitingInput})}let o=await this.store.list().catch(()=>[]);for(let i of o){if(s.has(i.sessionId)||e.cwd&&i.cwd!==e.cwd)continue;let a=await cd(i.sessionId),d=ni(i,a.hasContent);if(!r(d))continue;let c=a.mtime??i.updatedAt;n.push({sessionId:i.sessionId,upstreamSessionId:i.upstreamSessionId,cwd:i.cwd,title:i.title,agentId:i.agentId,currentModel:i.currentModel,currentUsage:i.currentUsage?{...i.currentUsage,costAmount:(i.currentUsage.cumulativeCost??0)+(i.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:i.importedFromMachine,importedFromUpstreamSessionId:i.importedFromUpstreamSessionId,parentSessionId:i.parentSessionId,forkedFromSessionId:i.forkedFromSessionId,forkedFromMessageId:i.forkedFromMessageId,originatingClient:i.originatingClient,interactive:d,updatedAt:c,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return n.sort((i,a)=>i.updatedAt<a.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=Br(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),r=l}let o=n.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Ou(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let d={};for(let c of Su(i)){let l=await yl(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=N.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${hn}${ti()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=N.SessionNotFound,g}let r=n.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=N.AgentNotInstalled,h}let i=await this.histories.load(e).catch(()=>[]),a,d;if(n.forkAt!==void 0){if(a=qa(i,n.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw g.code=N.InvalidParams,g}d=n.forkAt}else{let g=Qy(i);if(!g){let h=new Error(`source session ${e} has no completed turns to fork from`);throw h.code=N.InvalidParams,h}a=g.index,d=g.messageId}let c=i.slice(0,a+1),l=await Ou(e),f={...s,lineageId:Br(),agentId:r,...o?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},u=qr({record:f,history:c,promptHistory:l.length>0?l:void 0,hydraVersion:le,machine:ri.hostname()}),p=`${hn}${ti()}`;return await this.writeImportedRecord({sessionId:p,bundle:u,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:d}),{sessionId:p,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await wl(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await as.utimes(R.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await os(R.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await cd(e),r=ni(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,title:n,updatedAt:new Date().toISOString()})})}async persistSynopsis(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,synopsis:n,summarizedThroughEntry:s,updatedAt:new Date().toISOString()})})}async persistAgentChange(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,agentId:n,upstreamSessionId:s,updatedAt:new Date().toISOString()})})}async persistSnapshot(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},...n.currentMode!==void 0?{currentMode:n.currentMode}:{},...n.currentUsage!==void 0?{currentUsage:n.currentUsage}:{},...n.agentCommands!==void 0?{agentCommands:n.agentCommands}:{},...n.agentModes!==void 0?{agentModes:n.agentModes}:{},...n.agentModels!==void 0?{agentModels:n.agentModels}:{},...n.interactive!==void 0?{interactive:n.interactive}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},updatedAt:new Date().toISOString()})})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).then(n,n),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(n=>n.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Xl(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(d=>r-d.enqueuedAt<Ru),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${n.sessionId} (TTL ${Ru/1e3}s)`),await Or(n.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await Or(n.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${d.message}`)}}}};function Jy(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Wr.resolve(t),s=Wr.resolve(e);return n===s||n.startsWith(s+Wr.sep)}function Ky(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),i=(r.length>0?r.map(l=>{let f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=t.availableModels(),c=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return Ga({sessionId:t.sessionId,lineageId:e?.lineageId??Br(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:Lu(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:c,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Lu(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function Vy(t){return t?{...t}:void 0}function Yy(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Tu(t){let e=Le(t.currentModelId)??Le(t.currentModel)??Le(t.modelId)??Le(t.model);if(e)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Le(n.currentModelId)??Le(n.currentModel);if(o)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=Le(i.modelId)??Le(i.model)??Le(i.currentModelId);if(a)return a}}let r=oi(t,"model");if(r){let o=Le(r.currentValue);if(o)return o}}function Le(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function oi(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Eu(t){return t.length>0?t:void 0}function Pu(t){let e=ss(t.availableModels);if(e.length>0)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=ss(n.availableModels);if(o.length>0)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=ss(i.availableModels);if(a.length>0)return a}}let r=oi(t,"model");if(r){let o=ss(r.options);if(o.length>0)return o}return[]}function Mu(t){let e=Ys(t.availableModes);if(e.length>0)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Ys(n.availableModes);if(o.length>0)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=Ys(i.availableModes);if(a.length>0)return a}}let r=oi(t,"mode");if(r){let o=Ys(r.options);if(o.length>0)return o}return[]}function $u(t){let e=Le(t.currentModeId)??Le(t.currentMode)??Le(t.modeId)??Le(t.mode);if(e)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Le(n.currentModeId)??Le(n.currentMode);if(o)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=Le(i.currentModeId)??Le(i.currentMode)??Le(i.modeId);if(a)return a}}let r=oi(t,"mode");if(r){let o=Le(r.currentValue);if(o)return o}}async function _u(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=t;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(d=>d.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Fu(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:o}=t;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}function Qy(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Ou(t){try{let e=await as.readFile(R.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
|
|
234
|
-
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function cd(t){try{let e=await
|
|
231
|
+
`,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Dr.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await ot.readFile(T.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let i=[];for(let f of o.split(`
|
|
232
|
+
`)){if(f.length===0)continue;let u;try{u=JSON.parse(f)}catch{continue}if(!u||typeof u!="object"||Array.isArray(u))continue;let p=u;typeof p.method=="string"&&typeof p.recordedAt=="number"&&i.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=i.length>this.maxEntries?i.slice(-this.maxEntries):i;if(!s)return a;let d=new Map,c=async f=>{let u=d.get(f);if(u!==void 0)return u;let p=await Oo(e,f);return d.set(f,p),p},l=[];for(let f of a)l.push(await xu(f,c));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Dr.test(e))return this.enqueue(e,async()=>{try{await ot.unlink(T.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await bl(e);try{await ot.rmdir(T.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};de();_e();ei();os();Jo();dt();jt();Ha();var Ru=900*1e3,Jy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ti=zy(Jy,16),si=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(o=>_n.spawn(o)),this.store=s??new Vo,this.tombstones=r.tombstones??new Yo,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Xo({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.synopsisOnClose=r.synopsisOnClose??!1,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~",this.synopsisCoordinator=new Go({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,persistTitle:async(o,i)=>{let a=this.get(o);if(a){await a.retitle(i);return}await this.persistTitle(o,i)},persistSynopsis:(o,i,a)=>this.persistSynopsis(o,i,a),logger:this.logger,npmRegistry:this.npmRegistry}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;synopsisOnClose;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;agentCatalog=[];async refreshAgentCatalog(){try{let{agents:e}=await Ws(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress});if(e.transformChain&&e.transformChain.length>0){let r={...n.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let i=await o.connection.request("hydra-acp/transformer/message",{token:`t_${ti()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});i.action==="stop"&&i.payload&&(r=i.payload)}catch{}n.agentCapabilities=r}let s=new Vs({cwd:e.cwd,agentId:e.agentId,agent:n.agent,upstreamSessionId:n.upstreamSessionId,agentMeta:n.agentMeta,agentCapabilities:n.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:n.initialModel,currentMode:n.initialMode,agentModes:n.initialModes,agentModels:n.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=N.AlreadyAttached,o}return n}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=N.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await $n(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r}),i;try{i=(await o.connection.request("initialize",{protocolVersion:It,clientCapabilities:{},clientInfo:{name:"hydra",version:le}})).agentCapabilities}catch(h){throw await o.kill().catch(()=>{}),h}let a;try{let h=Qy(e.agentId,e.currentModel);a=await o.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:[],...h&&{_meta:h}})}catch(h){return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
|
|
233
|
+
`),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=$u(a??{}),c=e.agentModes??Eu(Mu(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(h=>h.id))}`);let l=await _u({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=Tu(a??{}),u=Eu(Pu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Fu({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let h=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new Vs({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:h=>this.bootstrapAgent({...h,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:u,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:[],onInstallProgress:e.onInstallProgress,model:e.currentModel}),r=e.agentModes??s.initialModes,o=await _u({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await Fu({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Vs({sessionId:e.hydraSessionId,cwd:n,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await is.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Ht(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=N.AgentNotInstalled,p}let s=await $n(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:ri.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:It,clientCapabilities:{},clientInfo:{name:"hydra",version:le}})}catch(p){throw await r.kill().catch(()=>{}),p}if((o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let l=T.sessionsDir(),f=[],u=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){u+=1;continue}if(Ky(p.cwd,l)){u+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!au(h,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let w=`${hn}${ti()}`,v=new Date().toISOString(),b=p.updatedAt??v,x={sessionId:w,lineageId:Br(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(x.title=p.title);let E=Ga(x);await this.store.write(E),f.push({version:1,...E})}return{synced:f,skipped:u}}async collectAgentSessions(e){let n=[],s;for(let r=0;r<100;r+=1){let o={};s!==void 0&&(o.cursor=s);let i=await e.connection.request("session/list",o),a=Array.isArray(i.sessions)?i.sessions:[];for(let d of a){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let c={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(c.title=d.title),typeof d.updatedAt=="string"&&(c.updatedAt=d.updatedAt),n.push(c)}if(typeof i.nextCursor!="string"||i.nextCursor.length===0)break;s=i.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let n=await this.registry.getAgent(e.agentId);if(!n){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=N.AgentNotInstalled,o}let s=await $n(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let i=(await r.connection.request("initialize",{protocolVersion:It,clientCapabilities:{},clientInfo:{name:"hydra",version:le}})).agentCapabilities,a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=Tu(a),l=Pu(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==c){let g=Js(f,l),h=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,f,h)&&(c=f);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${h} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let w=l.map(v=>v.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${w}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let u=Mu(a),p=$u(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:i,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await r.kill().catch(()=>{}),o}}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let s=ni({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}e.firstPromptSeeded&&this.synopsisOnClose&&this.synopsisCoordinator.schedule(e.sessionId)}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:Lu(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=Vy(e,n);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return Oo(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:Yy(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId}}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=ts(r.update.prompt),i=Wa(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let n of this.sessions.values()){let s=n.agent.agentId,r=n.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(hn))return;let n=hn+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=N.SessionNotFound,s}return n}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(n);i&&i.promise===o&&this.listCache.delete(n)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=i=>e.includeNonInteractive?!0:i===!0;for(let i of this.sessions.values()){if(e.cwd&&i.cwd!==e.cwd)continue;s.add(i.sessionId);let a=await cd(i.sessionId),d=ni({interactive:i.interactive,...i.originatingClient?{originatingClient:i.originatingClient}:{}},a.hasContent);if(!r(d))continue;let c=a.mtime??new Date(i.updatedAt).toISOString();n.push({sessionId:i.sessionId,upstreamSessionId:i.upstreamSessionId,cwd:i.cwd,title:i.title,agentId:i.agentId,currentModel:i.currentModel,currentUsage:i.currentUsage,parentSessionId:i.parentSessionId,forkedFromSessionId:i.forkedFromSessionId,forkedFromMessageId:i.forkedFromMessageId,originatingClient:i.originatingClient,interactive:d,updatedAt:c,attachedClients:i.attachedCount,status:"live",busy:i.turnStartedAt!==void 0,awaitingInput:i.awaitingInput})}let o=await this.store.list().catch(()=>[]);for(let i of o){if(s.has(i.sessionId)||e.cwd&&i.cwd!==e.cwd)continue;let a=await cd(i.sessionId),d=ni(i,a.hasContent);if(!r(d))continue;let c=a.mtime??i.updatedAt;n.push({sessionId:i.sessionId,upstreamSessionId:i.upstreamSessionId,cwd:i.cwd,title:i.title,agentId:i.agentId,currentModel:i.currentModel,currentUsage:i.currentUsage?{...i.currentUsage,costAmount:(i.currentUsage.cumulativeCost??0)+(i.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:i.importedFromMachine,importedFromUpstreamSessionId:i.importedFromUpstreamSessionId,parentSessionId:i.parentSessionId,forkedFromSessionId:i.forkedFromSessionId,forkedFromMessageId:i.forkedFromMessageId,originatingClient:i.originatingClient,interactive:d,updatedAt:c,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return n.sort((i,a)=>i.updatedAt<a.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=Br(),l={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),r=l}let o=n.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Ou(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let d={};for(let c of Su(i)){let l=await yl(e,c);l&&(d[c]=l.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=N.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${hn}${ti()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=N.SessionNotFound,g}let r=n.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=N.AgentNotInstalled,h}let i=await this.histories.load(e).catch(()=>[]),a,d;if(n.forkAt!==void 0){if(a=qa(i,n.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw g.code=N.InvalidParams,g}d=n.forkAt}else{let g=Gy(i);if(!g){let h=new Error(`source session ${e} has no completed turns to fork from`);throw h.code=N.InvalidParams,h}a=g.index,d=g.messageId}let c=i.slice(0,a+1),l=await Ou(e),f={...s,lineageId:Br(),agentId:r,...o?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},u=qr({record:f,history:c,promptHistory:l.length>0?l:void 0,hydraVersion:le,machine:ri.hostname()}),p=`${hn}${ti()}`;return await this.writeImportedRecord({sessionId:p,bundle:u,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:d}),{sessionId:p,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await wl(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await is.utimes(T.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await rs(T.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await cd(e),r=ni(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,title:n,updatedAt:new Date().toISOString()})})}async persistSynopsis(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,synopsis:n,summarizedThroughEntry:s,updatedAt:new Date().toISOString()})})}async persistAgentChange(e,n,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);r&&await this.store.write({...r,agentId:n,upstreamSessionId:s,updatedAt:new Date().toISOString()})})}async persistSnapshot(e,n){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);s&&await this.store.write({...s,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},...n.currentMode!==void 0?{currentMode:n.currentMode}:{},...n.currentUsage!==void 0?{currentUsage:n.currentUsage}:{},...n.agentCommands!==void 0?{agentCommands:n.agentCommands}:{},...n.agentModes!==void 0?{agentModes:n.agentModes}:{},...n.agentModels!==void 0?{agentModels:n.agentModels}:{},...n.interactive!==void 0?{interactive:n.interactive}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},updatedAt:new Date().toISOString()})})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).then(n,n),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(n=>n.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Xl(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(d=>r-d.enqueuedAt<Ru),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${n.sessionId} (TTL ${Ru/1e3}s)`),await Or(n.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await Or(n.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${d.message}`)}}}};function Ky(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Wr.resolve(t),s=Wr.resolve(e);return n===s||n.startsWith(s+Wr.sep)}function Vy(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),i=(r.length>0?r.map(l=>{let f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=t.availableModels(),c=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return Ga({sessionId:t.sessionId,lineageId:e?.lineageId??Br(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:Lu(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:c,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Lu(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function Yy(t){return t?{...t}:void 0}function Qy(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Tu(t){let e=Le(t.currentModelId)??Le(t.currentModel)??Le(t.modelId)??Le(t.model);if(e)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Le(n.currentModelId)??Le(n.currentModel);if(o)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=Le(i.modelId)??Le(i.model)??Le(i.currentModelId);if(a)return a}}let r=oi(t,"model");if(r){let o=Le(r.currentValue);if(o)return o}}function Le(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function oi(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Eu(t){return t.length>0?t:void 0}function Pu(t){let e=ns(t.availableModels);if(e.length>0)return e;let n=t.models;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=ns(n.availableModels);if(o.length>0)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=ns(i.availableModels);if(a.length>0)return a}}let r=oi(t,"model");if(r){let o=ns(r.options);if(o.length>0)return o}return[]}function Mu(t){let e=Ys(t.availableModes);if(e.length>0)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Ys(n.availableModes);if(o.length>0)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=Ys(i.availableModes);if(a.length>0)return a}}let r=oi(t,"mode");if(r){let o=Ys(r.options);if(o.length>0)return o}return[]}function $u(t){let e=Le(t.currentModeId)??Le(t.currentMode)??Le(t.modeId)??Le(t.mode);if(e)return e;let n=t.modes;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=Le(n.currentModeId)??Le(n.currentMode);if(o)return o}let s=t._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[o,i]of Object.entries(s))if(o!=="hydra-acp"&&i&&typeof i=="object"&&!Array.isArray(i)){let a=Le(i.currentModeId)??Le(i.currentMode)??Le(i.modeId);if(a)return a}}let r=oi(t,"mode");if(r){let o=Le(r.currentValue);if(o)return o}}async function _u(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=t;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(d=>d.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Fu(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:o}=t;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}function Gy(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Ou(t){try{let e=await is.readFile(T.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
|
|
234
|
+
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function cd(t){try{let e=await is.stat(T.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function ni(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===ss?!1:e?!0:void 0}import{spawn as Xy}from"child_process";import*as Xs from"fs";import*as Fn from"fs/promises";import*as Bu from"path";var ii=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,n,s){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${s}s start ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Zy=1e3,ew=6e4,ld=3e3,Gs=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Zy,this.restartCapMs=r.restartCapMs??ew;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Fn.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let o=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},ld);s.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw zr(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw zr(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw zr(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw zr(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw zr(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(o=>{e.exitWaiters.push(o)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},ld);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new ii(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Fn.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=Bu.join(this.adapter.paths.dir(),n),r;try{let o=await Fn.readFile(s,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&ud(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+ld;for(;Date.now()<o&&ud(r);)await new Promise(i=>setTimeout(i,50));if(ud(r))try{process.kill(r,"SIGKILL")}catch{}}await Fn.unlink(s).catch(()=>{})}}spawn(e,n){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Xs.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});i.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
|
|
235
235
|
`);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let d={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:a,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[c,...l]=o;if(c===void 0){i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
|
|
236
|
-
`),i.end();return}let f=[...l,...r.args],u;try{u=
|
|
236
|
+
`),i.end();return}let f=[...l,...r.args],u;try{u=Xy(c,f,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){i.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
|
|
237
237
|
`),i.end(),this.scheduleRestart(e,n);return}if(u.stdout&&u.stdout.pipe(i,{end:!1}),u.stderr&&u.stderr.pipe(i,{end:!1}),typeof u.pid=="number")try{Xs.writeFileSync(this.adapter.paths.pidFile(r.name),`${u.pid}
|
|
238
238
|
`,{encoding:"utf8",mode:384})}catch(p){i.write(`[hydra-acp] failed to write pid file for ${r.name}: ${p.message}
|
|
239
239
|
`)}e.child=u,e.logStream=i,e.pid=typeof u.pid=="number"?u.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,u.on("error",p=>{i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${p.message}
|
|
240
240
|
`)}),u.on("exit",(p,g)=>{try{Xs.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${g??"null"}
|
|
241
241
|
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof p=="number"?p:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let h=e.exitWaiters.splice(0);for(let v of h)v();if(this.stopping||e.manuallyStopped){try{i.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let w=e.breaker.recordExit(p,r.name,this.adapter.kind);if(typeof w=="object"){e.failureReason=w.tripped,i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${w.tripped}
|
|
242
|
-
`);try{i.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ud(t){try{return process.kill(t,0),!0}catch{return!1}}function zr(t,e){return t.code=e,t}de();var
|
|
242
|
+
`);try{i.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ud(t){try{return process.kill(t,0),!0}catch{return!1}}function zr(t,e){return t.code=e,t}de();var tw={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:T.extensionsDir,logFile:T.extensionLogFile,pidFile:T.extensionPidFile}},ai=class extends Gs{constructor(e,n,s={}){super(e,tw,n,s)}};de();var nw={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:T.transformersDir,logFile:T.transformerLogFile,pidFile:T.transformerPidFile}},di=class extends Gs{connected=new Map;constructor(e,n,s={}){super(e,nw,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var ci=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};de();de();import*as Kr from"fs/promises";import*as li from"path";var Jr=t=>{process.stderr.write(t+`
|
|
243
243
|
`)};function fd(t){Jr=t??(e=>process.stderr.write(e+`
|
|
244
|
-
`))}async function Nu(t,e){let n=Gt();if(!n)return;let s=await t.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=li.join(R.agentsDir(),n),a;try{a=await Kr.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;Jr(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let f=o.get(c)??new Set,u=li.join(i,c),p;try{p=await Kr.readdir(u,{withFileTypes:!0})}catch(g){Jr(`hydra-acp: prune: failed to read ${u}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let h=g.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let w=li.join(u,h);try{await Kr.rm(w,{recursive:!0,force:!0}),Jr(`hydra-acp: pruned stale ${c} ${h} (${w})`)}catch(v){Jr(`hydra-acp: prune: failed to remove ${w}: ${v.message}`)}}}}function Du(t){let e,n=!1,s=0,r=(a,d)=>{t.logger&&t.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let l=await t.registry.load();for(let f of l.agents)await Na(f)==="yes"&&a.push(f.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:f}=await t.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${f}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},i=a=>{n||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),i(t.intervalMs)})},a),e.unref())};return i(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function pd(t){let e=t.maxDeletions??200,n=(p,g)=>{t.logger&&t.logger[p](`session-gc: ${g}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,o=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||i.push({sessionId:p.sessionId,lastUsedMs:h}))}if(i.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=i.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,n("warn",`delete ${p} failed: ${g.message}`)}let f=i.length-a.length;if(t.verbose||c>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${c} ${p} session(s) older than ${nw(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:i.length,deleted:c,failed:l,deferred:f};return d!==void 0&&(u.oldestLastUsedMs=d),u}function Hu(t){let e,n=!1,s=!1,r=o=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await pd({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},o),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function nw(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}jt();ui();de();es();import*as qu from"path";import{createHash as rw,randomBytes as ow,timingSafeEqual as iw}from"crypto";var Wu="hydra_session_",aw=3600*24*30,Uu=12,dw=32,cw=50;function lw(){return qu.join(R.home(),"session-tokens.json")}function ju(t){return rw("sha256").update(t).digest("hex")}function zu(t){return ow(t).toString("hex")}function uw(){return zu(Uu).slice(0,Uu*2)}function fw(){return`${Wu}${zu(dw)}`}var fi=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=lw(),s=await Pt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(pw));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=fw(),s=ju(n),r=uw(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:aw,a=new Date(o.getTime()+i*1e3),d={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:n,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Wu))return;let n=ju(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(n,"hex");if(r.length!==o.length||!iw(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},cw))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>bt(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 pw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}wt();var Ju="Bearer ",pi=class{constructor(e){this.token=e}token;async validate(e){return mw(e,this.token)?"service":void 0}},mi=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},hi=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function Ku(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Ju)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Ju.length).trim(),i=await t.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}n.authIdentity=i}}function Vu(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var gi=class{tokens=new Map;mint(e,n){let s=Fs();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function mw(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var yi=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}};_e();is();import*as Yr from"os";import*as df from"path";gd();dt();jt();_r();cs();function Jw(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,d=[];for(let l of s){let f=l.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:d.push(l)}i?o="AND":a&&(o="OR");let c=d.map(l=>Kw(l)).filter(l=>l.term.length>0);return{operator:o,terms:c}}function Kw(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:tf(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:tf(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function tf(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Vw(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Yw=5,Qw=200,nf=30;async function of(t,e,n={}){let s=Jw(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Yw,o=n.maxSessions??Qw,i=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),d=i?a.filter(f=>i.has(f.sessionId)):a,c=[],l=!1;for(let f of d){if(c.length>=o){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Gw(u,s,r);if(p.snippets.length===0)continue;let g={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(g.title=f.title),c.push(g)}return{query:e,truncated:l,results:c}}function Gw(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=Xw(t,i,o,n-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Xw(t,e,n,s){let r=e.toLowerCase(),o=0,i=[];for(let a of t){let d=Zw(a).filter(c=>Vw(n,c.kind));for(let c of d){let l=c.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(o+=u,i.length<s){let p=l.indexOf(r),g={kind:c.kind,text:rb(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(g.toolName=c.toolName),i.push(g)}}}return{totalMatches:o,snippets:i}}function Zw(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=Ii(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?ct(s.text):Ii(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(nb(s))return[];let o=Ii(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=sb(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return eb(s);default:return[]}}function eb(t){let e=sf(t,"name"),n=sf(t,"title"),s=[];if(n!==void 0){let a=Ie(n);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==n){let a=Ie(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=rf(r);if(a.length>0){let d={kind:"tool-input",text:Ie(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=t.locations;if(Array.isArray(o)&&o.length>0){let a=rf(o);if(a.length>0){let d={kind:"tool-input",text:Ie(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=tb(t);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function tb(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=Ie(i.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ie(s);if(r.length>0)return r}}return null}function nb(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function Ii(t){if(typeof t=="string")return ct(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?ct(e.text):""}function sb(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Ii(n);s.length>0&&e.push(s)}return e.join("")}function sf(t,e){let n=t[e];return typeof n=="string"?n:void 0}function rf(t){try{return JSON.stringify(t)}catch{return""}}function rb(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-nf),d=Math.min(s.length,i+o.length+nf),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}function af(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!mn(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function cf(t,e,n){t.get("/v1/sessions",async s=>{let r=s.query,o=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:o})}}),t.post("/v1/sessions/search",async(s,r)=>{let o=s.body??{},i=typeof o.q=="string"?o.q:"";if(i.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(o.sessionIds)?o.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await of(e,i,{sessionIds:a})}),t.post("/v1/sessions",async(s,r)=>{let o=s.body??{},i=Ht(o.cwd??n.cwd),a=o.agentId??n.agentId;try{let d=await e.create({cwd:i,agentId:a,mcpServers:o.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),t.post("/v1/sessions/collect",async(s,r)=>{let o=s.body??{},i=typeof o.maxAgeDays=="number"&&o.maxAgeDays>0?o.maxAgeDays*24*60*60*1e3:0,a=typeof o.limit=="number"&&o.limit>0?o.limit:1e3,d=o.selection==="explicit"||o.selection==="unpromoted"?o.selection:"unpromoted";try{let c=await pd({manager:e,maxAgeMs:i,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),t.post("/v1/sessions/:id/kill",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(i)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c={};(d.mode==="memory"||d.mode==="file")&&(c.mode=d.mode),typeof d.capacityBytes=="number"&&(c.capacityBytes=d.capacityBytes),typeof d.fileCapBytes=="number"&&(c.fileCapBytes=d.fileCapBytes),(c.mode??"memory")==="file"&&(c.filePathFor=l=>df.join(Yr.tmpdir(),`hydra-acp-stdin-${l}.log`));try{return a.openStream(c)}catch(l){return r.code(409).send({error:l.message}),r}}),t.post("/v1/sessions/:id/stdin",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",l=d.eof===!0;try{return a.streamWrite(c,l)}catch(f){return r.code(409).send({error:f.message}),r}}),t.patch("/v1/sessions/:id",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=s.body??{};if(a.regen===!0){if(!(e.get(i)!==void 0||await e.hasRecord(i))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(i),r.code(202).send();return}if(typeof a.title!="string"||a.title.trim().length===0){r.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(i,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),t.delete("/v1/sessions/:id",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(i)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),t.get("/v1/sessions/:id/export",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=s.query?.tools,d=a==="references"?"references":bu(a),c=await e.exportBundle(i,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let l=qr({record:c.record,history:d==="summary"?vu(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:le,machine:Yr.hostname(),hydraHost:af(n)}),f=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${i}-${f}.hydra"`),r.code(200).send(l)}),t.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let o=s.params,i=await e.resolveCanonicalId(o.id)??o.id,a=await e.loadToolBlob(i,o.hash);if(a===null){r.code(404).send({error:"tool blob not found"});return}r.header("Content-Type","text/plain; charset=utf-8"),r.code(200).send(a)}),t.get("/v1/sessions/:id/transcript",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=await e.exportBundle(i);if(!a){r.code(404).send({error:"session not found"});return}let d=qr({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:le,machine:Yr.hostname(),hydraHost:af(n)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(vi(d))}),t.post("/v1/sessions/:id/fork",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=s.body??{},d={};if(a.forkAt!==void 0){if(typeof a.forkAt!="string"||a.forkAt.length===0){r.code(400).send({error:"forkAt must be a non-empty string"});return}d.forkAt=a.forkAt}if(a.cwd!==void 0){if(typeof a.cwd!="string"||a.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}d.cwd=Ht(a.cwd)}if(a.agentId!==void 0){if(typeof a.agentId!="string"||a.agentId.length===0){r.code(400).send({error:"agentId must be a non-empty string"});return}d.agentId=a.agentId}try{let c=await e.forkSession(i,d);r.code(201).send(c)}catch(c){let l=c;if(l.code===N.SessionNotFound){r.code(404).send({error:l.message});return}if(l.code===N.InvalidParams||l.code===N.AgentNotInstalled){r.code(400).send({error:l.message});return}r.code(500).send({error:l.message})}}),t.post("/v1/sessions/import",async(s,r)=>{let o=s.body??{};if(o.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let i;if(o.cwd!==void 0){if(typeof o.cwd!="string"||o.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}i=o.cwd}let a;try{a=qt(o.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:o.replace===!0,...i!==void 0?{cwd:i}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===N.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),t.get("/v1/sessions/:id/history",async(s,r)=>{let o=s.params.id,i=s.query,a=i?.follow==="1"||i?.follow==="true",d=await e.resolveCanonicalId(o)??o,c=e.get(d),l,f,u=!1,p=[];if(c)a&&(f=c.onBroadcast(h=>{r.raw.writableEnded||(u?r.raw.write(JSON.stringify(h)+`
|
|
244
|
+
`))}async function Nu(t,e){let n=Gt();if(!n)return;let s=await t.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=li.join(T.agentsDir(),n),a;try{a=await Kr.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;Jr(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let f=o.get(c)??new Set,u=li.join(i,c),p;try{p=await Kr.readdir(u,{withFileTypes:!0})}catch(g){Jr(`hydra-acp: prune: failed to read ${u}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let h=g.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let w=li.join(u,h);try{await Kr.rm(w,{recursive:!0,force:!0}),Jr(`hydra-acp: pruned stale ${c} ${h} (${w})`)}catch(v){Jr(`hydra-acp: prune: failed to remove ${w}: ${v.message}`)}}}}function Du(t){let e,n=!1,s=0,r=(a,d)=>{t.logger&&t.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let l=await t.registry.load();for(let f of l.agents)await Na(f)==="yes"&&a.push(f.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:f}=await t.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${f}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},i=a=>{n||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),i(t.intervalMs)})},a),e.unref())};return i(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function pd(t){let e=t.maxDeletions??200,n=(p,g)=>{t.logger&&t.logger[p](`session-gc: ${g}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,o=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||i.push({sessionId:p.sessionId,lastUsedMs:h}))}if(i.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=i.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,n("warn",`delete ${p} failed: ${g.message}`)}let f=i.length-a.length;if(t.verbose||c>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${c} ${p} session(s) older than ${sw(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:i.length,deleted:c,failed:l,deferred:f};return d!==void 0&&(u.oldestLastUsedMs=d),u}function Hu(t){let e,n=!1,s=!1,r=o=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await pd({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},o),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function sw(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}jt();ui();de();Zn();import*as qu from"path";import{createHash as ow,randomBytes as iw,timingSafeEqual as aw}from"crypto";var Wu="hydra_session_",dw=3600*24*30,Uu=12,cw=32,lw=50;function uw(){return qu.join(T.home(),"session-tokens.json")}function ju(t){return ow("sha256").update(t).digest("hex")}function zu(t){return iw(t).toString("hex")}function fw(){return zu(Uu).slice(0,Uu*2)}function pw(){return`${Wu}${zu(cw)}`}var fi=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=uw(),s=await Pt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(mw));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=pw(),s=ju(n),r=fw(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:dw,a=new Date(o.getTime()+i*1e3),d={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:n,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Wu))return;let n=ju(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(n,"hex");if(r.length!==o.length||!aw(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},lw))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>bt(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 mw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}wt();var Ju="Bearer ",pi=class{constructor(e){this.token=e}token;async validate(e){return hw(e,this.token)?"service":void 0}},mi=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},hi=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function Ku(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Ju)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Ju.length).trim(),i=await t.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}n.authIdentity=i}}function Vu(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var gi=class{tokens=new Map;mint(e,n){let s=Fs();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function hw(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var yi=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}};_e();os();import*as Yr from"os";import*as df from"path";gd();dt();jt();_r();ds();function Kw(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,d=[];for(let l of s){let f=l.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:d.push(l)}i?o="AND":a&&(o="OR");let c=d.map(l=>Vw(l)).filter(l=>l.term.length>0);return{operator:o,terms:c}}function Vw(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:tf(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:tf(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function tf(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Yw(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Qw=5,Gw=200,nf=30;async function of(t,e,n={}){let s=Kw(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Qw,o=n.maxSessions??Gw,i=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),d=i?a.filter(f=>i.has(f.sessionId)):a,c=[],l=!1;for(let f of d){if(c.length>=o){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Xw(u,s,r);if(p.snippets.length===0)continue;let g={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(g.title=f.title),c.push(g)}return{query:e,truncated:l,results:c}}function Xw(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=Zw(t,i,o,n-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Zw(t,e,n,s){let r=e.toLowerCase(),o=0,i=[];for(let a of t){let d=eb(a).filter(c=>Yw(n,c.kind));for(let c of d){let l=c.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(o+=u,i.length<s){let p=l.indexOf(r),g={kind:c.kind,text:ob(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(g.toolName=c.toolName),i.push(g)}}}return{totalMatches:o,snippets:i}}function eb(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=Ii(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?ct(s.text):Ii(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(sb(s))return[];let o=Ii(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=rb(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return tb(s);default:return[]}}function tb(t){let e=sf(t,"name"),n=sf(t,"title"),s=[];if(n!==void 0){let a=Ie(n);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==n){let a=Ie(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=rf(r);if(a.length>0){let d={kind:"tool-input",text:Ie(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=t.locations;if(Array.isArray(o)&&o.length>0){let a=rf(o);if(a.length>0){let d={kind:"tool-input",text:Ie(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=nb(t);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function nb(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=Ie(i.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ie(s);if(r.length>0)return r}}return null}function sb(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function Ii(t){if(typeof t=="string")return ct(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?ct(e.text):""}function rb(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Ii(n);s.length>0&&e.push(s)}return e.join("")}function sf(t,e){let n=t[e];return typeof n=="string"?n:void 0}function rf(t){try{return JSON.stringify(t)}catch{return""}}function ob(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-nf),d=Math.min(s.length,i+o.length+nf),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}function af(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!mn(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function cf(t,e,n){t.get("/v1/sessions",async s=>{let r=s.query,o=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:o})}}),t.post("/v1/sessions/search",async(s,r)=>{let o=s.body??{},i=typeof o.q=="string"?o.q:"";if(i.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(o.sessionIds)?o.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await of(e,i,{sessionIds:a})}),t.post("/v1/sessions",async(s,r)=>{let o=s.body??{},i=Ht(o.cwd??n.cwd),a=o.agentId??n.agentId;try{let d=await e.create({cwd:i,agentId:a,mcpServers:o.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),t.post("/v1/sessions/collect",async(s,r)=>{let o=s.body??{},i=typeof o.maxAgeDays=="number"&&o.maxAgeDays>0?o.maxAgeDays*24*60*60*1e3:0,a=typeof o.limit=="number"&&o.limit>0?o.limit:1e3,d=o.selection==="explicit"||o.selection==="unpromoted"?o.selection:"unpromoted";try{let c=await pd({manager:e,maxAgeMs:i,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),t.post("/v1/sessions/:id/kill",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(i)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c={};(d.mode==="memory"||d.mode==="file")&&(c.mode=d.mode),typeof d.capacityBytes=="number"&&(c.capacityBytes=d.capacityBytes),typeof d.fileCapBytes=="number"&&(c.fileCapBytes=d.fileCapBytes),(c.mode??"memory")==="file"&&(c.filePathFor=l=>df.join(Yr.tmpdir(),`hydra-acp-stdin-${l}.log`));try{return a.openStream(c)}catch(l){return r.code(409).send({error:l.message}),r}}),t.post("/v1/sessions/:id/stdin",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",l=d.eof===!0;try{return a.streamWrite(c,l)}catch(f){return r.code(409).send({error:f.message}),r}}),t.patch("/v1/sessions/:id",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=s.body??{};if(a.regen===!0){if(!(e.get(i)!==void 0||await e.hasRecord(i))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(i),r.code(202).send();return}if(typeof a.title!="string"||a.title.trim().length===0){r.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(i,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),t.delete("/v1/sessions/:id",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=e.get(i);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(i)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),t.get("/v1/sessions/:id/export",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=s.query?.tools,d=a==="references"?"references":bu(a),c=await e.exportBundle(i,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let l=qr({record:c.record,history:d==="summary"?vu(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:le,machine:Yr.hostname(),hydraHost:af(n)}),f=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${i}-${f}.hydra"`),r.code(200).send(l)}),t.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let o=s.params,i=await e.resolveCanonicalId(o.id)??o.id,a=await e.loadToolBlob(i,o.hash);if(a===null){r.code(404).send({error:"tool blob not found"});return}r.header("Content-Type","text/plain; charset=utf-8"),r.code(200).send(a)}),t.get("/v1/sessions/:id/transcript",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=await e.exportBundle(i);if(!a){r.code(404).send({error:"session not found"});return}let d=qr({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:le,machine:Yr.hostname(),hydraHost:af(n)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(vi(d))}),t.post("/v1/sessions/:id/fork",async(s,r)=>{let o=s.params.id,i=await e.resolveCanonicalId(o)??o,a=s.body??{},d={};if(a.forkAt!==void 0){if(typeof a.forkAt!="string"||a.forkAt.length===0){r.code(400).send({error:"forkAt must be a non-empty string"});return}d.forkAt=a.forkAt}if(a.cwd!==void 0){if(typeof a.cwd!="string"||a.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}d.cwd=Ht(a.cwd)}if(a.agentId!==void 0){if(typeof a.agentId!="string"||a.agentId.length===0){r.code(400).send({error:"agentId must be a non-empty string"});return}d.agentId=a.agentId}try{let c=await e.forkSession(i,d);r.code(201).send(c)}catch(c){let l=c;if(l.code===N.SessionNotFound){r.code(404).send({error:l.message});return}if(l.code===N.InvalidParams||l.code===N.AgentNotInstalled){r.code(400).send({error:l.message});return}r.code(500).send({error:l.message})}}),t.post("/v1/sessions/import",async(s,r)=>{let o=s.body??{};if(o.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let i;if(o.cwd!==void 0){if(typeof o.cwd!="string"||o.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}i=o.cwd}let a;try{a=qt(o.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:o.replace===!0,...i!==void 0?{cwd:i}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===N.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),t.get("/v1/sessions/:id/history",async(s,r)=>{let o=s.params.id,i=s.query,a=i?.follow==="1"||i?.follow==="true",d=await e.resolveCanonicalId(o)??o,c=e.get(d),l,f,u=!1,p=[];if(c)a&&(f=c.onBroadcast(h=>{r.raw.writableEnded||(u?r.raw.write(JSON.stringify(h)+`
|
|
245
245
|
`):p.push(h))})),l=await c.getHistorySnapshot();else{let h=await e.getHistory(d);if(h===void 0)return r.code(404).send({error:"session not found"}),r;l=h}r.raw.setHeader("Content-Type","application/x-ndjson"),r.raw.setHeader("Cache-Control","no-cache"),r.raw.statusCode=200;let g=new Set;for(let h of l??[]){r.raw.write(JSON.stringify(h)+`
|
|
246
246
|
`);let w=h;typeof w.recordedAt=="number"&&g.add(String(w.recordedAt))}for(let h of p){let w=h,v=typeof w.recordedAt=="number"?String(w.recordedAt):"";v&&g.has(v)||r.raw.write(JSON.stringify(h)+`
|
|
247
|
-
`)}return u=!0,f?(s.raw.on("close",()=>{f?.(),r.raw.writableEnded||r.raw.end()}),r):(r.raw.end(),r)})}dt();function lf(t,e,n,s={}){t.get("/v1/agents",async()=>Ws(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.post("/v1/agents/:id/install",async(r,o)=>{let i=r.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
|
|
248
|
-
`;await Ln.mkdir(R.home(),{recursive:!0}),await Ln.writeFile(yd(),s,{encoding:"utf8",mode:384})}async function Si(){try{return(await Ln.readFile(yd(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Ln.readFile(yd(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),o=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(i.length===0||a.length===0)return!1;let d=await bf(t,i,a.length,{N:s,r,p:o,maxmem:vf});return d.length!==a.length?!1:ub(d,a)}var hb=er.object({password:er.string().min(1),label:er.string().min(1).max(256).optional(),ttlSec:er.number().int().positive().optional()}),gb=er.object({id:er.string().optional()}).optional();function Sf(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=yb(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=hb.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Si())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await ki(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=gb.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??n.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function yb(t){return t.ip||"unknown"}Fr();xi();Jo();dt();import{nanoid as Sd}from"nanoid";jt();import{randomBytes as kf}from"crypto";function Af(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Vu({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=tr(n),a=new Zt(i),d={clientId:`hydra_client_${Sd(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let c=(f,u)=>{if(d.attached.get(f)?.readonly){let g=new Error(`${u} not permitted on a read-only attachment`);throw g.code=N.PermissionDenied,g}};if(a.onRequest("initialize",async f=>{let u=Ml.parse(f??{});u.clientInfo?.name&&(d.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p)),vb()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},g=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let w=h;if(typeof w.verb!="string"||w.verb.length===0)return;let v={verb:w.verb};return typeof w.argsHint=="string"&&(v.argsHint=w.argsHint),typeof w.description=="string"&&(v.description=w.description),v}).filter(h=>h!==void 0):[];return f.register(o.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let p=u??{},g=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(w=>{if(!w||typeof w!="object")return;let v=w;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let b={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(b.outputSchema=v.outputSchema),b}).filter(w=>w!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,g,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(o.name)})}o?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async f=>{let u=f??{},p=Array.isArray(u.intercepts)?u.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,p),e.manager?.defaultTransformers.includes(o.name))){let g=e.transformers.resolveChain([o.name])[0];if(g)for(let h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0,g=typeof u.method=="string"?u.method:void 0,h=u.envelope,w=u.route;if(!p||!g)throw Object.assign(new Error("emit_message requires sessionId and method"),{code:-32602});let v=e.manager.get(p);if(!v)throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});let b=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(b)return v.dischargeClaim(b,h),{ok:!0};if(w==="chain")return await v.emitToChain(o.name,g,h),{ok:!0};if(w==="daemon")return await v.emitToChain(o.name,g,h),{ok:!0};throw Object.assign(new Error(`unsupported route: ${JSON.stringify(w)}`),{code:-32602})}),a.onRequest("hydra-acp/child_session/spawn",async f=>{let u=f??{},p=typeof u.agentId=="string"?u.agentId:e.defaultAgent,g=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.parentSessionId=="string"?u.parentSessionId:void 0;if(!g)throw Object.assign(new Error("spawn_child_session requires cwd"),{code:-32602});return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:h,transformChain:[]})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw Object.assign(new Error("fork_session requires sessionId"),{code:N.InvalidParams});let p=typeof u.forkAt=="string"?u.forkAt:void 0,g=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw Object.assign(new Error("hydra-acp/session/delete requires sessionId"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,g=e.manager.get(p);if(g)return await g.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0,g=u.until==="idle"?"idle":"turn_complete",h=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,30*6e4):5*6e4;if(!p)throw Object.assign(new Error("await_child requires childSessionId"),{code:-32602});let w=e.manager.get(p);if(!w)throw Object.assign(new Error(`child session ${p} not found`),{code:N.SessionNotFound});return new Promise(v=>{let b=[],A,T=()=>{clearTimeout($),A?.(),v({entries:b})};A=w.onBroadcast(K=>{b.push(K),g==="turn_complete"&&K.params?.update?.sessionUpdate==="turn_complete"&&T()});let $=setTimeout(T,h);typeof $.unref=="function"&&$.unref(),w.onClose(()=>T())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!p)throw Object.assign(new Error("close_child_session requires childSessionId"),{code:-32602});let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let u=f??{},p=typeof u.token=="string"?u.token:void 0,g=typeof u.sessionId=="string"?u.sessionId:void 0,h=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw Object.assign(new Error("hydra-acp/session/tool_content requires sessionId and hash"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,g=await e.manager.loadToolBlob(p,u.hash);if(g===null)throw Object.assign(new Error("tool content not found"),{code:N.SessionNotFound});return{content:g}}),a.onRequest("session/new",async f=>{let u=$l.parse(f),p=St(f?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(_=>typeof _=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(g)??[],w,v,b=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){w=kf(32).toString("hex"),v=e.mcpTokenRegistry.reserve(w);let H={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${w}`}]};b=[...u.mcpServers??[],H]}let A,T;if(e.extensionMcp!==void 0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){let _=e.extensionMcp.list();if(_.length>0){A=kf(32).toString("hex"),T=e.mcpTokenRegistry.reserve(A);let H=e.getDaemonOrigin(),q=_.map(z=>({name:z,type:"http",url:`${H}/mcp/${z}`,headers:[{name:"Authorization",value:`Bearer ${A}`}]}));b=[...b??[],...q]}}let $;try{$=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:xf(a),transformChain:h,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch(_){throw v!==void 0&&v.abandon(_ instanceof Error?_:void 0),T!==void 0&&T.abandon(_ instanceof Error?_:void 0),_}if(w!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let _=w,H=e.mcpTokenRegistry;v.complete($),$.onClose(()=>{H.unbind(_)})}if(A!==void 0&&T!==void 0&&e.mcpTokenRegistry!==void 0){let _=A,H=e.mcpTokenRegistry;T.complete($),$.onClose(()=>{H.unbind(_)})}let K=Ai(a,$,d),{entries:te}=await $.attach(K,"full");d.attached.set($.sessionId,{sessionId:$.sessionId,clientId:K.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let _ of te)await a.notify(_.method,_.params).catch(()=>{})})()});let J=wd($),D=bd($);return{sessionId:$.sessionId,...J?{modes:J}:{},...D?{models:D}:{},configOptions:$.buildConfigOptions(),_meta:vd(e.manager,$,{clientId:K.clientId})}}),a.onRequest("session/attach",async f=>{let u=_l.parse(f),p=u.clientInfo?.version;p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p));let g=St(u._meta),h=g.resume,w=g.readonly===!0;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${w}`);let v=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,b=e.manager.get(v);if(!b&&w){let D=await e.manager.loadFromDisk(v);if(!D){let q=new Error(`session ${u.sessionId} not found`);throw q.code=N.SessionNotFound,q}let _=await e.manager.loadHistory(v),H=u.clientId??`cli_${Sd(8)}`;d.attached.set(D.hydraSessionId,{sessionId:D.hydraSessionId,clientId:H,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${D.hydraSessionId} clientId=${H} attachedCount=${d.attached.size} replayed=${_.length}`);for(let q of _)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:D.hydraSessionId,clientId:H,connectedClients:[H],historyPolicy:"full",replayed:_.length,_meta:bb(D)}}if(!b){let D=await e.manager.loadFromDisk(v),_=D;if(h&&(_={...D,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!_){let q=new Error(`session ${u.sessionId} not found and no resume hints provided`);throw q.code=N.SessionNotFound,q}let H=_.originatingClient?_:{..._,originatingClient:d.clientInfo};b=await e.manager.resurrect({...H,onInstallProgress:xf(a)}),Id(b,e)}let A=Ai(a,b,d,u.clientInfo,u.clientId),T=g.replayMode==="drip",{entries:$,appliedPolicy:K}=await b.attach(A,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:T,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:A.clientId,readonly:w}),t.log.info(`session/attach OK sessionId=${b.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${K} replayed=${$.length} readonly=${w}${T?" replayMode=drip":""}`),T){let D=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,_=750;(async()=>{let H=null;for(let q of $){let z=typeof q.recordedAt=="number"?q.recordedAt:null;if(H!==null&&z!==null){let be=Math.min(_,Math.max(0,(z-H)/D));be>0&&await new Promise(xe=>setTimeout(xe,be))}z!==null&&(H=z);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let _=0;_<$.length;_++){let H=$[_],q=a.notify(H.method,H.params).catch(()=>{});(_+1)%200===0&&await q}b.replayPendingPermissions(A);let te=wd(b),J=bd(b);return{sessionId:b.sessionId,clientId:A.clientId,connectedClients:b.connectedClients(A.clientId),historyPolicy:K,replayed:$.length,...te?{modes:te}:{},...J?{models:J}:{},configOptions:b.buildConfigOptions(),_meta:vd(e.manager,b)}}),a.onRequest("session/detach",async f=>{let u=Fl.parse(f),p=d.attached.get(u.sessionId);if(!p){let h=new Error("client not attached to that session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);return g?.detach(p.clientId),d.attached.delete(u.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[Mt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=Ol.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(w=>w.originatingClient?.name!==rs).map(Bl)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry){let f=new Error("agent registry unavailable");throw f.code=N.InternalError,f}return Ws(e.registry)}),a.onRequest("session/prompt",async f=>{let u=Nl.parse(f);c(u.sessionId,"session/prompt");let p=d.attached.get(u.sessionId);if(!p){t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`);let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);if(!g){let h=await e.manager.loadFromDisk(u.sessionId);if(!h){let v=new Error(`session ${u.sessionId} not found`);throw v.code=N.SessionNotFound,v}t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),g=await e.manager.resurrect(h),Id(g,e);let w=Ai(a,g,d,void 0,p.clientId);await g.attach(w,"none")}return g.prompt(p.clientId,u)});let l=f=>{let u;try{u=Ho.parse(f)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=d.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let g=e.manager.get(u.sessionId);g&&g.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Ho.parse(f);return c(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=Hl.parse(f);c(u.sessionId,"hydra-acp/prompt/cancel");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Ho.parse(f);c(u.sessionId,"hydra-acp/session/force_cancel");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=Ul.parse(f);c(u.sessionId,"hydra-acp/prompt/update");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=jl.parse(f);c(u.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(u.sessionId);if(!p){let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);if(!g){let h=new Error(`session ${u.sessionId} not found`);throw h.code=N.SessionNotFound,h}return g.amendPrompt(p.clientId,u)}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p){let T=new Error("session/load requires sessionId");throw T.code=N.InvalidParams,T}let g=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(g);if(!h){let T=await e.manager.loadFromDisk(g);if(!T){let $=new Error(`session ${p} not found in memory or on disk`);throw $.code=N.SessionNotFound,$}h=await e.manager.resurrect(T),Id(h,e)}let w=Ai(a,h,d),{entries:v}=await h.attach(w,"pending_only");d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:w.clientId,readonly:!1});for(let T of v)await a.notify(T.method,T.params);h.replayPendingPermissions(w);let b=wd(h),A=bd(h);return{sessionId:h.sessionId,...b?{modes:b}:{},...A?{models:A}:{},configOptions:h.buildConfigOptions(),_meta:vd(e.manager,h,{clientId:w.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&c(u,"session/set_model");let p=wb(f,e.manager);if(p.kind==="error"){t.log.warn(p.logMessage);let w=new Error(p.message);throw w.code=p.code,w}if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:g}=p,h=await p.session.forwardRequest("session/set_model",{...f,modelId:g});return p.session.applyModelChange(g),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!u||typeof u.sessionId!="string"){let w=new Error("session/set_mode requires string sessionId");throw w.code=N.InvalidParams,w}if(typeof u.modeId!="string"){let w=new Error("session/set_mode requires string modeId");throw w.code=N.InvalidParams,w}let g=e.manager.get(u.sessionId);if(!g){let w=new Error(`session ${u.sessionId} not found`);throw w.code=N.SessionNotFound,w}let h=await g.forwardRequest("session/set_mode",f);return g.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=v=>{let b=new Error(v);return b.code=N.InvalidParams,b},g=u?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=e.manager.get(u.sessionId);if(!h){let v=new Error(`session ${u.sessionId} not found`);throw v.code=N.SessionNotFound,v}let w=h.buildConfigOptions().find(v=>v.id===u.configId);if(!w)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!w.options.some(v=>v.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{if(!u.startsWith("session/")||f===null||typeof f!="object"){let h=new Error(`Method not found: ${u}`);throw h.code=N.MethodNotFound,h}let p=f.sessionId;if(typeof p!="string"){let h=new Error(`Method not found: ${u}`);throw h.code=N.MethodNotFound,h}c(p,u);let g=e.manager.get(p);if(!g){let h=new Error(`session ${p} not found`);throw h.code=N.SessionNotFound,h}return g.forwardRequest(u,f)})})}function xf(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(Uo,n).catch(()=>{})}}function wd(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function bd(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function wb(t,e){if(!t||typeof t!="object")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:N.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),o=Js(n.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:N.InvalidParams,message:`model "${n.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}function bb(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[Mt]:Do(e,n)}}function vd(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot()};return No(e.agentMeta,Do(s,r))}function vb(){return{protocolVersion:It,agentInfo:{name:"hydra",version:le},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"bearer-token",description:"Bearer token presented at WS upgrade"}],_meta:No(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Id(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function Ai(t,e,n,s,r){return{clientId:r??`cli_${Sd(8)}`,connection:t,clientInfo:s}}var Ci=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((i,a)=>{n=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,n(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Ib}from"crypto";import{McpServer as Sb}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as kb}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ze}from"zod";var Cf="Bearer ";function Ri(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(Cf))return;let n=e.slice(Cf.length).trim();return n.length>0?n:void 0}function xb(t){let e=new Sb({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:Ze.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:Ze.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:Ze.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:Ze.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Ze.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:n,max_bytes:s,wait_ms:r})=>{let o=await t.streamRead(n,s,r);return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent: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:Ze.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Ze.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),o=t.streamInfo(),i={outcome:r,writeCursor:o.writeCursor,closed:o.closed};return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),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:Ze.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Ze.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Ze.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Ze.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Ze.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Ze.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Ze.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Ze.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Ze.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.streamGrep(s),o=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:o}}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let n=t.streamInfo();return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}),e}var Ab=1e4;function Rf(t,e){let n=new Map;async function s(i,a){let d=n.get(i);if(d!==void 0)return d.transport;let c=xb(a),l=new kb({sessionIdGenerator:()=>Ib()});await c.connect(l);let f={server:c,transport:l};return n.set(i,f),e.addDisposer(i,async()=>{n.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(i,a){let d=Ri(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 u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),Ab)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),g===void 0){a.code(503).send({error:"session not ready"});return}l=g}let f=await s(d,l);a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),t.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),t.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}var Ti=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as $b}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as _b}from"crypto";import{Server as Cb}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Rb,ListToolsRequestSchema as Tb}from"@modelcontextprotocol/sdk/types.js";var Eb=6e4;function Tf(t,e,n={}){let s=n.invokeTimeoutMs??Eb,r=new Cb({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=new Map(e.tools.map(i=>[i.name,i]));return r.setRequestHandler(Tb,async()=>({tools:e.tools.map(i=>({name:i.name,description:i.description,inputSchema:i.inputSchema,...i.outputSchema!==void 0?{outputSchema:i.outputSchema}:{}}))})),r.setRequestHandler(Rb,async i=>{let a=i.params.name;if(!o.has(a))return Ei(`unknown tool: ${a}`);try{let d=await Pb(e.connection,t,a,i.params.arguments??{},s);return Mb(d,a)}catch(d){return Ei(d instanceof Error?d.message:String(d))}}),r}async function Pb(t,e,n,s,r){let o,i=new Promise((a,d)=>{o=setTimeout(()=>d(new Error(`extension timeout after ${r}ms`)),r)});try{return await Promise.race([t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s}),i])}finally{o!==void 0&&clearTimeout(o)}}function Mb(t,e){if(t===null||typeof t!="object")return Ei(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Ei(`extension ${e} omitted content array`)}function Ei(t){return{content:[{type:"text",text:t}],isError:!0}}var Fb=1e4;function Ef(t,e,n,s={}){let r=new Map;async function o(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let f of r.values()){let u=f.get(l);u!==void 0&&(f.delete(l),o(u))}}n.onChange(l=>{i(l)});async function a(l,f){let u=r.get(l);u===void 0&&(u=new Map,r.set(l,u),e.addDisposer(l,async()=>{let v=r.get(l);if(v!==void 0){r.delete(l);for(let b of v.values())await o(b)}}));let p=u.get(f);if(p!==void 0)return p.transport;let g=n.lookup(f);if(g===void 0)return;let h=Tf(f,g,s.buildOptions),w=new $b({sessionIdGenerator:()=>_b()});return await h.connect(w),u.set(f,{server:h,transport:w}),w}async function d(l,f){let u=Ri(l);if(u===void 0){f.code(401).send({error:"missing bearer token"});return}let p=e.lookup(u);if(p===void 0){f.code(404).send({error:"unknown mcp token"});return}if(p.session===void 0){let w,v=new Promise(A=>{w=setTimeout(()=>A(void 0),Fb)}),b=await Promise.race([p.sessionReady.catch(()=>{}),v]);if(w!==void 0&&clearTimeout(w),b===void 0){f.code(503).send({error:"session not ready"});return}}let g=l.params.name,h=await a(u,g);if(h===void 0){f.code(404).send({error:`unknown mcp server: ${g}`});return}f.hijack(),await h.handleRequest(l.raw,f.raw,l.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(l,f)=>{await d(l,f)}),t.get("/mcp/:name",c,async(l,f)=>{await d(l,f)}),t.delete("/mcp/:name",c,async(l,f)=>{await d(l,f)})}async function $f(t,e){Db(t);let n=t.daemon.tls?{key:await Bn.readFile(t.daemon.tls.key),cert:await Bn.readFile(t.daemon.tls.cert)}:void 0;await Bn.mkdir(R.home(),{recursive:!0});let{stream:s,fileStream:r}=await Nb(t.daemon.logLevel),o=Ob({logger:{level:t.daemon.logLevel,stream:s},https:n??null,bodyLimit:256*1024*1024});await o.register(Lb,{options:{handleProtocols:fl}}),_a(Y=>{o.log.info(Y)}),La(Y=>{o.log.info(Y)});let i=await fi.load(),a=new yi,d=new gi,c=new hi([new pi(e),new mi(i),d]),l=Ku({validator:c});o.addHook("onRequest",async(Y,ge)=>{Y.routeOptions.config?.skipAuth||Y.url==="/acp"||Y.url?.startsWith("/acp?")||await l(Y,ge)});let f=setInterval(()=>{i.sweepExpired()},300*1e3);f.unref();let u=new Lo(t,{onFetched:()=>{Nu(u,w)}});fd(Y=>o.log.info(Y));let p={info:Y=>o.log.info(Y),warn:Y=>o.log.warn(Y)},g=Y=>Fn.spawn({...Y,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:p});gl(t.compressToolContent);let h=new ci,w=new si(u,g,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,synopsisOnClose:t.synopsisOnClose,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:p,npmRegistry:t.npmRegistry,extensionCommands:h,defaultCwd:t.defaultCwd}),v=new ai(Vc(t),void 0,{tokenRegistry:d}),b=new di(Yc(t),void 0,{tokenRegistry:d});uf(o,le,Zs(t)),cf(o,w,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port}),lf(o,u,w,{npmRegistry:t.npmRegistry}),ff(o,v),pf(o,b),mf(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},synopsisOnClose:t.synopsisOnClose,defaultTransformers:[...t.defaultTransformers]}),Sf(o,{store:i,rateLimiter:a});let A=new Ci,T=new Ti;Rf(o,A),Ef(o,A,T);let $,K=()=>{if($!==void 0)return $;let Y=o.server.address(),ge=Y&&typeof Y=="object"?Y.port:t.daemon.port;return $=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${ge}`,$};Af(o,{validator:c,manager:w,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Y,ge)=>v.reportVersion(Y,ge),onTransformerVersion:(Y,ge)=>b.reportVersion(Y,ge),transformers:b,extensionCommands:h,mcpTokenRegistry:A,extensionMcp:T,getDaemonOrigin:K,registry:u}),await o.listen({host:t.daemon.host,port:t.daemon.port});let te=o.server.address(),J=te&&typeof te=="object"?te.port:t.daemon.port;await Bn.mkdir(R.home(),{recursive:!0}),await Bn.writeFile(R.pidFile(),JSON.stringify({pid:process.pid,host:t.daemon.host,port:J,startedAt:new Date().toISOString()})+`
|
|
249
|
-
`,{encoding:"utf8",mode:384});let D=t.daemon.tls?"https":"http",_=t.daemon.tls?"wss":"ws",H={daemonUrl:`${D}://${t.daemon.host}:${J}`,daemonHost:t.daemon.host,daemonPort:J,serviceToken:e,daemonWsUrl:`${_}://${t.daemon.host}:${J}/acp`,hydraHome:
|
|
250
|
-
`),process.exit(1);return}throw d}let o=await
|
|
251
|
-
`);let i=!1,a=_f.watch(t,()=>{i||(i=!0,setImmediate(async()=>{i=!1;try{let d=await sr.stat(t);if(d.size<=o){d.size<o&&(o=d.size);return}let c=await sr.open(t,"r");try{let l=Buffer.alloc(d.size-o);await c.read(l,0,l.length,o),process.stdout.write(l),o=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function
|
|
247
|
+
`)}return u=!0,f?(s.raw.on("close",()=>{f?.(),r.raw.writableEnded||r.raw.end()}),r):(r.raw.end(),r)})}dt();function lf(t,e,n,s={}){t.get("/v1/agents",async()=>Ws(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.post("/v1/agents/:id/install",async(r,o)=>{let i=r.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 $n(a,[],{npmRegistry:s.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})}}),t.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:d}=await n.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===N.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}function uf(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var ib=/^[A-Za-z0-9._-]+$/;function ff(t,e){t.get("/v1/extensions",async()=>({extensions:e.list()})),t.get("/v1/extensions/:name",async(n,s)=>{let r=n.params.name,o=e.get(r);if(!o){s.code(404).send({error:`unknown extension: ${r}`});return}return o}),t.post("/v1/extensions",async(n,s)=>{let r=n.body??{},o=ab(r);if("error"in o){s.code(400).send({error:o.error});return}try{let i=e.register(o.config);s.code(201).send(i)}catch(i){Qr(s,i)}}),t.delete("/v1/extensions/:name",async(n,s)=>{let r=n.params.name;try{await e.unregister(r),s.code(204).send()}catch(o){Qr(s,o)}}),t.post("/v1/extensions/:name/start",async(n,s)=>{let r=n.params.name;try{let o=await e.startByName(r);s.code(200).send(o)}catch(o){Qr(s,o)}}),t.post("/v1/extensions/:name/stop",async(n,s)=>{let r=n.params.name;try{let o=await e.stopByName(r);s.code(200).send(o)}catch(o){Qr(s,o)}}),t.post("/v1/extensions/:name/restart",async(n,s)=>{let r=n.params.name;try{let o=await e.restartByName(r);s.code(200).send(o)}catch(o){Qr(s,o)}})}function Qr(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function ab(t){let e=t.name;if(typeof e!="string"||!ib.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=t.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=t.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}var db=/^[A-Za-z0-9._-]+$/;function pf(t,e){t.get("/v1/transformers",async()=>({transformers:e.list()})),t.get("/v1/transformers/:name",async(n,s)=>{let r=n.params.name,o=e.get(r);if(!o){s.code(404).send({error:`unknown transformer: ${r}`});return}return o}),t.post("/v1/transformers",async(n,s)=>{let r=n.body??{},o=cb(r);if("error"in o){s.code(400).send({error:o.error});return}try{let i=e.register(o.config);s.code(201).send(i)}catch(i){Gr(s,i)}}),t.delete("/v1/transformers/:name",async(n,s)=>{let r=n.params.name;try{await e.unregister(r),s.code(204).send()}catch(o){Gr(s,o)}}),t.post("/v1/transformers/:name/start",async(n,s)=>{let r=n.params.name;try{let o=await e.startByName(r);s.code(200).send(o)}catch(o){Gr(s,o)}}),t.post("/v1/transformers/:name/stop",async(n,s)=>{let r=n.params.name;try{let o=await e.stopByName(r);s.code(200).send(o)}catch(o){Gr(s,o)}}),t.post("/v1/transformers/:name/restart",async(n,s)=>{let r=n.params.name;try{let o=await e.restartByName(r);s.code(200).send(o)}catch(o){Gr(s,o)}})}function Gr(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function cb(t){let e=t.name;if(typeof e!="string"||!db.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=t.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=t.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}function mf(t,e){t.get("/v1/config",async()=>e)}import{z as er}from"zod";de();import*as On from"fs/promises";import*as wf from"path";import{randomBytes as lb,scrypt as ub,timingSafeEqual as fb}from"crypto";import{promisify as pb}from"util";var bf=pb(ub);function yd(){return wf.join(T.home(),"password-hash")}var hf=32768,gf=8,yf=1,mb=64,hb=16,vf=128*1024*1024;async function If(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=lb(hb),n=await bf(t,e,mb,{N:hf,r:gf,p:yf,maxmem:vf}),s=`scrypt$${hf}$${gf}$${yf}$${e.toString("hex")}$${n.toString("hex")}
|
|
248
|
+
`;await On.mkdir(T.home(),{recursive:!0}),await On.writeFile(yd(),s,{encoding:"utf8",mode:384})}async function Si(){try{return(await On.readFile(yd(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await On.readFile(yd(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),o=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(i.length===0||a.length===0)return!1;let d=await bf(t,i,a.length,{N:s,r,p:o,maxmem:vf});return d.length!==a.length?!1:fb(d,a)}var gb=er.object({password:er.string().min(1),label:er.string().min(1).max(256).optional(),ttlSec:er.number().int().positive().optional()}),yb=er.object({id:er.string().optional()}).optional();function Sf(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=wb(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=gb.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Si())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await ki(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=yb.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??n.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function wb(t){return t.ip||"unknown"}Fr();xi();Jo();dt();import{nanoid as Sd}from"nanoid";jt();import{randomBytes as kf}from"crypto";function Af(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Vu({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=tr(n),a=new Zt(i),d={clientId:`hydra_client_${Sd(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let c=(f,u)=>{if(d.attached.get(f)?.readonly){let g=new Error(`${u} not permitted on a read-only attachment`);throw g.code=N.PermissionDenied,g}};if(a.onRequest("initialize",async f=>{let u=Ml.parse(f??{});u.clientInfo?.name&&(d.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p)),Sb()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},g=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let w=h;if(typeof w.verb!="string")return;let v={verb:w.verb};return typeof w.argsHint=="string"&&(v.argsHint=w.argsHint),typeof w.description=="string"&&(v.description=w.description),v}).filter(h=>h!==void 0):[];return f.register(o.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let p=u??{},g=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(w=>{if(!w||typeof w!="object")return;let v=w;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let b={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(b.outputSchema=v.outputSchema),b}).filter(w=>w!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,g,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(o.name)})}o?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async f=>{let u=f??{},p=Array.isArray(u.intercepts)?u.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,p),e.manager?.defaultTransformers.includes(o.name))){let g=e.transformers.resolveChain([o.name])[0];if(g)for(let h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0,g=typeof u.method=="string"?u.method:void 0,h=u.envelope,w=u.route;if(!p||!g)throw Object.assign(new Error("emit_message requires sessionId and method"),{code:-32602});let v=e.manager.get(p);if(!v)throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});let b=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(b)return v.dischargeClaim(b,h),{ok:!0};if(w==="chain")return{ok:!0,response:await v.emitToChain(o.name,g,h)};if(w==="daemon")return{ok:!0,response:await v.emitToChain(o.name,g,h)};throw Object.assign(new Error(`unsupported route: ${JSON.stringify(w)}`),{code:-32602})}),a.onRequest("hydra-acp/transformer/attach",async f=>vb(f,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let u=f??{},p=typeof u.agentId=="string"?u.agentId:e.defaultAgent,g=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.parentSessionId=="string"?u.parentSessionId:void 0;if(!g&&h){let b=e.manager.get(h);b&&(g=b.cwd)}if(!g)throw Object.assign(new Error("child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)"),{code:-32602});let w=typeof u.interactive=="boolean"?u.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:h,interactive:w,transformChain:[]})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw Object.assign(new Error("fork_session requires sessionId"),{code:N.InvalidParams});let p=typeof u.forkAt=="string"?u.forkAt:void 0,g=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw Object.assign(new Error("hydra-acp/session/delete requires sessionId"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,g=e.manager.get(p);if(g)return await g.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw Object.assign(new Error(`session ${p} not found`),{code:N.SessionNotFound});return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0,g=u.until==="idle"?"idle":"turn_complete",h=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,30*6e4):5*6e4;if(!p)throw Object.assign(new Error("await_child requires childSessionId"),{code:-32602});let w=e.manager.get(p);if(!w)throw Object.assign(new Error(`child session ${p} not found`),{code:N.SessionNotFound});return new Promise(v=>{let b=[],x,E=()=>{clearTimeout($),x?.(),v({entries:b})};x=w.onBroadcast(K=>{b.push(K),g==="turn_complete"&&K.params?.update?.sessionUpdate==="turn_complete"&&E()});let $=setTimeout(E,h);typeof $.unref=="function"&&$.unref(),w.onClose(()=>E())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!p)throw Object.assign(new Error("close_child_session requires childSessionId"),{code:-32602});let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let u=f??{},p=typeof u.token=="string"?u.token:void 0,g=typeof u.sessionId=="string"?u.sessionId:void 0,h=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw Object.assign(new Error("hydra-acp/session/tool_content requires sessionId and hash"),{code:N.InvalidParams});let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,g=await e.manager.loadToolBlob(p,u.hash);if(g===null)throw Object.assign(new Error("tool content not found"),{code:N.SessionNotFound});return{content:g}}),a.onRequest("session/new",async f=>{let u=$l.parse(f),p=St(f?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(_=>typeof _=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(g)??[],w,v,b=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){w=kf(32).toString("hex"),v=e.mcpTokenRegistry.reserve(w);let H={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${w}`}]};b=[...u.mcpServers??[],H]}let x,E;if(e.extensionMcp!==void 0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){let _=e.extensionMcp.list();if(_.length>0){x=kf(32).toString("hex"),E=e.mcpTokenRegistry.reserve(x);let H=e.getDaemonOrigin(),q=_.map(z=>({name:z,type:"http",url:`${H}/mcp/${z}`,headers:[{name:"Authorization",value:`Bearer ${x}`}]}));b=[...b??[],...q]}}let $;try{$=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:xf(a),transformChain:h,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch(_){throw v!==void 0&&v.abandon(_ instanceof Error?_:void 0),E!==void 0&&E.abandon(_ instanceof Error?_:void 0),_}if(w!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let _=w,H=e.mcpTokenRegistry;v.complete($),$.onClose(()=>{H.unbind(_)})}if(x!==void 0&&E!==void 0&&e.mcpTokenRegistry!==void 0){let _=x,H=e.mcpTokenRegistry;E.complete($),$.onClose(()=>{H.unbind(_)})}let K=Ai(a,$,d),{entries:te}=await $.attach(K,"full");d.attached.set($.sessionId,{sessionId:$.sessionId,clientId:K.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let _ of te)await a.notify(_.method,_.params).catch(()=>{})})()});let J=wd($),D=bd($);return{sessionId:$.sessionId,...J?{modes:J}:{},...D?{models:D}:{},configOptions:$.buildConfigOptions(),_meta:vd(e.manager,$,{clientId:K.clientId})}}),a.onRequest("session/attach",async f=>{let u=_l.parse(f),p=u.clientInfo?.version;p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p));let g=St(u._meta),h=g.resume,w=g.readonly===!0;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${w}`);let v=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,b=e.manager.get(v);if(!b&&w){let D=await e.manager.loadFromDisk(v);if(!D){let q=new Error(`session ${u.sessionId} not found`);throw q.code=N.SessionNotFound,q}let _=await e.manager.loadHistory(v),H=u.clientId??`cli_${Sd(8)}`;d.attached.set(D.hydraSessionId,{sessionId:D.hydraSessionId,clientId:H,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${D.hydraSessionId} clientId=${H} attachedCount=${d.attached.size} replayed=${_.length}`);for(let q of _)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:D.hydraSessionId,clientId:H,connectedClients:[H],historyPolicy:"full",replayed:_.length,_meta:Ib(D)}}if(!b){let D=await e.manager.loadFromDisk(v),_=D;if(h&&(_={...D,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!_){let q=new Error(`session ${u.sessionId} not found and no resume hints provided`);throw q.code=N.SessionNotFound,q}let H=_.originatingClient?_:{..._,originatingClient:d.clientInfo};b=await e.manager.resurrect({...H,onInstallProgress:xf(a)}),Id(b,e)}let x=Ai(a,b,d,u.clientInfo,u.clientId),E=g.replayMode==="drip",{entries:$,appliedPolicy:K}=await b.attach(x,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:E,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:x.clientId,readonly:w}),t.log.info(`session/attach OK sessionId=${b.sessionId} clientId=${x.clientId} attachedCount=${d.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${K} replayed=${$.length} readonly=${w}${E?" replayMode=drip":""}`),E){let D=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,_=750;(async()=>{let H=null;for(let q of $){let z=typeof q.recordedAt=="number"?q.recordedAt:null;if(H!==null&&z!==null){let be=Math.min(_,Math.max(0,(z-H)/D));be>0&&await new Promise(xe=>setTimeout(xe,be))}z!==null&&(H=z);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let _=0;_<$.length;_++){let H=$[_],q=a.notify(H.method,H.params).catch(()=>{});(_+1)%200===0&&await q}b.replayPendingPermissions(x);let te=wd(b),J=bd(b);return{sessionId:b.sessionId,clientId:x.clientId,connectedClients:b.connectedClients(x.clientId),historyPolicy:K,replayed:$.length,...te?{modes:te}:{},...J?{models:J}:{},configOptions:b.buildConfigOptions(),_meta:vd(e.manager,b)}}),a.onRequest("session/detach",async f=>{let u=Fl.parse(f),p=d.attached.get(u.sessionId);if(!p){let h=new Error("client not attached to that session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);return g?.detach(p.clientId),d.attached.delete(u.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[Mt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=Ol.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(w=>w.originatingClient?.name!==ss).map(Bl)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry){let f=new Error("agent registry unavailable");throw f.code=N.InternalError,f}return Ws(e.registry)}),a.onRequest("session/prompt",async f=>{let u=Nl.parse(f);c(u.sessionId,"session/prompt");let p=d.attached.get(u.sessionId);if(!p){t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`);let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);if(!g){let h=await e.manager.loadFromDisk(u.sessionId);if(!h){let v=new Error(`session ${u.sessionId} not found`);throw v.code=N.SessionNotFound,v}t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),g=await e.manager.resurrect(h),Id(g,e);let w=Ai(a,g,d,void 0,p.clientId);await g.attach(w,"none")}return g.prompt(p.clientId,u)});let l=f=>{let u;try{u=Ho.parse(f)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=d.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let g=e.manager.get(u.sessionId);g&&g.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Ho.parse(f);return c(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=Hl.parse(f);c(u.sessionId,"hydra-acp/prompt/cancel");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Ho.parse(f);c(u.sessionId,"hydra-acp/session/force_cancel");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=Ul.parse(f);c(u.sessionId,"hydra-acp/prompt/update");let p=e.manager.get(u.sessionId);if(!p){let g=new Error(`session ${u.sessionId} not found`);throw g.code=N.SessionNotFound,g}return p.updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=jl.parse(f);c(u.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(u.sessionId);if(!p){let h=new Error("not attached to session");throw h.code=N.SessionNotFound,h}let g=e.manager.get(u.sessionId);if(!g){let h=new Error(`session ${u.sessionId} not found`);throw h.code=N.SessionNotFound,h}return g.amendPrompt(p.clientId,u)}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p){let E=new Error("session/load requires sessionId");throw E.code=N.InvalidParams,E}let g=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(g);if(!h){let E=await e.manager.loadFromDisk(g);if(!E){let $=new Error(`session ${p} not found in memory or on disk`);throw $.code=N.SessionNotFound,$}h=await e.manager.resurrect(E),Id(h,e)}let w=Ai(a,h,d),{entries:v}=await h.attach(w,"pending_only");d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:w.clientId,readonly:!1});for(let E of v)await a.notify(E.method,E.params);h.replayPendingPermissions(w);let b=wd(h),x=bd(h);return{sessionId:h.sessionId,...b?{modes:b}:{},...x?{models:x}:{},configOptions:h.buildConfigOptions(),_meta:vd(e.manager,h,{clientId:w.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&c(u,"session/set_model");let p=bb(f,e.manager);if(p.kind==="error"){t.log.warn(p.logMessage);let w=new Error(p.message);throw w.code=p.code,w}if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:g}=p,h=await p.session.forwardRequest("session/set_model",{...f,modelId:g});return p.session.applyModelChange(g),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!u||typeof u.sessionId!="string"){let w=new Error("session/set_mode requires string sessionId");throw w.code=N.InvalidParams,w}if(typeof u.modeId!="string"){let w=new Error("session/set_mode requires string modeId");throw w.code=N.InvalidParams,w}let g=e.manager.get(u.sessionId);if(!g){let w=new Error(`session ${u.sessionId} not found`);throw w.code=N.SessionNotFound,w}let h=await g.forwardRequest("session/set_mode",f);return g.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=v=>{let b=new Error(v);return b.code=N.InvalidParams,b},g=u?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=e.manager.get(u.sessionId);if(!h){let v=new Error(`session ${u.sessionId} not found`);throw v.code=N.SessionNotFound,v}let w=h.buildConfigOptions().find(v=>v.id===u.configId);if(!w)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!w.options.some(v=>v.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{if(!u.startsWith("session/")||f===null||typeof f!="object"){let h=new Error(`Method not found: ${u}`);throw h.code=N.MethodNotFound,h}let p=f.sessionId;if(typeof p!="string"){let h=new Error(`Method not found: ${u}`);throw h.code=N.MethodNotFound,h}c(p,u);let g=e.manager.get(p);if(!g){let h=new Error(`session ${p} not found`);throw h.code=N.SessionNotFound,h}return g.forwardRequest(u,f)})})}function xf(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(Uo,n).catch(()=>{})}}function wd(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function bd(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function bb(t,e){if(!t||typeof t!="object")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:N.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:N.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),o=Js(n.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:N.InvalidParams,message:`model "${n.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}async function vb(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw Object.assign(new Error("transformer/attach requires sessionId"),{code:N.InvalidParams});if(!n.transformers)throw Object.assign(new Error("transformer manager not configured"),{code:N.InternalError});let o=n.transformers.resolveChain([e])[0];if(!o)throw Object.assign(new Error(`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`),{code:N.InternalError});let i=n.manager.get(r);if(!i)throw Object.assign(new Error(`session ${r} not found`),{code:N.SessionNotFound});return i.addTransformer(o),{ok:!0}}function Ib(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[Mt]:Do(e,n)}}function vd(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot()};return No(e.agentMeta,Do(s,r))}function Sb(){return{protocolVersion:It,agentInfo:{name:"hydra",version:le},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"bearer-token",description:"Bearer token presented at WS upgrade"}],_meta:No(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Id(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function Ai(t,e,n,s,r){return{clientId:r??`cli_${Sd(8)}`,connection:t,clientInfo:s}}var Ci=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((i,a)=>{n=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,n(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as kb}from"crypto";import{McpServer as xb}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Ab}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ze}from"zod";var Cf="Bearer ";function Ri(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(Cf))return;let n=e.slice(Cf.length).trim();return n.length>0?n:void 0}function Cb(t){let e=new xb({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:Ze.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:Ze.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s}}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:Ze.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:Ze.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Ze.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:n,max_bytes:s,wait_ms:r})=>{let o=await t.streamRead(n,s,r);return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent: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:Ze.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Ze.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),o=t.streamInfo(),i={outcome:r,writeCursor:o.writeCursor,closed:o.closed};return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),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:Ze.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Ze.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Ze.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Ze.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Ze.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Ze.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Ze.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Ze.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Ze.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.streamGrep(s),o=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:o}}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let n=t.streamInfo();return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}),e}var Rb=1e4;function Rf(t,e){let n=new Map;async function s(i,a){let d=n.get(i);if(d!==void 0)return d.transport;let c=Cb(a),l=new Ab({sessionIdGenerator:()=>kb()});await c.connect(l);let f={server:c,transport:l};return n.set(i,f),e.addDisposer(i,async()=>{n.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(i,a){let d=Ri(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 u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),Rb)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),g===void 0){a.code(503).send({error:"session not ready"});return}l=g}let f=await s(d,l);a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),t.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),t.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}var Ti=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as Fb}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Ob}from"crypto";import{Server as Tb}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Eb,ListToolsRequestSchema as Pb}from"@modelcontextprotocol/sdk/types.js";var Mb=6e4;function Tf(t,e,n={}){let s=n.invokeTimeoutMs??Mb,r=new Tb({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=new Map(e.tools.map(i=>[i.name,i]));return r.setRequestHandler(Pb,async()=>({tools:e.tools.map(i=>({name:i.name,description:i.description,inputSchema:i.inputSchema,...i.outputSchema!==void 0?{outputSchema:i.outputSchema}:{}}))})),r.setRequestHandler(Eb,async i=>{let a=i.params.name;if(!o.has(a))return Ei(`unknown tool: ${a}`);try{let d=await $b(e.connection,t,a,i.params.arguments??{},s);return _b(d,a)}catch(d){return Ei(d instanceof Error?d.message:String(d))}}),r}async function $b(t,e,n,s,r){let o,i=new Promise((a,d)=>{o=setTimeout(()=>d(new Error(`extension timeout after ${r}ms`)),r)});try{return await Promise.race([t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s}),i])}finally{o!==void 0&&clearTimeout(o)}}function _b(t,e){if(t===null||typeof t!="object")return Ei(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Ei(`extension ${e} omitted content array`)}function Ei(t){return{content:[{type:"text",text:t}],isError:!0}}var Lb=1e4;function Ef(t,e,n,s={}){let r=new Map;async function o(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let f of r.values()){let u=f.get(l);u!==void 0&&(f.delete(l),o(u))}}n.onChange(l=>{i(l)});async function a(l,f){let u=r.get(l);u===void 0&&(u=new Map,r.set(l,u),e.addDisposer(l,async()=>{let v=r.get(l);if(v!==void 0){r.delete(l);for(let b of v.values())await o(b)}}));let p=u.get(f);if(p!==void 0)return p.transport;let g=n.lookup(f);if(g===void 0)return;let h=Tf(f,g,s.buildOptions),w=new Fb({sessionIdGenerator:()=>Ob()});return await h.connect(w),u.set(f,{server:h,transport:w}),w}async function d(l,f){let u=Ri(l);if(u===void 0){f.code(401).send({error:"missing bearer token"});return}let p=e.lookup(u);if(p===void 0){f.code(404).send({error:"unknown mcp token"});return}if(p.session===void 0){let w,v=new Promise(x=>{w=setTimeout(()=>x(void 0),Lb)}),b=await Promise.race([p.sessionReady.catch(()=>{}),v]);if(w!==void 0&&clearTimeout(w),b===void 0){f.code(503).send({error:"session not ready"});return}}let g=l.params.name,h=await a(u,g);if(h===void 0){f.code(404).send({error:`unknown mcp server: ${g}`});return}f.hijack(),await h.handleRequest(l.raw,f.raw,l.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(l,f)=>{await d(l,f)}),t.get("/mcp/:name",c,async(l,f)=>{await d(l,f)}),t.delete("/mcp/:name",c,async(l,f)=>{await d(l,f)})}async function $f(t,e){Ub(t);let n=t.daemon.tls?{key:await Ln.readFile(t.daemon.tls.key),cert:await Ln.readFile(t.daemon.tls.cert)}:void 0;await Ln.mkdir(T.home(),{recursive:!0});let{stream:s,fileStream:r}=await Hb(t.daemon.logLevel),o=Bb({logger:{level:t.daemon.logLevel,stream:s},https:n??null,bodyLimit:256*1024*1024});await o.register(Nb,{options:{handleProtocols:fl}}),_a(Y=>{o.log.info(Y)}),La(Y=>{o.log.info(Y)});let i=await fi.load(),a=new yi,d=new gi,c=new hi([new pi(e),new mi(i),d]),l=Ku({validator:c});o.addHook("onRequest",async(Y,ge)=>{Y.routeOptions.config?.skipAuth||Y.url==="/acp"||Y.url?.startsWith("/acp?")||await l(Y,ge)});let f=setInterval(()=>{i.sweepExpired()},300*1e3);f.unref();let u=new Lo(t,{onFetched:()=>{Nu(u,w)}});fd(Y=>o.log.info(Y));let p={info:Y=>o.log.info(Y),warn:Y=>o.log.warn(Y)},g=Y=>_n.spawn({...Y,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:p});gl(t.compressToolContent);let h=new ci,w=new si(u,g,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,synopsisOnClose:t.synopsisOnClose,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:p,npmRegistry:t.npmRegistry,extensionCommands:h,defaultCwd:t.defaultCwd}),v=new ai(Vc(t),void 0,{tokenRegistry:d}),b=new di(Yc(t),void 0,{tokenRegistry:d});uf(o,le,Zs(t)),cf(o,w,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port}),lf(o,u,w,{npmRegistry:t.npmRegistry}),ff(o,v),pf(o,b),mf(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},synopsisOnClose:t.synopsisOnClose,defaultTransformers:[...t.defaultTransformers]}),Sf(o,{store:i,rateLimiter:a});let x=new Ci,E=new Ti;Rf(o,x),Ef(o,x,E);let $,K=()=>{if($!==void 0)return $;let Y=o.server.address(),ge=Y&&typeof Y=="object"?Y.port:t.daemon.port;return $=`${t.daemon.tls?"https":"http"}://${t.daemon.host}:${ge}`,$};Af(o,{validator:c,manager:w,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Y,ge)=>v.reportVersion(Y,ge),onTransformerVersion:(Y,ge)=>b.reportVersion(Y,ge),transformers:b,extensionCommands:h,mcpTokenRegistry:x,extensionMcp:E,getDaemonOrigin:K,registry:u}),await o.listen({host:t.daemon.host,port:t.daemon.port});let te=o.server.address(),J=te&&typeof te=="object"?te.port:t.daemon.port;await Ln.mkdir(T.home(),{recursive:!0}),await Ln.writeFile(T.pidFile(),JSON.stringify({pid:process.pid,host:t.daemon.host,port:J,startedAt:new Date().toISOString()})+`
|
|
249
|
+
`,{encoding:"utf8",mode:384});let D=t.daemon.tls?"https":"http",_=t.daemon.tls?"wss":"ws",H={daemonUrl:`${D}://${t.daemon.host}:${J}`,daemonHost:t.daemon.host,daemonPort:J,serviceToken:e,daemonWsUrl:`${_}://${t.daemon.host}:${J}/acp`,hydraHome:T.home()};v.setContext(H),b.setContext(H),await v.start(),await b.start(),w.resurrectPendingQueues().catch(Y=>{o.log.warn(`queue replay scan failed: ${Y.message}`)});let q=t.daemon.agentSyncIntervalMinutes*60*1e3,z=q>0?Du({registry:u,manager:w,intervalMs:q,logger:p}):void 0,be=t.daemon.sessionGcIntervalMinutes*60*1e3,xe=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,X=be>0?Hu({manager:w,intervalMs:be,maxAgeMs:xe,logger:p}):void 0;return{app:o,manager:w,registry:u,extensions:v,transformers:b,mcpTokenRegistry:x,extensionMcp:E,processRegistry:d,shutdown:async()=>{X&&X(),z&&z(),clearInterval(f),await i.flush(),await v.stop(),await b.stop(),await w.closeAll(),await w.flushSynopsis(3e4),await w.shutdownSynopsis(),await w.flushMetaWrites(),await w.flushHistoryWrites(),_a(null),La(null),fd(null),await o.close();try{Mf.unlinkSync(T.pidFile())}catch{}try{r.flushSync()}catch{}}}}async function Hb(t){let e=await Db({file:T.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),n=Pf.destination(2);return{stream:Pf.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function Ub(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Zr();jt();ui();import*as _f from"fs";import*as sr from"fs/promises";async function Bn(t,e,n){let s=zb(e),r;try{r=await sr.stat(t)}catch(d){if(d.code==="ENOENT"){process.stderr.write(`${n} (${t})
|
|
250
|
+
`),process.exit(1);return}throw d}let o=await Wb(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
|
|
251
|
+
`);let i=!1,a=_f.watch(t,()=>{i||(i=!0,setImmediate(async()=>{i=!1;try{let d=await sr.stat(t);if(d.size<=o){d.size<o&&(o=d.size);return}let c=await sr.open(t,"r");try{let l=Buffer.alloc(d.size-o);await c.read(l,0,l.length,o),process.stdout.write(l),o=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function Wb(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await sr.open(t,"r");try{let o=e,i="",a=0;for(;o>0&&a<=n;){let l=Math.min(s,o);o-=l;let f=Buffer.alloc(l);await r.read(f,0,l,o),i=f.toString("utf8")+i,a=(i.match(/\n/g)??[]).length}let c=i.split(`
|
|
252
252
|
`).slice(-n-1);process.stdout.write(c.join(`
|
|
253
253
|
`)),i.endsWith(`
|
|
254
254
|
`)||process.stdout.write(`
|
|
255
|
-
`)}finally{await r.close()}return e}function rr(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let o=t[r];if(o===void 0)break;if(o.startsWith("-")){if(s.push(o),e.has(o)&&r+1<t.length){let i=t[r+1];i!==void 0&&s.push(i),r+=2;continue}r+=1;continue}if(n===void 0){n=o,r+=1;continue}s.push(o),r+=1}return{name:n,rest:s}}function
|
|
255
|
+
`)}finally{await r.close()}return e}function rr(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let o=t[r];if(o===void 0)break;if(o.startsWith("-")){if(s.push(o),e.has(o)&&r+1<t.length){let i=t[r+1];i!==void 0&&s.push(i),r+=2;continue}r+=1;continue}if(n===void 0){n=o,r+=1;continue}s.push(o),r+=1}return{name:n,rest:s}}function zb(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let o=t[s+1],i=Number.parseInt(o??"",10);(!Number.isInteger(i)||i<0)&&(process.stderr.write(`Invalid --tail value: ${o}
|
|
256
256
|
`),process.exit(2)),e=i,s+=2;continue}if(r==="--follow"||r==="-f"){n=!0,s+=1;continue}return process.stderr.write(`Unknown flag: ${r}
|
|
257
257
|
`),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function Lf(t={}){let e=await G(),n=await Mr();if(await Xr(e)){let r=await or();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
|
|
258
258
|
`);return}if($s(t,"foreground")){process.title="hydra-daemon";let r=await $f(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
|
|
@@ -263,10 +263,10 @@ ${za}`:za;await n.connection.request("session/prompt",{sessionId:d,prompt:[{type
|
|
|
263
263
|
`)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
|
|
264
264
|
`)}}async function Nf(){let t=await G();await Mr();let e=await or();if(e&&kd(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
|
|
265
265
|
`);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
|
|
266
|
-
`),process.exit(1)}await
|
|
266
|
+
`),process.exit(1)}await Kb(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
|
|
267
267
|
`),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
|
|
268
268
|
`);if(Mi(),await $i(t),await Xr(t)){let n=await or();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
|
|
269
|
-
`)}}async function
|
|
269
|
+
`)}}async function Kb(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!kd(t))return!0;await Jb(50)}return!1}async function Df(t){await Bn(T.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Hf(){let t=await or();if(!t){process.stdout.write(`Daemon: not running
|
|
270
270
|
`),process.stdout.write(`CLI version: ${le}
|
|
271
271
|
`);return}let e=kd(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
|
|
272
272
|
`);let n,s;if(e)try{let i=await G();n=await Pi(i),s=Zs(i)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${le}
|
|
@@ -274,92 +274,92 @@ ${za}`:za;await n.connection.request("session/prompt",{sessionId:d,prompt:[{type
|
|
|
274
274
|
`);return}let r=n.version===le,o=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&o){process.stdout.write(`Version: ${le}
|
|
275
275
|
`);return}process.stdout.write(`CLI version: ${le}
|
|
276
276
|
`),process.stdout.write(`Daemon version: ${n.version}
|
|
277
|
-
`),r||process.stdout.write(Ff.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!o&&process.stdout.write(Ff.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function or(){try{let t=await Of.readFile(
|
|
277
|
+
`),r||process.stdout.write(Ff.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!o&&process.stdout.write(Ff.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function or(){try{let t=await Of.readFile(T.pidFile(),"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return;throw t}}function kd(t){try{return process.kill(t,0),!0}catch{return!1}}Dn();Dd();Bi();Od();_e();wt();de();import*as Wi from"fs/promises";Dn();async function Sp(){let t=await G(),e=await ce(),n=me(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let d=await fetch(`${n}/v1/extensions`,{headers:{Authorization:`Bearer ${e}`}});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
|
|
278
278
|
`),process.exit(1)),s=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${n}: ${d.message}
|
|
279
279
|
`),process.exit(1);return}if(s.extensions.length===0){process.stdout.write(`No extensions configured.
|
|
280
|
-
`);return}let r=s.extensions.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?
|
|
280
|
+
`);return}let r=s.extensions.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?Vv(d.startedAt):"-",log:d.logPath})),o={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},i={name:fr(o.name,r.map(d=>d.name)),status:fr(o.status,r.map(d=>d.status)),version:fr(o.version,r.map(d=>d.version)),pid:fr(o.pid,r.map(d=>d.pid)),restarts:fr(o.restarts,r.map(d=>d.restarts)),started:fr(o.started,r.map(d=>d.started))},a=d=>[d.name.padEnd(i.name),d.status.padEnd(i.status),d.version.padEnd(i.version),d.pid.padStart(i.pid),d.restarts.padStart(i.restarts),d.started.padEnd(i.started),d.log].join(" ");process.stdout.write(a(o)+`
|
|
281
281
|
`);for(let d of r)process.stdout.write(a(d)+`
|
|
282
282
|
`);for(let d of s.extensions)d.failureReason&&process.stdout.write(` \u21B3 ${d.name}: ${d.failureReason}
|
|
283
|
-
`)}async function
|
|
283
|
+
`)}async function kp(t,e){if(!t){process.stderr.write(`Usage: hydra-acp extensions add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
|
|
284
284
|
`),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid extension name '${t}': must match [A-Za-z0-9._-]+
|
|
285
|
-
`),process.exit(2);return}await G();let n=await
|
|
286
|
-
`),process.exit(1);return}let{command:r,args:o,env:i,enabled:a}=
|
|
285
|
+
`),process.exit(2);return}await G();let n=await Ap();(!n.extensions||typeof n.extensions!="object")&&(n.extensions={});let s=n.extensions;if(s[t]){process.stderr.write(`Extension '${t}' already exists in config.
|
|
286
|
+
`),process.exit(1);return}let{command:r,args:o,env:i,enabled:a}=Jv(e),d={};r.length>0&&(d.command=r),o.length>0&&(d.args=o),Object.keys(i).length>0&&(d.env=i),a||(d.enabled=!1),s[t]=d,await Cp(n),process.stdout.write(`Added extension '${t}' to ${T.config()}
|
|
287
287
|
`);let c=await G(),l=await ce(),f=me(c.daemon.host,c.daemon.port,!!c.daemon.tls),u={name:t,...d};try{let p=await fetch(`${f}/v1/extensions`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(u)});if(p.ok){let h=await p.json(),w=h.pid!=null?` pid=${h.pid}`:"";process.stdout.write(`${t}: ${h.status}${w}
|
|
288
288
|
`);return}let g="";try{let h=await p.json();h.error&&(g=`: ${h.error}`)}catch{}process.stderr.write(`Daemon refused to register ${t} (HTTP ${p.status}${g}). Restart the daemon to apply.
|
|
289
|
-
`)}catch{}}async function
|
|
290
|
-
`),process.exit(2);return}await G();let e=await
|
|
291
|
-
`),process.exit(1);return}delete n[t],e.extensions=n,await
|
|
289
|
+
`)}catch{}}async function xp(t){if(!t){process.stderr.write(`Usage: hydra-acp extensions remove <name>
|
|
290
|
+
`),process.exit(2);return}await G();let e=await Ap(),n=e.extensions??{};if(!n[t]){process.stderr.write(`Extension '${t}' not found in config.
|
|
291
|
+
`),process.exit(1);return}delete n[t],e.extensions=n,await Cp(e),process.stdout.write(`Removed extension '${t}' from ${T.config()}
|
|
292
292
|
`);let s=await G(),r=await ce(),o=me(s.daemon.host,s.daemon.port,!!s.daemon.tls);try{let i=await fetch(`${o}/v1/extensions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(i.status===204||i.status===404){process.stdout.write(`${t}: stopped
|
|
293
293
|
`);return}let a="";try{let d=await i.json();d.error&&(a=`: ${d.error}`)}catch{}process.stderr.write(`Daemon refused to unregister ${t} (HTTP ${i.status}${a}).
|
|
294
294
|
`)}catch(i){process.stderr.write(`Daemon not reachable (${i.message}). Config saved.
|
|
295
|
-
`)}}async function
|
|
296
|
-
`,{encoding:"utf8",mode:384})}async function
|
|
297
|
-
`),process.exit(2);return}if(t==="all"){await
|
|
295
|
+
`)}}async function Ap(){let t=await Wi.readFile(T.config(),"utf8");return JSON.parse(t)}async function Cp(t){await Wi.writeFile(T.config(),JSON.stringify(t,null,2)+`
|
|
296
|
+
`,{encoding:"utf8",mode:384})}async function Rp(t){await Hd(t,"start")}async function Tp(t){await Hd(t,"stop")}async function Ep(t){await Hd(t,"restart")}async function Hd(t,e){if(!t){process.stderr.write(`Usage: hydra-acp extensions ${e} <name|all>
|
|
297
|
+
`),process.exit(2);return}if(t==="all"){await zv(e);return}let n=await G(),s=await ce(),r=me(n.daemon.host,n.daemon.port,!!n.daemon.tls),o;try{o=await fetch(`${r}/v1/extensions/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`}})}catch(d){process.stderr.write(`Could not reach daemon at ${r}: ${d.message}
|
|
298
298
|
`),process.exit(1);return}if(!o.ok){let d="";try{let c=await o.json();c.error&&(d=`: ${c.error}`)}catch{}process.stderr.write(`HTTP ${o.status}${d}
|
|
299
299
|
`),process.exit(1);return}let i=await o.json(),a=i.pid!=null?` pid=${i.pid}`:"";process.stdout.write(`${t}: ${i.status}${a}
|
|
300
|
-
`)}async function
|
|
300
|
+
`)}async function zv(t){let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r={Authorization:`Bearer ${n}`},o;try{let d=await fetch(`${s}/v1/extensions`,{headers:r});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
|
|
301
301
|
`),process.exit(1)),o=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${s}: ${d.message}
|
|
302
302
|
`),process.exit(1);return}let i=o.extensions.filter(d=>t==="start"?d.enabled&&d.status!=="running":d.status==="running");if(i.length===0){let d=t==="start"?"no enabled extensions are stopped":"no extensions are running";process.stdout.write(`Nothing to ${t}: ${d}.
|
|
303
303
|
`);return}let a=0;for(let d of i)try{let c=await fetch(`${s}/v1/extensions/${encodeURIComponent(d.name)}/${t}`,{method:"POST",headers:r});if(!c.ok){let u="";try{let p=await c.json();p.error&&(u=`: ${p.error}`)}catch{}process.stdout.write(`${d.name}: ERROR HTTP ${c.status}${u}
|
|
304
304
|
`),a+=1;continue}let l=await c.json(),f=l.pid!=null?` pid=${l.pid}`:"";process.stdout.write(`${d.name}: ${l.status}${f}
|
|
305
305
|
`)}catch(c){process.stdout.write(`${d.name}: ERROR ${c.message}
|
|
306
|
-
`),a+=1}a>0&&process.exit(1)}async function
|
|
307
|
-
`),process.exit(2);return}let s=
|
|
308
|
-
`),process.exit(2)),e=
|
|
306
|
+
`),a+=1}a>0&&process.exit(1)}async function Pp(t){let{name:e,rest:n}=rr(t);if(!e){process.stderr.write(`Usage: hydra-acp extensions log <name> [--tail N] [--follow]
|
|
307
|
+
`),process.exit(2);return}let s=T.extensionLogFile(e);await Bn(s,n,"No log file (extension never ran?)")}function Jv(t){let e=[],n=[],s={},r=!0,o=0;for(;o<t.length;){let i=t[o];if(i==="--command"){let a=t[o+1];a===void 0&&(process.stderr.write(`--command requires a value
|
|
308
|
+
`),process.exit(2)),e=Kv(a),o+=2;continue}if(i==="--args"){let a=t[o+1];a===void 0&&(process.stderr.write(`--args requires a value
|
|
309
309
|
`),process.exit(2)),n=a.split(",").filter(d=>d.length>0),o+=2;continue}if(i==="--env"){let a=t[o+1];a===void 0&&(process.stderr.write(`--env requires KEY=VALUE
|
|
310
310
|
`),process.exit(2));let d=a.indexOf("=");d<=0&&(process.stderr.write(`Invalid --env value '${a}': expected KEY=VALUE
|
|
311
311
|
`),process.exit(2)),s[a.slice(0,d)]=a.slice(d+1),o+=2;continue}if(i==="--disabled"){r=!1,o+=1;continue}return process.stderr.write(`Unknown flag: ${i}
|
|
312
|
-
`),process.exit(2),{command:[],args:[],env:{},enabled:!0}}return{command:e,args:n,env:s,enabled:r}}function
|
|
312
|
+
`),process.exit(2),{command:[],args:[],env:{},enabled:!0}}return{command:e,args:n,env:s,enabled:r}}function Kv(t){return t.split(/\s+/).filter(e=>e.length>0)}function Vv(t){let e=Math.max(0,Date.now()-t),n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function fr(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}_e();wt();de();import*as zi from"fs/promises";Dn();async function Mp(){let t=await G(),e=await ce(),n=me(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let d=await fetch(`${n}/v1/transformers`,{headers:{Authorization:`Bearer ${e}`}});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
|
|
313
313
|
`),process.exit(1)),s=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${n}: ${d.message}
|
|
314
314
|
`),process.exit(1);return}if(s.transformers.length===0){process.stdout.write(`No transformers configured.
|
|
315
|
-
`);return}let r=s.transformers.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?
|
|
315
|
+
`);return}let r=s.transformers.map(d=>({name:d.name,status:d.status.toUpperCase(),version:d.version??"-",pid:d.pid!=null?String(d.pid):"-",restarts:String(d.restartCount),started:d.startedAt?Xv(d.startedAt):"-",log:d.logPath})),o={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},i={name:pr(o.name,r.map(d=>d.name)),status:pr(o.status,r.map(d=>d.status)),version:pr(o.version,r.map(d=>d.version)),pid:pr(o.pid,r.map(d=>d.pid)),restarts:pr(o.restarts,r.map(d=>d.restarts)),started:pr(o.started,r.map(d=>d.started))},a=d=>[d.name.padEnd(i.name),d.status.padEnd(i.status),d.version.padEnd(i.version),d.pid.padStart(i.pid),d.restarts.padStart(i.restarts),d.started.padEnd(i.started),d.log].join(" ");process.stdout.write(a(o)+`
|
|
316
316
|
`);for(let d of r)process.stdout.write(a(d)+`
|
|
317
317
|
`);for(let d of s.transformers)d.failureReason&&process.stdout.write(` \u21B3 ${d.name}: ${d.failureReason}
|
|
318
|
-
`)}async function
|
|
318
|
+
`)}async function $p(t,e){if(!t){process.stderr.write(`Usage: hydra-acp transformers add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
|
|
319
319
|
`),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid transformer name '${t}': must match [A-Za-z0-9._-]+
|
|
320
|
-
`),process.exit(2);return}await G();let n=await
|
|
321
|
-
`),process.exit(1);return}let{command:r,args:o,env:i,enabled:a}=
|
|
320
|
+
`),process.exit(2);return}await G();let n=await Np();(!n.transformers||typeof n.transformers!="object")&&(n.transformers={});let s=n.transformers;if(s[t]){process.stderr.write(`Transformer '${t}' already exists in config.
|
|
321
|
+
`),process.exit(1);return}let{command:r,args:o,env:i,enabled:a}=Qv(e),d={};r.length>0&&(d.command=r),o.length>0&&(d.args=o),Object.keys(i).length>0&&(d.env=i),a||(d.enabled=!1),s[t]=d,await Dp(n),process.stdout.write(`Added transformer '${t}' to ${T.config()}
|
|
322
322
|
`);let c=await G(),l=await ce(),f=me(c.daemon.host,c.daemon.port,!!c.daemon.tls),u={name:t,...d};try{let p=await fetch(`${f}/v1/transformers`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(u)});if(p.ok){let h=await p.json(),w=h.pid!=null?` pid=${h.pid}`:"";process.stdout.write(`${t}: ${h.status}${w}
|
|
323
323
|
`);return}let g="";try{let h=await p.json();h.error&&(g=`: ${h.error}`)}catch{}process.stderr.write(`Daemon refused to register ${t} (HTTP ${p.status}${g}). Restart the daemon to apply.
|
|
324
|
-
`)}catch{}}async function
|
|
325
|
-
`),process.exit(2);return}await G();let e=await
|
|
326
|
-
`),process.exit(1);return}delete n[t],e.transformers=n,await
|
|
324
|
+
`)}catch{}}async function _p(t){if(!t){process.stderr.write(`Usage: hydra-acp transformers remove <name>
|
|
325
|
+
`),process.exit(2);return}await G();let e=await Np(),n=e.transformers??{};if(!n[t]){process.stderr.write(`Transformer '${t}' not found in config.
|
|
326
|
+
`),process.exit(1);return}delete n[t],e.transformers=n,await Dp(e),process.stdout.write(`Removed transformer '${t}' from ${T.config()}
|
|
327
327
|
`);let s=await G(),r=await ce(),o=me(s.daemon.host,s.daemon.port,!!s.daemon.tls);try{let i=await fetch(`${o}/v1/transformers/${encodeURIComponent(t)}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(i.status===204||i.status===404){process.stdout.write(`${t}: stopped
|
|
328
328
|
`);return}let a="";try{let d=await i.json();d.error&&(a=`: ${d.error}`)}catch{}process.stderr.write(`Daemon refused to unregister ${t} (HTTP ${i.status}${a}).
|
|
329
329
|
`)}catch(i){process.stderr.write(`Daemon not reachable (${i.message}). Config saved.
|
|
330
|
-
`)}}async function
|
|
331
|
-
`),process.exit(2);return}if(t==="all"){await
|
|
330
|
+
`)}}async function Fp(t){await Ud(t,"start")}async function Op(t){await Ud(t,"stop")}async function Lp(t){await Ud(t,"restart")}async function Ud(t,e){if(!t){process.stderr.write(`Usage: hydra-acp transformers ${e} <name|all>
|
|
331
|
+
`),process.exit(2);return}if(t==="all"){await Yv(e);return}let n=await G(),s=await ce(),r=me(n.daemon.host,n.daemon.port,!!n.daemon.tls),o;try{o=await fetch(`${r}/v1/transformers/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`}})}catch(d){process.stderr.write(`Could not reach daemon at ${r}: ${d.message}
|
|
332
332
|
`),process.exit(1);return}if(!o.ok){let d="";try{let c=await o.json();c.error&&(d=`: ${c.error}`)}catch{}process.stderr.write(`HTTP ${o.status}${d}
|
|
333
333
|
`),process.exit(1);return}let i=await o.json(),a=i.pid!=null?` pid=${i.pid}`:"";process.stdout.write(`${t}: ${i.status}${a}
|
|
334
|
-
`)}async function
|
|
334
|
+
`)}async function Yv(t){let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r={Authorization:`Bearer ${n}`},o;try{let d=await fetch(`${s}/v1/transformers`,{headers:r});d.ok||(process.stderr.write(`Daemon returned HTTP ${d.status}
|
|
335
335
|
`),process.exit(1)),o=await d.json()}catch(d){process.stderr.write(`Could not reach daemon at ${s}: ${d.message}
|
|
336
336
|
`),process.exit(1);return}let i=o.transformers.filter(d=>t==="start"?d.enabled&&d.status!=="running":d.status==="running");if(i.length===0){let d=t==="start"?"no enabled transformers are stopped":"no transformers are running";process.stdout.write(`Nothing to ${t}: ${d}.
|
|
337
337
|
`);return}let a=0;for(let d of i)try{let c=await fetch(`${s}/v1/transformers/${encodeURIComponent(d.name)}/${t}`,{method:"POST",headers:r});if(!c.ok){let u="";try{let p=await c.json();p.error&&(u=`: ${p.error}`)}catch{}process.stdout.write(`${d.name}: ERROR HTTP ${c.status}${u}
|
|
338
338
|
`),a+=1;continue}let l=await c.json(),f=l.pid!=null?` pid=${l.pid}`:"";process.stdout.write(`${d.name}: ${l.status}${f}
|
|
339
339
|
`)}catch(c){process.stdout.write(`${d.name}: ERROR ${c.message}
|
|
340
|
-
`),a+=1}a>0&&process.exit(1)}async function
|
|
341
|
-
`),process.exit(2);return}let s=
|
|
342
|
-
`,{encoding:"utf8",mode:384})}function
|
|
343
|
-
`),process.exit(2)),e=
|
|
340
|
+
`),a+=1}a>0&&process.exit(1)}async function Bp(t){let{name:e,rest:n}=rr(t);if(!e){process.stderr.write(`Usage: hydra-acp transformers log <name> [--tail N] [--follow]
|
|
341
|
+
`),process.exit(2);return}let s=T.transformerLogFile(e);await Bn(s,n,"No log file (transformer never ran?)")}async function Np(){let t=await zi.readFile(T.config(),"utf8");return JSON.parse(t)}async function Dp(t){await zi.writeFile(T.config(),JSON.stringify(t,null,2)+`
|
|
342
|
+
`,{encoding:"utf8",mode:384})}function Qv(t){let e=[],n=[],s={},r=!0,o=0;for(;o<t.length;){let i=t[o];if(i==="--command"){let a=t[o+1];a===void 0&&(process.stderr.write(`--command requires a value
|
|
343
|
+
`),process.exit(2)),e=Gv(a),o+=2;continue}if(i==="--args"){let a=t[o+1];a===void 0&&(process.stderr.write(`--args requires a value
|
|
344
344
|
`),process.exit(2)),n=a.split(",").filter(d=>d.length>0),o+=2;continue}if(i==="--env"){let a=t[o+1];a===void 0&&(process.stderr.write(`--env requires KEY=VALUE
|
|
345
345
|
`),process.exit(2));let d=a.indexOf("=");d<=0&&(process.stderr.write(`Invalid --env value '${a}': expected KEY=VALUE
|
|
346
346
|
`),process.exit(2)),s[a.slice(0,d)]=a.slice(d+1),o+=2;continue}if(i==="--disabled"){r=!1,o+=1;continue}return process.stderr.write(`Unknown flag: ${i}
|
|
347
|
-
`),process.exit(2),{command:[],args:[],env:{},enabled:!1}}return{command:e,args:n,env:s,enabled:r}}function
|
|
347
|
+
`),process.exit(2),{command:[],args:[],env:{},enabled:!1}}return{command:e,args:n,env:s,enabled:r}}function Gv(t){return t.split(/\s+/).filter(e=>e.length>0)}function Xv(t){let e=Math.max(0,Date.now()-t),n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function pr(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}_e();wt();de();import*as qp from"fs/promises";Dn();async function Wp(){let t=await G(),e=await ce(),n=me(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let c=await fetch(`${n}/v1/agents`,{headers:{Authorization:`Bearer ${e}`}});c.ok||(process.stderr.write(`Daemon returned HTTP ${c.status}
|
|
348
348
|
`),process.exit(1)),s=await c.json()}catch(c){process.stderr.write(`Could not reach daemon at ${n}: ${c.message}
|
|
349
349
|
`),process.exit(1);return}if(s.agents.length===0){process.stdout.write(`No agents in registry.
|
|
350
350
|
`);return}let r=s.agents.map(c=>({id:c.id,name:c.name,version:c.version,source:c.source??"registry",distributions:c.distributions.join(","),installed:c.installed,description:c.description??""})),o={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},i={id:wn(o.id,r.map(c=>c.id)),name:wn(o.name,r.map(c=>c.name)),version:wn(o.version,r.map(c=>c.version)),source:wn(o.source,r.map(c=>c.source)),distributions:wn(o.distributions,r.map(c=>c.distributions)),installed:wn(o.installed,r.map(c=>c.installed))},a=c=>[c.id.padEnd(i.id),c.name.padEnd(i.name),c.version.padEnd(i.version),c.source.padEnd(i.source),c.distributions.padEnd(i.distributions),c.installed.padEnd(i.installed),c.description].join(" ");process.stdout.write(a(o)+`
|
|
351
351
|
`);for(let c of r)process.stdout.write(a(c)+`
|
|
352
|
-
`);let d=s.fetchedAt!==void 0?` (synced ${
|
|
352
|
+
`);let d=s.fetchedAt!==void 0?` (synced ${Zv(Date.now()-s.fetchedAt)} ago)`:"";process.stdout.write(`
|
|
353
353
|
Registry version: ${s.version}${d}
|
|
354
|
-
`)}function
|
|
355
|
-
`),process.exit(2))}async function
|
|
354
|
+
`)}function Zv(t){if(t<0)return"just now";let e=Math.floor(t/1e3);if(e<60)return"just now";let n=Math.floor(e/60);if(n<60)return`${n} minute${n===1?"":"s"}`;let s=Math.floor(n/60);if(s<24)return`${s} hour${s===1?"":"s"}`;let r=Math.floor(s/24);return`${r} day${r===1?"":"s"}`}async function qd(t){let e=await G();if(e.agents[t]!==void 0)return;let n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r;try{let o=await fetch(`${s}/v1/agents`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)return;r=(await o.json()).agents.map(a=>a.id)}catch{return}r.includes(t)||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
|
|
355
|
+
`),process.exit(2))}async function zp(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
|
|
356
356
|
`),process.exit(2);return}let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls);process.stdout.write(`Installing ${t}\u2026
|
|
357
357
|
`);let r;try{let o=await fetch(`${s}/v1/agents/${encodeURIComponent(t)}/install`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!o.ok){let i=`HTTP ${o.status}`;try{let a=await o.json();a.error&&(i=a.error)}catch{}process.stderr.write(`hydra agent install ${t}: ${i}
|
|
358
358
|
`),process.exit(1)}r=await o.json()}catch(o){process.stderr.write(`Could not reach daemon at ${s}: ${o.message}
|
|
359
359
|
`),process.exit(1);return}if(!r.installed){process.stdout.write(`${r.agentId} (${r.version}, ${r.distribution}): ${r.message??"nothing to install"}
|
|
360
360
|
`);return}process.stdout.write(`Installed ${r.agentId} (${r.version}, ${r.distribution})
|
|
361
361
|
`),r.command&&process.stdout.write(` \u2192 ${r.command}
|
|
362
|
-
`)}async function
|
|
362
|
+
`)}async function Jp(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
|
|
363
363
|
`),process.exit(2);return}let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r;try{let c=await fetch(`${s}/v1/agents/${encodeURIComponent(t)}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!c.ok){let l=`HTTP ${c.status}`;try{let f=await c.json();f.error&&(l=f.error)}catch{}process.stderr.write(`hydra agent sync ${t}: ${l}
|
|
364
364
|
`),process.exit(1)}r=await c.json()}catch(c){process.stderr.write(`Could not reach daemon at ${s}: ${c.message}
|
|
365
365
|
`),process.exit(1);return}if(r.synced.length===0){process.stdout.write(`Nothing new to sync (${r.skipped} already tracked).
|
|
@@ -367,61 +367,61 @@ Registry version: ${s.version}${d}
|
|
|
367
367
|
`);for(let c of o)process.stdout.write(d(c)+`
|
|
368
368
|
`);process.stdout.write(`
|
|
369
369
|
Synced ${r.synced.length} session(s); skipped ${r.skipped} already tracked.
|
|
370
|
-
`)}async function
|
|
371
|
-
`),process.exit(2);return}let n=
|
|
370
|
+
`)}async function Kp(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
|
|
371
|
+
`),process.exit(2);return}let n=T.agentLogFile(t);await Bn(n,e,"No log file (agent never ran?)")}async function Vp(t,e){let n=await G(),s=await ce(),r=me(n.daemon.host,n.daemon.port,!!n.daemon.tls);if(!t){let l=await Up(r,s)??jd(await jp());process.stdout.write(`${Hp(l)}
|
|
372
372
|
`);return}let o;try{let c=await fetch(`${r}/v1/agents`,{headers:{Authorization:`Bearer ${s}`}});c.ok&&(o=(await c.json()).agents.map(f=>f.id))}catch{}if(!(n.agents[t]!==void 0)&&o!==void 0&&!o.includes(t)){process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${o.join(", ")}
|
|
373
|
-
`),process.exit(1);return}e!==void 0?await Qc(t,e):await Eo(t);let a=
|
|
374
|
-
`),process.stdout.write(`${
|
|
375
|
-
`);let d=await
|
|
376
|
-
`))}function
|
|
373
|
+
`),process.exit(1);return}e!==void 0?await Qc(t,e):await Eo(t);let a=jd(await jp());e!==void 0&&t!==a.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
|
|
374
|
+
`),process.stdout.write(`${Hp(a)}
|
|
375
|
+
`);let d=await Up(r,s);d!==void 0&&(d.agent===a.agent&&d.model===a.model||process.stdout.write(`Daemon still has ${Yp(d)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
|
|
376
|
+
`))}function Hp(t){return`Default agent is ${Yp(t)}`}function Yp(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function jd(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Up(t,e){try{let n=await fetch(`${t}/v1/config`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return;let s=await n.json();return jd(s)}catch{return}}async function jp(){let t=await qp.readFile(T.config(),"utf8");return JSON.parse(t)}async function Wd(){let t=await G(),e=await ce(),n=me(t.daemon.host,t.daemon.port,!!t.daemon.tls),s;try{let r=await fetch(`${n}/v1/registry/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});r.ok||(process.stderr.write(`Daemon returned HTTP ${r.status}
|
|
377
377
|
`),process.exit(1)),s=await r.json()}catch(r){process.stderr.write(`Could not reach daemon at ${n}: ${r.message}
|
|
378
378
|
`),process.exit(1);return}process.stdout.write(`Refreshed registry: ${s.agentCount} agents (version ${s.version})
|
|
379
|
-
`)}async function
|
|
379
|
+
`)}async function Qp(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
|
|
380
380
|
`),process.exit(2);return}await Gc(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
|
|
381
381
|
`):process.stdout.write(`Pinned ${t} to ${e}.
|
|
382
|
-
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function
|
|
382
|
+
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Gp(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
|
|
383
383
|
`),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid agent id '${t}': must match [A-Za-z0-9._-]+
|
|
384
|
-
`),process.exit(2);return}let{command:n,args:s,env:r}=
|
|
385
|
-
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function
|
|
384
|
+
`),process.exit(2);return}let{command:n,args:s,env:r}=eI(e),o={};n!==void 0&&(o.command=n),s.length>0&&(o.args=s),Object.keys(r).length>0&&(o.env=r),await ba(t,o);let i=n??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${s.length>0?" "+s.join(" "):""}
|
|
385
|
+
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Xp(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
|
|
386
386
|
`),process.exit(2);return}await ba(t,void 0),process.stdout.write(`Removed local agent ${t}.
|
|
387
|
-
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}function
|
|
387
|
+
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}function eI(t){let e,n=[],s={},r=0;for(;r<t.length;){let o=t[r];if(o==="--command"){let i=t[r+1];i===void 0&&(process.stderr.write(`--command requires a value
|
|
388
388
|
`),process.exit(2)),e=i,r+=2;continue}if(o==="--args"){let i=t[r+1];i===void 0&&(process.stderr.write(`--args requires a value
|
|
389
389
|
`),process.exit(2)),n=i.split(",").filter(a=>a.length>0),r+=2;continue}if(o==="--env"){let i=t[r+1];i===void 0&&(process.stderr.write(`--env requires KEY=VALUE
|
|
390
390
|
`),process.exit(2));let a=i.indexOf("=");a<=0&&(process.stderr.write(`Invalid --env value '${i}': expected KEY=VALUE
|
|
391
391
|
`),process.exit(2)),s[i.slice(0,a)]=i.slice(a+1),r+=2;continue}return process.stderr.write(`Unknown flag: ${o}
|
|
392
|
-
`),process.exit(2),{command:void 0,args:[],env:{}}}return{command:e,args:n,env:s}}async function
|
|
393
|
-
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function wn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}_e();wt();xa();
|
|
392
|
+
`),process.exit(2),{command:void 0,args:[],env:{}}}return{command:e,args:n,env:s}}async function zd(t){await Xc(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
|
|
393
|
+
`),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function wn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}_e();wt();xa();Dn();async function Zp(t){let e=$s(t,"force");if(await Si()&&!e){let r=await Ds("Current password: ");await ki(r)||(process.stderr.write(`Wrong password.
|
|
394
394
|
`),process.exit(1))}let n=await Ds("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
|
|
395
395
|
`),process.exit(2));let s=await Ds("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
|
|
396
396
|
`),process.exit(1)),await If(n),process.stdout.write(`Password set.
|
|
397
|
-
`)}async function
|
|
397
|
+
`)}async function em(){let t=await G(),e=await ce(),n=me(t.daemon.host,t.daemon.port,!!t.daemon.tls),s=await fetch(`${n}/v1/auth/sessions`,{headers:{Authorization:`Bearer ${e}`}});s.ok||(process.stderr.write(`Daemon returned HTTP ${s.status}
|
|
398
398
|
`),process.exit(1));let r=await s.json();if(r.sessions.length===0){process.stdout.write(`No active session tokens.
|
|
399
399
|
`);return}let o={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},i=r.sessions.map(c=>({id:c.id,label:c.label??"-",createdAt:c.createdAt,expiresAt:c.expiresAt,lastUsedAt:c.lastUsedAt})),a={id:Ji(o.id,i.map(c=>c.id)),label:Ji(o.label,i.map(c=>c.label)),createdAt:Ji(o.createdAt,i.map(c=>c.createdAt)),expiresAt:Ji(o.expiresAt,i.map(c=>c.expiresAt))},d=c=>[c.id.padEnd(a.id),c.label.padEnd(a.label),c.createdAt.padEnd(a.createdAt),c.expiresAt.padEnd(a.expiresAt),c.lastUsedAt].join(" ");process.stdout.write(d(o)+`
|
|
400
400
|
`);for(let c of i)process.stdout.write(d(c)+`
|
|
401
|
-
`)}async function
|
|
401
|
+
`)}async function tm(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
|
|
402
402
|
`),process.exit(2));let e=await G(),n=await ce(),s=me(e.daemon.host,e.daemon.port,!!e.daemon.tls),r=await fetch(`${s}/v1/auth/sessions/${t}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(r.status===204){process.stdout.write(`Revoked ${t}
|
|
403
403
|
`);return}r.status===404&&(process.stderr.write(`No session token with id ${t}
|
|
404
404
|
`),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${r.status}
|
|
405
|
-
`),process.exit(1)}function Ji(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as
|
|
406
|
-
`);for(let l of c)await
|
|
407
|
-
`),r.close(),process.exit(d?1:0)}),r.onClose(()=>{a.close(),process.exit(0)}),await a.start()}function
|
|
408
|
-
`);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let o={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(o.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:o}}).catch(()=>{})}}}async function
|
|
405
|
+
`),process.exit(1)}function Ji(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Hn from"fs";_e();Hs();Zr();Jd();dt();var Ki=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Vd(e)){let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(Kd(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!Kd(e)&&!Vd(e)&&"method"in e){if(e.method==="session/update"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0,p=typeof f.update?.messageId=="string"?f.update.messageId:void 0;u&&p&&this.lastMessageIds.set(u,p)}return}if(Kd(e)){if(e.method==="session/request_permission"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0;if(u){let p=f.toolCall,g=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:u,toolCallId:g,params:f};this.pendingPermissions.set(e.id,h),g&&this.pendingPermissionsByToolCall.set(g,h)}}return}if(!Vd(e))return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let o=s._meta,i=St(o),a=i.upstreamSessionId,d=i.agentId,c="";(n.kind==="new"||n.kind==="load")&&(c=n.data.cwd);let l=i.cwd??c;!a||!d||!l||this.contexts.set(r,{sessionId:r,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)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);return n&&this.deletePendingPermission(n),n}deletePendingPermission(e){this.pendingPermissions.delete(e.requestId),e.toolCallId&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}};function Kd(t){return"method"in t&&"id"in t&&t.id!==void 0}function Vd(t){return!("method"in t)&&"id"in t}Yi();jt();de();$o();import{writeFileSync as cI}from"fs";var lI=t=>{cI("/proc/self/comm",t)};function hr(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??lI;try{s(e.commName??Pn())}catch{}}function gr(t,e=Pn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Gi(t){hr(gr(process.argv.slice(2)),{commName:"hydra-shim"});let e=await G(),n=t.target??await Qt(e);n.isLocal&&!t.target&&await nr(e);let s=new Ki,r=jo(process.stdin,process.stdout),o=n.wsUrl,i=["acp.v1",`hydra-acp-token.${n.token}`],a=new mr({url:o,subprotocols:i,onConnect:async d=>{if(d)return;s.clearPending(),await gI(s,r);let c=s.list();if(c.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${c.length} session(s)
|
|
406
|
+
`);for(let l of c)await yI(a,l,s.lastMessageId(l.sessionId))}}});uI({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(d=>{d&&process.stderr.write(`hydra-acp: ${d.message}
|
|
407
|
+
`),r.close(),process.exit(d?1:0)}),r.onClose(()=>{a.close(),process.exit(0)}),await a.start()}function uI({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(o=>{if(am("daemon\u2192client",o),s.observeFromServer(o),t.dangerouslySkipPermissions===!0&&II(o)){e.send({jsonrpc:"2.0",id:o.id,result:ls(o.params)});return}fI(o,s,n),n.send(o)});let r={name:t.name,used:!1};n.onMessage(o=>{if(am("client\u2192daemon",o),s.observeFromClient(o),bI(o)){e.send(vI(o));return}if(wI(o)){if(t.sessionId){e.send(SI(o,t.sessionId));return}let i=o;t.agentId&&(i=Qi(i,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(i=Qi(i,{agentArgs:t.agentArgs})),r.name&&!r.used&&(i=Qi(i,{title:r.name}),r.used=!0),t.model&&(i=Qi(i,{model:t.model})),e.send(i);return}e.send(o)})}function fI(t,e,n){let s=pI(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let o=e.takePendingPermissionByToolCall(r);if(!o)return;let i=hI(s);n.send({jsonrpc:"2.0",id:o.requestId,result:i?{outcome:i}:null}).catch(()=>{})}function pI(t){if(!mI(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function mI(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function hI(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function gI(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
|
|
408
|
+
`);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let o={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(o.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:o}}).catch(()=>{})}}}async function yI(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let o={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let i=await t.request(o);i.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${i.error.message}
|
|
409
409
|
`)}catch(i){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${i.message}
|
|
410
|
-
`)}}function
|
|
411
|
-
`;
|
|
410
|
+
`)}}function wI(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function bI(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function vI(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:le}}}}function II(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function SI(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var kI=25*1024*1024,im=!1,us=null;function am(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!im){im=!0;try{us=T.shimWireLogFile(),Hn.mkdirSync(T.home(),{recursive:!0});let n=Hn.statSync(us,{throwIfNoEntry:!1});n&&n.size>kI&&Hn.renameSync(us,`${us}.1`)}catch{us=null}}if(us)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
|
|
411
|
+
`;Hn.appendFile(us,n,()=>{})}catch{}}}function Qi(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Fr();xi();_e();Hs();Zr();ds();dt();jt();Yi();import{mkdtempSync as FI,rmSync as OI}from"fs";import{tmpdir as LI}from"os";import{join as BI}from"path";import{WebSocket as NI}from"ws";function dm(t){let e="",n=!1,s=!1,r=!1,o=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},i=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){i();return}o()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:i())},eof(){r||(r=!0,o())}}}so();import xI from"chalk";import AI from"strip-ansi";var Xi=new xI.Instance({level:3});function cm(t,e){if(t.length===0)return"";let n=ur(t);if(n.length===0)return"";let s=[];for(let o of n)s.push(CI(o,e));let r=s.join(`
|
|
412
412
|
`);return r.endsWith(`
|
|
413
413
|
`)||(r+=`
|
|
414
|
-
`),r}function
|
|
415
|
-
`),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let d
|
|
414
|
+
`),r}function CI(t,e){let n=$I(t.body,e);return e==="ansi"?n=_I(n,t.bodyStyle):n=AI(n),n}var RI="\x1B[1m",TI="\x1B[96m",EI="\x1B[93m",PI="\x1B[0m",MI="\0";function $I(t,e){let n=t.replace(/\^\^/g,MI);return e==="ansi"&&(n=n.replace(/\^\+/g,RI).replace(/\^C/g,TI).replace(/\^Y/g,EI).replace(/\^:/g,PI)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function _I(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Xi.bold.yellowBright(t);case"heading-2":return Xi.bold.cyanBright(t);case"heading-3":return Xi.bold(t);case"dim":return Xi.dim(t);default:return t}}var DI=1*1024*1024,lm="mcp__hydra-acp-stdin__";function um(t,e){return{sessionId:t,prompt:e,_meta:{[Mt]:{ancillary:!0}}}}function HI(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function UI(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(lm))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(lm))}async function fm(t){if(hr(gr(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
|
|
415
|
+
`),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let d=FI(BI(LI(),"hydra-cat-"));t.cwd=d,t.detach||process.on("exit",()=>{try{OI(d,{recursive:!0,force:!0})}catch{}})}let e=await G(),n=t.target??await Qt(e);n.isLocal&&!t.target&&await nr(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await KI(n.wsUrl,s),o=tr(r),i=new Zt(o),a=await qI({conn:i,opts:t,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:jI(n.baseUrl,n.token)});process.exit(a.exitCode)}function jI(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,o)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${o}`;return{async open(r,o){let i=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(o)});if(!i.ok)throw new Error(`stdin/open HTTP ${i.status}`);return await i.json()},async write(r,o,i){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:o,eof:i})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function qI(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:o,stdout:i,stderr:a}=t,d=o?"ansi":"plain",c=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async X=>n.dangerouslySkipPermissions?ls(X):UI(X)?ls(X):sm(X));try{await e.request("initialize",{protocolVersion:It,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:ss,version:le}})}catch{}let f=await JI(e,n,l),u=!1,p=!0,g="",h=0,w=X=>{X.length!==0&&(i(X),p=X.charCodeAt(X.length-1)===10,u=!0)},v=()=>{if(c||g.length===0)return;let X=cm(g,d);if(g="",X.length===0)return;let Ae=h>0?`
|
|
416
416
|
`:"";w(Ae+X),h+=1},b=()=>{v(),u&&!p&&w(`
|
|
417
|
-
`),u=!1};e.onNotification("session/update",X=>{let Ae=X?.update,Y=
|
|
417
|
+
`),u=!1};e.onNotification("session/update",X=>{let Ae=X?.update,Y=as(Ae,{cwd:n.cwd});if(Y){if(Y.kind==="agent-text"){c?w(Y.text):g+=Y.text;return}if(Y.kind==="turn-complete"){b();return}switch(Y.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":v();return;default:return}}});let x=!1,E=async X=>{let Ae=[];if(n.prompt&&!x&&Ae.push({type:"text",text:n.prompt}),X.length>0&&Ae.push({type:"text",text:X}),Ae.length!==0){try{await e.request("session/prompt",um(f,Ae)),x=!0}catch(Y){a(`hydra-acp cat: prompt failed: ${Y.message}
|
|
418
418
|
`);return}b()}},$=0,K,te=new Promise(X=>{K=X}),J=!1,D=async X=>{J||(J=!0,b(),n.detach||e.request("session/detach",{sessionId:f}).catch(()=>{}),await e.close().catch(()=>{}),K({exitCode:X}))};e.onClose(X=>{X&&(a(`hydra-acp cat: ${X.message}
|
|
419
|
-
`),$=1),J||(J=!0,b(),K({exitCode:$}))});let _=[],H=!1,q=!1,z=async()=>{if(!H){H=!0;try{for(;_.length>0;){let X=_.shift();if(X===void 0)break;await
|
|
419
|
+
`),$=1),J||(J=!0,b(),K({exitCode:$}))});let _=[],H=!1,q=!1,z=async()=>{if(!H){H=!0;try{for(;_.length>0;){let X=_.shift();if(X===void 0)break;await E(X)}}finally{H=!1,q&&_.length===0&&await D($)}}};if(r&&!n.sessionId)return n.prompt&&await E(""),await D(0),te;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),WI({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:E,onEof:()=>{q=!0,!H&&_.length===0&&D($)},onError:X=>{a(`hydra-acp cat: stdin error: ${X.message}
|
|
420
420
|
`),$=1,q=!0,!H&&_.length===0&&D($)},onPromptFailed:X=>{a(`hydra-acp cat: ${X.message}
|
|
421
|
-
`),$=1,q=!0,!H&&_.length===0&&D($)}}),te;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let X=
|
|
421
|
+
`),$=1,q=!0,!H&&_.length===0&&D($)}}),te;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let X=dm({scheduleFlushCheck:Ae=>{let Y=setImmediate(Ae);return()=>clearImmediate(Y)},onChunk:Ae=>{_.push(Ae),z()}});return s.on("data",Ae=>{X.feed(typeof Ae=="string"?Ae:Ae.toString("utf8"))}),s.on("end",()=>{X.eof(),q=!0,!H&&_.length===0&&D($)}),s.on("error",Ae=>{a(`hydra-acp cat: stdin error: ${Ae.message}
|
|
422
422
|
`),$=1,q=!0,!H&&_.length===0&&D($)}),te}let xe="";return s.on("data",X=>{xe+=typeof X=="string"?X:X.toString("utf8")}),s.on("end",()=>{q=!0,xe.length>0&&_.push(xe),z()}),s.on("error",X=>{a(`hydra-acp cat: stdin error: ${X.message}
|
|
423
|
-
`),$=1,q=!0,!H&&_.length===0&&D($)}),te}function
|
|
424
|
-
`)})},g=async()=>{c="inline";let w=l.toString("utf8");l=Buffer.alloc(0);try{await a(w)}catch(v){t.onPromptFailed(v);return}t.onEof()},h=async()=>{c="file";let w;try{let
|
|
423
|
+
`),$=1,q=!0,!H&&_.length===0&&D($)}),te}function WI(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:o,stderr:i,sendInline:a}=t,d=r.streamThreshold??DI,c="undecided",l=Buffer.alloc(0),f=!1,u=Promise.resolve(),p=(w,v)=>{let b=w.toString("base64");u=u.then(()=>n.write(s,b,v)).catch(x=>{i(`hydra-acp cat: stdin write failed: ${x.message}
|
|
424
|
+
`)})},g=async()=>{c="inline";let w=l.toString("utf8");l=Buffer.alloc(0);try{await a(w)}catch(v){t.onPromptFailed(v);return}t.onEof()},h=async()=>{c="file";let w;try{let x={mode:"memory"};r.streamBufferBytes!==void 0&&(x.capacityBytes=r.streamBufferBytes),w=await n.open(s,x)}catch(x){t.onPromptFailed(new Error(`stdin/open failed: ${x.message}`));return}l.length>0&&(p(l,!1),l=Buffer.alloc(0)),await u.catch(()=>{});let v=zI(r.prompt,w.capacityBytes);e.request("session/prompt",um(s,[{type:"text",text:v}])).catch(x=>{t.onPromptFailed(new Error(`prompt failed: ${x.message}`))}).then(()=>{f||p(Buffer.alloc(0),!0),t.onEof()})};o.on("data",w=>{let v=typeof w=="string"?Buffer.from(w,"utf8"):w;if(c==="undecided"){l=Buffer.concat([l,v]),l.length>d&&h();return}if(c==="file"){p(v,!1);return}l=Buffer.concat([l,v])}),o.on("end",()=>{if(f=!0,c==="undecided"){g();return}c==="file"&&p(Buffer.alloc(0),!0)}),o.on("error",t.onError)}function zI(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
|
|
425
425
|
- \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
|
|
426
426
|
- \`grep({pattern, regex?, case_insensitive?, context_before?, context_after?, cursor?})\` \u2014 server-side line filter; returns matching lines as decoded strings (not base64). Prefer this for "find lines that mention X" questions on multi-MB inputs.
|
|
427
427
|
- \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
|
|
@@ -436,28 +436,29 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
|
|
|
436
436
|
User's question:
|
|
437
437
|
${t}`:`${s}
|
|
438
438
|
|
|
439
|
-
Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function
|
|
440
|
-
`)
|
|
441
|
-
`)
|
|
442
|
-
`),process.exit(2);return}let
|
|
443
|
-
`)
|
|
444
|
-
`)
|
|
445
|
-
`),process.exit(2);return}
|
|
446
|
-
`),process.exit(2);return}
|
|
447
|
-
`),process.exit(2);return}
|
|
448
|
-
`),process.exit(2);return}
|
|
449
|
-
`),process.exit(2);return}
|
|
450
|
-
`),process.exit(2);return}case"
|
|
451
|
-
`),process.exit(2);return}case"
|
|
452
|
-
`),process.exit(2);return}case"
|
|
453
|
-
`),process.exit(2);return}case"
|
|
454
|
-
`),process.exit(2);return}if(w===
|
|
455
|
-
`),process.exit(2);return}
|
|
456
|
-
`),
|
|
457
|
-
`),process.exit(2))
|
|
439
|
+
Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function JI(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:ss,version:le}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=HI(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let o={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(o._meta={[Mt]:s});let i=await t.request("session/new",o);return St(i._meta),i.sessionId}async function KI(t,e){return new Promise((n,s)=>{let r=new NI(t,e),o=()=>{r.off("error",i),n(r)},i=a=>{r.off("open",o),s(a)};r.once("open",o),r.once("error",i)})}import{spawnSync as VI}from"child_process";import{accessSync as YI,constants as QI,statSync as GI}from"fs";import{delimiter as XI,join as ZI}from"path";var eS=new Set(["agent","agents","auth","cat","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function tS(t){return eS.has(t)}function nS(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function sS(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function rS(t){try{if(!GI(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return YI(t,QI.X_OK),!0}catch{return!1}}function oS(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(XI).filter(i=>i.length>0),r=`hydra-acp-${t}`,o=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let i of s)for(let a of o){let d=ZI(i,r+a);if(rS(d))return d}}function iS(t,e){let n=VI(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
|
|
440
|
+
`),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function pm(t){let e=nS(t);if(e===void 0||tS(e))return!1;let n=oS(e);if(n===void 0)return!1;iS(n,sS(t))}Yd();var gs=!1,mh=!1;function hh(t){!t||mh||(mh=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
|
|
441
|
+
`))}async function _k(){let t=process.argv.slice(2),e=t.indexOf("launch");if(e!==-1){let w=t.slice(0,e),v=t.slice(e+1),b=v[0],x=v.slice(1),{flags:E}=ga(w);if(yh(E),E.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
|
|
442
|
+
`),process.exit(2);return}let $=b??ze(E,"agent");if(!$){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
|
|
443
|
+
`),process.exit(2);return}let K=await wh(Ra(E),{allowPrompt:!1}),te=ze(E,"name"),J=ze(E,"model");gs=!0;let D=E["dangerously-skip-permissions"]===!0;hh(D);let _={agentId:$,agentArgs:x,name:te,model:J,dangerouslySkipPermissions:D};K?.sessionId!==void 0&&(_.sessionId=K.sessionId),K?.target!==void 0&&K.fromUrl&&(_.target=K.target),await Gi(_);return}Ic(t)===void 0&&!t.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&pm(t);let{positional:n,flags:s}=ga(t);if(yh(s),s.version===!0||n[0]==="--version"){process.stdout.write(`hydra-acp ${Fk()}
|
|
444
|
+
`);return}if(s.help===!0){kc();return}let r=Ic(t)!==void 0||typeof s.prompt=="string",o=n[0],i=o!==void 0&&!o.startsWith("-")?o:r?"cat":o,a=ze(s,"name"),d=ze(s,"agent"),c=ze(s,"model"),l=s["dangerously-skip-permissions"]===!0;hh(l);let f=Ra(s),u=i==="tui"||i===void 0&&process.stdout.isTTY,p=await wh(f,{allowPrompt:u});p!==void 0&&p.sessionId!==void 0&&s.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
|
|
445
|
+
`),process.exit(2));let g=p?.sessionId,h=p?.fromUrl?p.target:void 0;if(!i){if(process.stdout.isTTY){gs=!0,await gh(s,{sessionId:g,agentId:d,name:a,model:c,target:h,dangerouslySkipPermissions:l});return}gs=!0;let w={name:a,model:c,agentId:d,dangerouslySkipPermissions:l};g!==void 0&&(w.sessionId=g),h!==void 0&&(w.target=h),await Gi(w);return}switch(i){case"shim":{gs=!0;let w={name:a,model:c,agentId:d,dangerouslySkipPermissions:l};g!==void 0&&(w.sessionId=g),h!==void 0&&(w.target=h),await Gi(w);return}case"cat":{let w=Ic(t),v=typeof s.prompt=="string"?s.prompt:void 0,b=w??v,x=ze(s,"cwd"),E={prompt:b,sessionId:g,name:a,model:c,agentId:d,detach:s.detach===!0,follow:s.follow===!0,raw:s.raw===!0,dangerouslySkipPermissions:l};x!==void 0&&(E.cwd=x),h!==void 0&&(E.target=h);let $=Sc(s,"stream-threshold");$!==void 0&&(E.streamThreshold=$);let K=Sc(s,"stream-bytes");K!==void 0&&(E.streamBufferBytes=K),d!==void 0&&await qd(d),gs=!0,await fm(E);return}case"init":await ll(s);return;case"daemon":{let w=t.indexOf("daemon"),v=t.slice(w+1),b=v[0];if(b===void 0||b==="status"){await Hf();return}if(b==="start"){await Lf(s);return}if(b==="stop"){await Bf();return}if(b==="restart"){await Nf();return}if(b==="logs"){await Df(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${b}
|
|
446
|
+
`),process.exit(2);return}case"session":case"sessions":{let w=n[1];if(w===void 0||w==="list"){let v=ze(s,"columns"),b;if(v!==void 0)try{b=Xf(v)}catch(x){process.stderr.write(`${x.message}
|
|
447
|
+
`),process.exit(2);return}await ep({all:s.all===!0,json:s.json===!0,host:typeof s.host=="string"?s.host:void 0,includeNonInteractive:s["include-non-interactive"]===!0,columns:b});return}if(w==="info"){await Ip(n[2],{verbose:s.verbose===!0,json:s.json===!0,diff:s.diff===!0,fold:s.fold===!0,noColor:s["no-color"]===!0,noPager:s["no-pager"]===!0});return}if(w==="diff"){await vp(n[2],{json:s.json===!0,noColor:s["no-color"]===!0,noPager:s["no-pager"]===!0,fold:s.fold===!0});return}if(w==="kill"){await tp(n[2]);return}if(w==="remove"){await np(n[2]);return}if(w==="collect"){let v=ze(s,"max-age-days"),b=ze(s,"limit"),x={json:s.json===!0,keepUndecided:s["keep-undecided"]===!0};if(v!==void 0){let E=Number(v);if(!Number.isFinite(E)||E<0){process.stderr.write(`--max-age-days must be a non-negative number
|
|
448
|
+
`),process.exit(2);return}x.maxAgeDays=E}if(b!==void 0){let E=Number(b);if(!Number.isFinite(E)||E<=0){process.stderr.write(`--limit must be a positive number
|
|
449
|
+
`),process.exit(2);return}x.limit=E}await sp(x);return}if(w==="export"){let v=ze(s,"out"),b=ze(s,"tools");await rp(n[2],v,b);return}if(w==="transcript"){let v=ze(s,"out");await op(n[2],v);return}if(w==="import"){let v=ze(s,"cwd");await ip(n[2],{replace:s.replace===!0,info:s.info===!0,...v!==void 0?{cwd:v}:{}});return}if(w==="share"){let v=ze(s,"host"),b=ze(s,"cwd");await ap(n[2],{...v!==void 0?{host:v}:{},...b!==void 0?{cwd:b}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
|
|
450
|
+
`),process.exit(2);return}case"extension":case"extensions":{let w=t.indexOf(i),v=t.slice(w+1),b=v[0],x=v[1],E=v.slice(2);if(b===void 0||b==="list"){await Sp();return}if(b==="add"){await kp(x,E);return}if(b==="remove"){await xp(x);return}if(b==="start"){await Rp(x);return}if(b==="stop"){await Tp(x);return}if(b==="restart"){await Ep(x);return}if(b==="log"||b==="logs"){await Pp(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${b}
|
|
451
|
+
`),process.exit(2);return}case"transformer":case"transformers":{let w=t.indexOf(i),v=t.slice(w+1),b=v[0],x=v[1],E=v.slice(2);if(b===void 0||b==="list"){await Mp();return}if(b==="add"){await $p(x,E);return}if(b==="remove"){await _p(x);return}if(b==="start"){await Fp(x);return}if(b==="stop"){await Op(x);return}if(b==="restart"){await Lp(x);return}if(b==="log"||b==="logs"){await Bp(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${b}
|
|
452
|
+
`),process.exit(2);return}case"agent":case"agents":{let w=n[1];if(w===void 0||w==="list"){await Wp();return}if(w==="refresh"){await Wd();return}if(w==="install"){await zp(n[2]);return}if(w==="sync"){await Jp(n[2]);return}if(w==="set"){await Vp(n[2],n[3]);return}if(w==="pin"){await Qp(n[2],n[3]);return}if(w==="add"){let v=t.indexOf(i),b=t.slice(v+1);await Gp(b[1],b.slice(2));return}if(w==="remove"){await Xp(n[2]);return}if(w==="log"||w==="logs"){let v=t.indexOf(i),b=t.slice(v+2),{name:x,rest:E}=rr(b);await Kp(x,E);return}process.stderr.write(`Unknown agent subcommand: ${w}
|
|
453
|
+
`),process.exit(2);return}case"registry":{let w=n[1];if(w==="refresh"){await Wd();return}if(w==="pin"){await zd(!0);return}if(w==="unpin"){await zd(!1);return}process.stderr.write(`Unknown registry subcommand: ${w}
|
|
454
|
+
`),process.exit(2);return}case"auth":{let w=n[1];if(w==="password"){let v=n[2];if(v===void 0||v==="set"){await Zp(s);return}process.stderr.write(`Unknown auth password action: ${v}
|
|
455
|
+
`),process.exit(2);return}if(w===void 0||w==="list"){await em();return}if(w==="revoke"){await tm(n[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
|
|
456
|
+
`),process.exit(2);return}case"tui":gs=!0,await gh(s,{sessionId:g,agentId:d,name:a,model:c,target:h,dangerouslySkipPermissions:l});return;default:process.stderr.write(`Unknown command: ${i}
|
|
457
|
+
`),kc(),process.exit(2)}}async function gh(t,e){let n=ze(t,"cwd"),s=t.reattach===!0,r=t.new===!0,o=t.readonly===!0;o&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await qd(e.agentId),hr(gr(process.argv.slice(2)));let{runTui:i}=await Promise.resolve().then(()=>(ph(),fh)),a={resume:s,forceNew:r,readonly:o};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
|
|
458
|
+
`),process.exit(2)),a.drip=!0;let d=Sc(t,"drip-speed");d!==void 0&&d>0&&(a.dripSpeed=d)}await i(a)}function Sc(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function yh(t){let e=jc(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
|
|
458
459
|
|
|
459
|
-
`),
|
|
460
|
-
`),process.exit(1)}}function bk(){try{let t=gk(hk(import.meta.url));return JSON.parse(mk(yk(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Ic(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon logs [-f] [-n N] Tail or follow the daemon log"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."," hydra-acp session kill <id> Demote a live session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."," hydra-acp agent remove <id> Remove a local agent."," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
|
|
461
|
-
`))}async function
|
|
462
|
-
`)}catch{}}
|
|
463
|
-
`),await
|
|
460
|
+
`),kc(),process.exit(2))}function Ic(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function wh(t,e){try{return await dl(t,e)}catch(n){process.stderr.write(`${n.message}
|
|
461
|
+
`),process.exit(1)}}function Fk(){try{let t=Mk(Pk(import.meta.url));return JSON.parse(Ek($k(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function kc(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon logs [-f] [-n N] Tail or follow the daemon log"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."," hydra-acp session kill <id> Demote a live session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."," hydra-acp agent remove <id> Remove a local agent."," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","External subcommands:"," Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"," `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"," @hydra-acp/planner expose themselves through this mechanism.","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
|
|
462
|
+
`))}async function bh(){if(!gs)try{let t=await oo();t&&process.stderr.write(`\u2728 ${io(t)}
|
|
463
|
+
`)}catch{}}_k().then(bh).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
|
|
464
|
+
`),await bh(),process.exit(1)});
|