@hydra-acp/cli 0.1.79 → 0.1.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +130 -130
  2. package/dist/index.js +6 -6
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ stderr: ${f}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.c
16
16
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
17
17
  stderr: ${t}`:e}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=_o(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
18
18
  `),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()} ---
19
- `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},Fo=2e3;function Oo(n){try{let e=w.agentLogFile(n);bt.mkdirSync(Ds.dirname(e),{recursive:!0});let t=bt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Me from"fs/promises";import*as _t from"os";import*as it from"path";import{customAlphabet as Qa}from"nanoid";import{customAlphabet as Ys}from"nanoid";import*as qs from"fs/promises";var No=64*1024*1024,jo=1*1024*1024,Ne=64*1024,Ho=6e4,Bo=100,Uo=1e3,Do=64*1024,Lo=256*1024,Ls=20;function qo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var St=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??No,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(jo,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Ne));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),f={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(f.gap=i),this.closed&&r+d>=this.writeCursor&&(f.eof=!0),f}tail(e){let t=Math.max(0,Math.min(e,Ne)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Ne)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Ho));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(qo(e.pattern),d),f=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Bo,Uo)),l=Math.max(1,Math.min(e.maxBytes??Do,Lo)),p=Math.max(0,Math.min(e.contextBefore??0,Ls)),g=Math.max(0,Math.min(e.contextAfter??0,Ls)),m=[],h=[],y=[],k=0,S=!1,A=0,N=0,H=(R,P)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:R,line:P}),D.remaining--,k+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==f&&m.length<u){let D={cursor:R,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let he of D.before)k+=he.line.length}k+=P.length,m.push(D),g>0&&y.push({match:D,remaining:g})}if(p>0)for(h.push({cursor:R,line:P});h.length>p;)h.shift();let B=m.length>=u&&y.length===0,q=k>=l;return B||q};for(let R=0;R<o.length;R++){if(o[R]!==10)continue;let P=o.subarray(A,R).toString("utf8"),j=r+A;if(A=R+1,N=A,H(j,P)){S=!0;break}}if(!S&&A<o.length&&this.closed){let R=o.subarray(A).toString("utf8"),P=r+A;H(P,R)&&(S=!0),N=o.length}let X=Math.min(r+N,this.writeCursor),J={matches:m,truncated:S,nextCursor:X,scannedBytes:N};return i>0&&(J.gap=i),this.closed&&X>=this.writeCursor&&(J.eof=!0),J}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>qs.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var kt=[{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)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],vl=new Map(kt.map(n=>[n.verb,n]));function Js(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function je(n,e){return vn(n,e.map(t=>t.modelId))}function vn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=Js(n),s=e.filter(i=>Js(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function zs(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=In(d);if(c?.sessionUpdate!=="tool_call_update")continue;let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&(e.set(f,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(f,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(f);u?u.push(...c.content):t.set(f,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=In(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let f=c.sessionUpdate;if(f==="agent_message_chunk"||f==="agent_thought_chunk"||f==="user_message_chunk"){i&&i.kind===f?zo(r,i.outIndex,Jo(c.content)):(r.push(d),i={outIndex:r.length-1,kind:f});continue}if(i=null,f==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let l=u!==void 0&&t.has(u)?Wo(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!Qo(l)&&(l=Vo(l,s.get(u))),r.push(l);continue}if(f==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(f==="prompt_received"||f==="turn_complete")&&(o=null),r.push(d)}return r}function In(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Jo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function zo(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Wo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Qo(n){let t=In(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Vo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as ce from"fs/promises";async function Ke(n,e){let t=w.queueFile(n);if(e.length===0){await ce.unlink(t).catch(()=>{});return}await ce.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
19
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},Fo=2e3;function Oo(n){try{let e=w.agentLogFile(n);bt.mkdirSync(Ds.dirname(e),{recursive:!0});let t=bt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Me from"fs/promises";import*as _t from"os";import*as it from"path";import{customAlphabet as Qa}from"nanoid";import{customAlphabet as Ys}from"nanoid";import*as qs from"fs/promises";var No=64*1024*1024,jo=1*1024*1024,Ne=64*1024,Ho=6e4,Bo=100,Uo=1e3,Do=64*1024,Lo=256*1024,Ls=20;function qo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var St=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??No,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(jo,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Ne));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),f={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(f.gap=i),this.closed&&r+d>=this.writeCursor&&(f.eof=!0),f}tail(e){let t=Math.max(0,Math.min(e,Ne)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Ne)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Ho));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(qo(e.pattern),d),f=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Bo,Uo)),l=Math.max(1,Math.min(e.maxBytes??Do,Lo)),p=Math.max(0,Math.min(e.contextBefore??0,Ls)),g=Math.max(0,Math.min(e.contextAfter??0,Ls)),m=[],h=[],y=[],A=0,S=!1,k=0,j=0,N=(R,P)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:R,line:P}),D.remaining--,A+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==f&&m.length<u){let D={cursor:R,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let he of D.before)A+=he.line.length}A+=P.length,m.push(D),g>0&&y.push({match:D,remaining:g})}if(p>0)for(h.push({cursor:R,line:P});h.length>p;)h.shift();let B=m.length>=u&&y.length===0,q=A>=l;return B||q};for(let R=0;R<o.length;R++){if(o[R]!==10)continue;let P=o.subarray(k,R).toString("utf8"),H=r+k;if(k=R+1,j=k,N(H,P)){S=!0;break}}if(!S&&k<o.length&&this.closed){let R=o.subarray(k).toString("utf8"),P=r+k;N(P,R)&&(S=!0),j=o.length}let X=Math.min(r+j,this.writeCursor),J={matches:m,truncated:S,nextCursor:X,scannedBytes:j};return i>0&&(J.gap=i),this.closed&&X>=this.writeCursor&&(J.eof=!0),J}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>qs.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var kt=[{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)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],vl=new Map(kt.map(n=>[n.verb,n]));function Js(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function je(n,e){return vn(n,e.map(t=>t.modelId))}function vn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=Js(n),s=e.filter(i=>Js(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function zs(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=In(d);if(c?.sessionUpdate!=="tool_call_update")continue;let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&(e.set(f,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(f,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(f);u?u.push(...c.content):t.set(f,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=In(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let f=c.sessionUpdate;if(f==="agent_message_chunk"||f==="agent_thought_chunk"||f==="user_message_chunk"){i&&i.kind===f?zo(r,i.outIndex,Jo(c.content)):(r.push(d),i={outIndex:r.length-1,kind:f});continue}if(i=null,f==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let l=u!==void 0&&t.has(u)?Wo(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!Qo(l)&&(l=Vo(l,s.get(u))),r.push(l);continue}if(f==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(f==="prompt_received"||f==="turn_complete")&&(o=null),r.push(d)}return r}function In(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Jo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function zo(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Wo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Qo(n){let t=In(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Vo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as ce from"fs/promises";async function Ke(n,e){let t=w.queueFile(n);if(e.length===0){await ce.unlink(t).catch(()=>{});return}await ce.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
20
20
  `)+`
21
21
  `;await ce.writeFile(t,s,"utf8")}async function Ws(n){let e=w.queueFile(n),t;try{t=await ce.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
22
22
  `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Qs(n){let e=w.queueFile(n);await ce.unlink(e).catch(()=>{})}import*as er from"fs/promises";var Ks="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Xs=Ys(Ks,16),Vs=Ys(Ks,16),ge="hydra_session_";function He(){return`m_${Xs()}`}function Zs(n){return n.startsWith(ge)?n.slice(ge.length):n}var Go=1e3,bn=300*1e3,Yo=64,xe=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}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;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){this.sessionId=e.sessionId??`${ge}${Xs()}`,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.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Go,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){sa(this.internalPromptCapture,t);return}this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>this.handlePermissionRequest(t)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0){let r=e,i=this.injectCumulativeCost(e);for(let d=s;d<this.transformChain.length;d++){let c=this.transformChain[d];if(t.has(c.name)||!c.intercepts.has("response:session/update"))continue;let f=`t_${Vs()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return;if(l==="processing"){let p=d,g=i,m=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:c.name}),this.runResponseChain(g,new Set([...m,c.name]),p+1).then(()=>h()).catch(()=>h()))},bn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:m,side:"response"})});return}t.add(c.name)}let o=ra(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=na(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.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 t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}attach(e,t,s={}){if(this.closed)throw K(new Error("session is closed"),I.SessionNotFound);if(this.clients.has(e.clientId))throw K(new Error(`client ${e.clientId} is already attached`),I.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=o=>t.raw?o:zs(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?kn(r,t.afterMessageId):-1;return o<0?{entries:[...i,...s(r)],appliedPolicy:"full"}:{entries:[...i,...s(r.slice(o+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(r)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return e}replayPendingPermissions(e){for(let t of this.inFlightPermissions)t.addClient(e)}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw K(new Error("client not attached"),I.SessionNotFound);if(this.closing)throw K(new Error("session is closing; new prompts cannot be accepted"),I.SessionClosing);let r=He();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ye((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Be(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,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:He()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Yo;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw K(new Error("client not attached"),I.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(f=>f.messageId===r&&f.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=He(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=He(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw K(new Error("client not attached"),I.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let f=`t_${Vs()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:f,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return i==="notification"?void 0:u?.payload??Sn(e);if(l==="processing"){let p=a,g=o,m=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:d.name}),this.forwardRequest(e,g,new Set([...m,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:Sn(e))))},bn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):bn,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:Sn(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Be((e??{}).prompt),r=An(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=Ue(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ue(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(o.id==="mode"){let a=Xe(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let c=d.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=Ue(o.options);if(d.length>0){let c=Xe(o.options),f=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),u=o.name,l=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,g=typeof p=="string"&&p.trim()?p.trim():f[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=f,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:l,category:"other",type:"select",currentValue:g,options:f})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let t={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=t;for(let s of this.usageHandlers)try{s(t)}catch{}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Zo(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(ea(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),ta(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(!t)return;if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}applyModeChange(e){let t=e.trim();if(!t)return;if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{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:t,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${t} ${s.verb}`:`hydra ${t}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),t.startsWith("hydra-acp-")){let a=t.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,f={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(f.description=s.description),e.push(f)}}}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 i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(kt.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=I.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let c=kt.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:l}of this.extensionCommands.list())u.has(l)||(c.push(l),u.add(l))}let f=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw f.code=I.InvalidParams,f}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(g=>g.verb===o)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},f=new Promise(g=>{c=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let u,l=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,f]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return l=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.message}`)}finally{s!==void 0&&!l&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
@@ -59,7 +59,7 @@ ${g}:
59
59
  ${l.join(`
60
60
  `)}
61
61
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(c!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:c}),this.applyModelChange(c),{stopReason:"end_turn"}):s==="mode"?(c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"}):s==="agent"?(c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:c}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[]};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(!e)throw K(new Error("/hydra agent requires an agent id"),I.InvalidParams);if(e===this.agentId)throw K(new Error(`already on agent ${e}`),I.InvalidParams);if(!this.spawnReplacementAgent)throw K(new Error("agent switching not configured for this session"),I.InternalError);let t=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await t({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.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(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw K(new Error("agent restart not configured for this session"),I.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw K(new Error("session is closing"),I.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let u=(c.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let g=Be(u.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let g=u.status,m=u.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${g}`})}}if(s.length===0)return"";let i=[],o;for(let c of s)o&&o.speaker===c.speaker?o.text+=c.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:c.speaker,text:c.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,d,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
62
- `)}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,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t}}}}),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 i=new St(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Ne,Ne)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=I.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);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let t=this.promptQueue;this.promptQueue=[];for(let r of t){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(()=>Qs(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,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>er.unlink(i).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 t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.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,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.upstreamSessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!Xo(e,r),o=i?ia(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw K(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=oa(s);return new Promise((i,o)=>{let a=!1,d=[],c=0,f,u={addClient:m};this.inFlightPermissions.add(u);let l=this.sessionId,p=h=>{a||(a=!0,this.inFlightPermissions.delete(u),h())},g=h=>h?.code===I.MethodNotFound;function m(h){if(a)return;let y=h.connection.request("session/request_permission",s);d.push({client:h}),c++,y.then(k=>{c--,p(()=>{let S=aa({toolCallId:r,result:k,resolver:h});for(let A of d)A.client.clientId!==h.clientId&&A.client.connection.notify("session/update",{sessionId:l,update:S}).catch(()=>{});i(k)})}).catch(k=>{if(c--,g(k)||(f=k),c===0&&!a){let S=f??K(new Error("no client handled permission request"),I.PermissionDenied);p(()=>o(S))}})}for(let h of t)m(h)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:He(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},f=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:f}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ke(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Be(e.prompt).replace(/\s+$/,""),s=!t.includes(`
62
+ `)}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,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t}}}}),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 i=new St(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Ne,Ne)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=I.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);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let t=this.promptQueue;this.promptQueue=[];for(let r of t){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(()=>Qs(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,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>er.unlink(i).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 t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.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,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.upstreamSessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!Xo(e,r),o=i?ia(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw K(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=oa(s);return new Promise((i,o)=>{let a=!1,d=[],c=0,f,u={addClient:m};this.inFlightPermissions.add(u);let l=this.sessionId,p=h=>{a||(a=!0,this.inFlightPermissions.delete(u),h())},g=h=>h?.code===I.MethodNotFound;function m(h){if(a)return;let y=h.connection.request("session/request_permission",s);d.push({client:h}),c++,y.then(A=>{c--,p(()=>{let S=aa({toolCallId:r,result:A,resolver:h});for(let k of d)k.client.clientId!==h.clientId&&k.client.connection.notify("session/update",{sessionId:l,update:S}).catch(()=>{});i(A)})}).catch(A=>{if(c--,g(A)||(f=A),c===0&&!a){let S=f??K(new Error("no client handled permission request"),I.PermissionDenied);p(()=>o(S))}})}for(let h of t)m(h)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:He(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},f=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:f}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ke(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Be(e.prompt).replace(/\s+$/,""),s=!t.includes(`
63
63
  `)&&t.startsWith("/")?t.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(t):s==="/model"?i=await this.handleModelCommand(t):i=await this.handleSlashCommand(t,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}let r;try{r=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(i){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),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function K(n,e){return n.code=e,n}var Ko=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function Xo(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Ko.has(s)}function Zo(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function ea(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function ta(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Ue(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Xe(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function na(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function sa(n,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&n.chunks.push(r.text)}function ra(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function ia(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:He()}}}function kn(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function oa(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function aa(n){let e=da(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=ca(n.resolver),t}function da(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function ca(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Be(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Sn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Gs(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
64
64
  ${s.join(`
65
65
  `)}`}function An(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}import*as De from"fs/promises";import*as Ol from"path";import{customAlphabet as fa}from"nanoid";import{z as x}from"zod";import{z as re}from"zod";var Ze=re.object({goal:re.string().optional(),outcome:re.string().optional(),files_touched:re.array(re.string()).optional(),tools_used:re.array(re.string()).optional(),rejected_approaches:re.array(re.string()).optional(),open_threads:re.array(re.string()).optional()}),ua=200,xn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
@@ -88,7 +88,7 @@ ${xn}`:xn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type
88
88
  `)){if(u.length===0)continue;let l;try{l=JSON.parse(u)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let p=l;typeof p.method=="string"&&typeof p.recordedAt=="number"&&o.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=o.length>this.maxEntries?o.slice(-this.maxEntries):o;if(!s)return a;let d=new Map,c=async u=>{let l=d.get(u);if(l!==void 0)return l;let p=await yt(e,u);return d.set(u,p),p},f=[];for(let u of a)f.push(await vr(u,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(nt.test(e))return this.enqueue(e,async()=>{try{await Y.unlink(w.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await hs(e);try{await Y.rmdir(w.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};import{promises as Ir}from"fs";import*as br from"path";async function Sr(n,e){await Ir.mkdir(br.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await Ir.writeFile(n,t.length>0?t.join(`
89
89
  `)+`
90
90
  `:"")}import{z as F}from"zod";var Ja=F.object({method:F.string(),params:F.unknown(),recordedAt:F.number()}),za=F.object({sessionId:F.string(),lineageId:F.string(),upstreamSessionId:F.string().optional(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),synopsis:Ze.optional(),summarizedThroughEntry:F.number().int().nonnegative().optional(),currentModel:F.string().optional(),currentMode:F.string().optional(),currentUsage:En.optional(),agentCommands:F.array(Mn).optional(),agentModes:F.array(Rn).optional(),interactive:F.boolean().optional(),originatingClient:Pn.optional(),priority:F.number().int().nonnegative().optional(),createdAt:F.string(),updatedAt:F.string()}),Wa=F.object({version:F.literal(1),exportedAt:F.string(),exportedFrom:F.object({hydraVersion:F.string(),machine:F.string(),hydraHost:F.string().optional()}),session:za,history:F.array(Ja),promptHistory:F.array(F.string()).optional(),toolBlobs:F.record(F.string()).optional()});function st(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function kr(n){return Wa.parse(n)}var Ar=900*1e3,Va="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Pt=Qa(Va,16),ot=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>pe.spawn(i)),this.store=s??new At,this.tombstones=r.tombstones??new xt,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Et({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 Rt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,persistTitle:async(i,o)=>{let a=this.get(i);if(a){await a.retitle(o);return}await this.persistTitle(i,o)},persistSynopsis:(i,o,a)=>this.persistSynopsis(i,o,a),logger:this.logger,npmRegistry:this.npmRegistry}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=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 Oe(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let r={...t.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Pt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}t.agentCapabilities=r}let s=new xe({cwd:e.cwd,agentId:e.agentId,agent:t.agent,upstreamSessionId:t.upstreamSessionId,agentMeta:t.agentMeta,agentCapabilities:t.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:t.initialModel,currentMode:t.initialMode,agentModes:t.initialModes,agentModels:t.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=I.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=I.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await se(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});o=m.agentCapabilities,i.authMethods=Tt(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ce(m,i)}let a;try{let m=Xa(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===I.AuthRequired)throw await i.kill().catch(()=>{}),Ce(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
91
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Er(a??{}),c=e.agentModes??Cr(Rr(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let f=await Pr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=xr(a??{}),l=Cr(Mr(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(l?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Tr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new xe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:f,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:l,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Pr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Tr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new xe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await Me.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Te(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=I.AgentNotInstalled,p}let s=await se(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:_t.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}})}catch(p){throw await r.kill().catch(()=>{}),Ce(p,r)}if(r.authMethods=Tt(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let f=w.sessionsDir(),u=[],l=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){l+=1;continue}if(Ga(p.cwd,f)){l+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!sr(m,p.updatedAt)){l+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ge}${Pt()}`,y=new Date().toISOString(),k=p.updatedAt??y,S={sessionId:h,lineageId:et(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:k,updatedAt:k};p.title!==void 0&&(S.title=p.title);let A=Tn(S);await this.store.write(A),u.push({version:1,...A})}return{synced:u,skipped:l}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let f={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(f.title=c.title),typeof c.updatedAt=="string"&&(f.updatedAt=c.updatedAt),t.push(f)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let s=await se(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}}),o=i.agentCapabilities;r.authMethods=Tt(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=xr(a),f=Mr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=je(u,f),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,u,m)&&(c=u);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=f.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let l=Rr(a),p=Er(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:f.length>0?f:void 0,initialModes:l.length>0?l:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Ce(i,r)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let d=new Error(`agent ${e} not found in registry`);throw d.code=I.AgentNotInstalled,d}let i=await se(r,[],{npmRegistry:this.npmRegistry}),o=t??Te(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});a.authMethods=Tt(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ce(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.AgentNotInstalled,s}return se(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=Le({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(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:$r(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Ya(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return yt(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Ka(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forwardedEnv:t.forwardedEnv}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Be(r.update.prompt),o=An(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ge))return;let t=ge+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=I.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,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 getOne(e){let t=this.sessions.get(e);if(t){let a=await rt(t.sessionId),d=Le({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"live",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await rt(s.sessionId),i=Le(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=f=>e.includeNonInteractive?!0:f===!0,i=[...this.sessions.values()].filter(f=>!e.cwd||f.cwd===e.cwd),o=await Promise.all(i.map(f=>rt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=Le({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let g=l.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(f=>{throw this.logger?.warn(`session list: store.list() failed: ${f?.message??String(f)}`),f})).filter(f=>!s.has(f.sessionId)&&(!e.cwd||f.cwd===e.cwd)),c=await Promise.all(d.map(f=>rt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=Le(u,l.hasContent);if(!r(p))continue;let g=l.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((f,u)=>f.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=et(),f={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=f}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await _r(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of yr(o)){let f=await gs(e,c);f&&(d[c]=f.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=I.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ge}${Pt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=I.SessionNotFound,g}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let m=new Error(`agent ${r} not found in registry`);throw m.code=I.AgentNotInstalled,m}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=kn(o,t.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw g.code=I.InvalidParams,g}d=t.forkAt}else{let g=ed(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await _r(e),u={...s,lineageId:et(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},l=st({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:G,machine:_t.hostname()}),p=`${ge}${Pt()}`;return await this.writeImportedRecord({sessionId:p,bundle:l,cwd:t.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[i,o]of Object.entries(e.bundle.toolBlobs))await ms(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Me.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Sr(w.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,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let t=await this.store.read(e);if(!t)return!1;if(t.upstreamSessionId){let s=await rt(e),r=Le(t,s.hasContent);await this.tombstones.add({agentId:t.agentId,upstreamSessionId:t.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:t.updatedAt,cwd:t.cwd,title:t.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 setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}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 t of e){let s=await Ws(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ar),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ar/1e3}s)`),await Ke(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Ke(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function Ga(n,e){if(typeof n!="string"||n.length===0)return!1;let t=it.resolve(n),s=it.resolve(e);return t===s||t.startsWith(s+it.sep)}function Ya(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(f=>{let u={id:f.id};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let u={modelId:f.modelId};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModels;return Tn({sessionId:n.sessionId,lineageId:e?.lineageId??et(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:$r(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function $r(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Ka(n){return n?{...n}:void 0}function Xa(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function $t(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Za(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function xr(n){return $t(n,{nestedKey:"models",configId:"model",fromObject:e=>le(e.currentModelId)??le(e.currentModel)??le(e.modelId)??le(e.model),fromConfig:e=>le(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==I.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=I.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function Tt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function le(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Za(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Cr(n){return n.length>0?n:void 0}function Mr(n){return $t(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ue(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ue(e.options);return t.length>0?t:void 0}})??[]}function Rr(n){return $t(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Xe(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Xe(e.options);return t.length>0?t:void 0}})??[]}function Er(n){return $t(n,{nestedKey:"modes",configId:"mode",fromObject:e=>le(e.currentModeId)??le(e.currentMode)??le(e.modeId)??le(e.mode),fromConfig:e=>le(e.currentValue)})}async function Pr(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Tr(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}function ed(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function _r(n){try{let e=await Me.readFile(w.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
91
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Er(a??{}),c=e.agentModes??Cr(Rr(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let f=await Pr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=xr(a??{}),l=Cr(Mr(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(l?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Tr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new xe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:f,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:l,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Pr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Tr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new xe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await Me.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Te(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=I.AgentNotInstalled,p}let s=await se(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:_t.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}})}catch(p){throw await r.kill().catch(()=>{}),Ce(p,r)}if(r.authMethods=Tt(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let f=w.sessionsDir(),u=[],l=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){l+=1;continue}if(Ga(p.cwd,f)){l+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!sr(m,p.updatedAt)){l+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ge}${Pt()}`,y=new Date().toISOString(),A=p.updatedAt??y,S={sessionId:h,lineageId:et(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:A,updatedAt:A};p.title!==void 0&&(S.title=p.title);let k=Tn(S);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:l}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let f={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(f.title=c.title),typeof c.updatedAt=="string"&&(f.updatedAt=c.updatedAt),t.push(f)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let s=await se(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}}),o=i.agentCapabilities;r.authMethods=Tt(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=xr(a),f=Mr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=je(u,f),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,u,m)&&(c=u);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=f.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let l=Rr(a),p=Er(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:f.length>0?f:void 0,initialModes:l.length>0?l:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Ce(i,r)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let d=new Error(`agent ${e} not found in registry`);throw d.code=I.AgentNotInstalled,d}let i=await se(r,[],{npmRegistry:this.npmRegistry}),o=t??Te(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});a.authMethods=Tt(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ce(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.AgentNotInstalled,s}return se(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=Le({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(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:$r(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Ya(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return yt(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Ka(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forwardedEnv:t.forwardedEnv}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Be(r.update.prompt),o=An(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ge))return;let t=ge+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=I.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,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 getOne(e){let t=this.sessions.get(e);if(t){let a=await rt(t.sessionId),d=Le({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"live",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await rt(s.sessionId),i=Le(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=f=>e.includeNonInteractive?!0:f===!0,i=[...this.sessions.values()].filter(f=>!e.cwd||f.cwd===e.cwd),o=await Promise.all(i.map(f=>rt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=Le({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let g=l.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(f=>{throw this.logger?.warn(`session list: store.list() failed: ${f?.message??String(f)}`),f})).filter(f=>!s.has(f.sessionId)&&(!e.cwd||f.cwd===e.cwd)),c=await Promise.all(d.map(f=>rt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=Le(u,l.hasContent);if(!r(p))continue;let g=l.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((f,u)=>f.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=et(),f={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=f}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await _r(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of yr(o)){let f=await gs(e,c);f&&(d[c]=f.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=I.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ge}${Pt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let g=new Error(`source session not found: ${e}`);throw g.code=I.SessionNotFound,g}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let m=new Error(`agent ${r} not found in registry`);throw m.code=I.AgentNotInstalled,m}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=kn(o,t.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw g.code=I.InvalidParams,g}d=t.forkAt}else{let g=ed(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await _r(e),u={...s,lineageId:et(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},l=st({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:G,machine:_t.hostname()}),p=`${ge}${Pt()}`;return await this.writeImportedRecord({sessionId:p,bundle:l,cwd:t.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[i,o]of Object.entries(e.bundle.toolBlobs))await ms(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Me.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Sr(w.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,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let t=await this.store.read(e);if(!t)return!1;if(t.upstreamSessionId){let s=await rt(e),r=Le(t,s.hasContent);await this.tombstones.add({agentId:t.agentId,upstreamSessionId:t.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:t.updatedAt,cwd:t.cwd,title:t.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 setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}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 t of e){let s=await Ws(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ar),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ar/1e3}s)`),await Ke(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Ke(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function Ga(n,e){if(typeof n!="string"||n.length===0)return!1;let t=it.resolve(n),s=it.resolve(e);return t===s||t.startsWith(s+it.sep)}function Ya(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(f=>{let u={id:f.id};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let u={modelId:f.modelId};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModels;return Tn({sessionId:n.sessionId,lineageId:e?.lineageId??et(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:$r(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function $r(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Ka(n){return n?{...n}:void 0}function Xa(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function $t(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Za(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function xr(n){return $t(n,{nestedKey:"models",configId:"model",fromObject:e=>le(e.currentModelId)??le(e.currentModel)??le(e.modelId)??le(e.model),fromConfig:e=>le(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==I.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=I.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function Tt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function le(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Za(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Cr(n){return n.length>0?n:void 0}function Mr(n){return $t(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ue(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ue(e.options);return t.length>0?t:void 0}})??[]}function Rr(n){return $t(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Xe(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Xe(e.options);return t.length>0?t:void 0}})??[]}function Er(n){return $t(n,{nestedKey:"modes",configId:"mode",fromObject:e=>le(e.currentModeId)??le(e.currentMode)??le(e.modeId)??le(e.mode),fromConfig:e=>le(e.currentValue)})}async function Pr(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Tr(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}function ed(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function _r(n){try{let e=await Me.readFile(w.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
92
92
  `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function rt(n){try{let e=await Me.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Le(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Mt?!1:e?!0:void 0}import{spawn as td}from"child_process";import*as Je from"fs";import*as be from"fs/promises";import*as Fr from"path";var Ft=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var nd=1e3,sd=6e4,jn=3e3,qe=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??nd,this.restartCapMs=r.restartCapMs??sd;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await be.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 t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},jn);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw at(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw at(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw at(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw at(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw at(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},jn);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Ft(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await be.readdir(this.adapter.paths.dir())}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.endsWith(".pid"))continue;let s=Fr.join(this.adapter.paths.dir(),t),r;try{let i=await be.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Hn(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+jn;for(;Date.now()<i&&Hn(r);)await new Promise(o=>setTimeout(o,50));if(Hn(r))try{process.kill(r,"SIGKILL")}catch{}}await be.unlink(s).catch(()=>{})}}spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=Je.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
93
93
  `);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,...f]=i;if(c===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
94
94
  `),o.end();return}let u=[...f,...r.args],l;try{l=td(c,u,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){o.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
@@ -107,6 +107,6 @@ ${xn}`:xn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type
107
107
  `))n.push(`> ${Re(f)}`);n.push(""),n.push("**Assistant:**"),n.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let f=c.text.split(`
108
108
  `);for(let u of f)n.push(`> _${Re(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let f=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Zd(f.status)} ${Xd(f)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let f of c.entries){let u=f.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${Re(f.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Re(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Re(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Kd(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Xd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Re(n.title)}${t}`}function Zd(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function Re(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qn(n){return n.toLocaleString("en-US")}function ri(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function ec(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let f of s){let u=f.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(f)}o?i="AND":a&&(i="OR");let c=d.map(f=>tc(f)).filter(f=>f.term.length>0);return{operator:i,terms:c}}function tc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:ii(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:ii(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function ii(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function nc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var sc=5,rc=200,oi=30;async function ci(n,e,t={}){let s=ec(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??sc,i=t.maxSessions??rc,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],f=!1;for(let u of d){if(c.length>=i){f=!0;break}let l=await n.loadHistory(u.sessionId).catch(()=>[]),p=ic(l,s,r);if(p.snippets.length===0)continue;let g={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(g.title=u.title),c.push(g)}return{query:e,truncated:f,results:c}}function ic(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=oc(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function oc(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=ac(a).filter(c=>nc(t,c.kind));for(let c of d){let f=c.text.toLowerCase(),u=f.indexOf(r);if(u===-1)continue;let l=0;for(;u!==-1;)l++,u=f.indexOf(r,u+r.length);if(i+=l,o.length<s){let p=f.indexOf(r),g={kind:c.kind,text:fc(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(g.toolName=c.toolName),o.push(g)}}}return{totalMatches:i,snippets:o}}function ac(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Wt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ee(s.text):Wt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(uc(s))return[];let i=Wt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=lc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return dc(s);default:return[]}}function dc(n){let e=ai(n,"name"),t=ai(n,"title"),s=[];if(t!==void 0){let a=L(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=L(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=di(r);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=di(i);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=cc(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function cc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=L(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=L(s);if(r.length>0)return r}}return null}function uc(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function Wt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ee(e.text):""}function lc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Wt(t);s.length>0&&e.push(s)}return e.join("")}function ai(n,e){let t=n[e];return typeof t=="string"?t:void 0}function di(n){try{return JSON.stringify(n)}catch{return""}}function fc(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-oi),d=Math.min(s.length,o+i.length+oi),c=a>0?"\u2026":"",f=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${f}`}function ui(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!ri(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function fi(n,e,t){n.get("/v1/sessions",async s=>{let r=s.query,i=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:i})}}),n.get("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.getOne(o);return a||(r.code(404).send({error:"session not found"}),r)}),n.post("/v1/sessions/search",async(s,r)=>{let i=s.body??{},o=typeof i.q=="string"?i.q:"";if(o.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(i.sessionIds)?i.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await ci(e,o,{sessionIds:a})}),n.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Te(i.cwd??t.cwd),a=i.agentId??t.agentId;try{let d=await e.create({cwd:o,agentId:a,mcpServers:i.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),n.post("/v1/sessions/collect",async(s,r)=>{let i=s.body??{},o=typeof i.maxAgeDays=="number"&&i.maxAgeDays>0?i.maxAgeDays*24*60*60*1e3:0,a=typeof i.limit=="number"&&i.limit>0?i.limit:1e3,d=i.selection==="explicit"||i.selection==="unpromoted"?i.selection:"unpromoted";try{let c=await Un({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),n.post("/v1/sessions/:id/kill",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);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=f=>li.join(ft.tmpdir(),`hydra-acp-stdin-${f}.log`));try{return a.openStream(c)}catch(f){return r.code(409).send({error:f.message}),r}}),n.post("/v1/sessions/:id/stdin",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",f=d.eof===!0;try{return a.streamWrite(c,f)}catch(u){return r.code(409).send({error:u.message}),r}}),n.patch("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{};if(a.priority!==void 0){let c=a.priority,f;if(c===null||c===0)f=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)f=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,f)){r.code(404).send({error:"session not found"});return}r.code(204).send();return}if(a.regen===!0){if(!(e.get(o)!==void 0||await e.hasRecord(o))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(o),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(o,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.delete("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.get("/v1/sessions/:id/export",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.query?.tools,d=a==="references"?"references":gr(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let f=st({record:c.record,history:d==="summary"?mr(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:G,machine:ft.hostname(),hydraHost:ui(t)}),u=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${u}.hydra"`),r.code(200).send(f)}),n.get("/v1/sessions/:id/diff",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=s.query??{},c=d.fold==="true"||d.fold==="1",f=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(l=>l.trim()).filter(l=>l.length>0)):void 0,u=ti(a.history);f&&(u=u.filter(l=>f.has(l.path))),c&&(u=u.map(l=>({...l,hunks:ni(l.hunks)}))),r.code(200).send(u)}),n.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let i=s.params,o=await e.resolveCanonicalId(i.id)??i.id,a=await e.loadToolBlob(o,i.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)}),n.get("/v1/sessions/:id/transcript",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=st({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:G,machine:ft.hostname(),hydraHost:ui(t)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(si(d))}),n.post("/v1/sessions/:id/fork",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,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=Te(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}if(a.title!==void 0){if(typeof a.title!="string"){r.code(400).send({error:"title must be a string"});return}d.title=a.title}try{let c=await e.forkSession(o,d);r.code(201).send(c)}catch(c){let f=c;if(f.code===I.SessionNotFound){r.code(404).send({error:f.message});return}if(f.code===I.InvalidParams||f.code===I.AgentNotInstalled){r.code(400).send({error:f.message});return}r.code(500).send({error:f.message})}}),n.post("/v1/sessions/import",async(s,r)=>{let i=s.body??{};if(i.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let o;if(i.cwd!==void 0){if(typeof i.cwd!="string"||i.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}o=i.cwd}let a;try{a=kr(i.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:i.replace===!0,...o!==void 0?{cwd:o}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===I.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),n.get("/v1/sessions/:id/history",async(s,r)=>{let i=s.params.id,o=s.query,a=o?.follow==="1"||o?.follow==="true",d=await e.resolveCanonicalId(i)??i,c=e.get(d),f,u,l=!1,p=1e4,g=[];if(c){a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(l?r.raw.write(JSON.stringify(h)+`
109
109
  `):(g.push(h),g.length>p&&g.shift()))})),s.raw.on("close",()=>{u?.(),r.raw.writableEnded||r.raw.end()});try{f=await c.getHistorySnapshot()}catch(h){throw u?.(),h}}else{let h=await e.getHistory(d);if(h===void 0)return r.code(404).send({error:"session not found"}),r;f=h}r.raw.setHeader("Content-Type","application/x-ndjson"),r.raw.setHeader("Cache-Control","no-cache"),r.raw.statusCode=200;let m=new Set;for(let h of f??[]){r.raw.write(JSON.stringify(h)+`
110
- `);let y=h;typeof y.recordedAt=="number"&&m.add(String(y.recordedAt))}for(;g.length>0;){let h=g.splice(0,g.length);for(let y of h){let k=y,S=typeof k.recordedAt=="number"?String(k.recordedAt):"";S&&m.has(S)||r.raw.write(JSON.stringify(y)+`
111
- `)}}return l=!0,u||r.raw.end(),r})}function pi(n,e,t,s={}){n.get("/v1/agents",async()=>Oe(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await se(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===I.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function gi(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var pc=/^[A-Za-z0-9._-]+$/;function Qt(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=gc(a);if("error"in d){o.code(400).send({error:d.error});return}try{let c=t.register(d.config);o.code(201).send(c)}catch(c){pt(o,c)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){pt(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){pt(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){pt(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){pt(o,d)}})}function pt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function gc(n){let e=n.name;if(typeof e!="string"||!pc.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function mi(n,e){Qt(n,"extension",e)}function hi(n,e){Qt(n,"transformer",e)}function yi(n,e){n.get("/v1/config",async()=>e)}import{z as We}from"zod";import*as ze from"fs/promises";import*as wi from"path";import{randomBytes as Gp,scrypt as mc,timingSafeEqual as hc}from"crypto";import{promisify as yc}from"util";var wc=yc(mc);function vi(){return wi.join(w.home(),"password-hash")}var vc=128*1024*1024;async function Ii(){try{return(await ze.readFile(vi(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function bi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ze.readFile(vi(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await wc(n,o,a.length,{N:s,r,p:i,maxmem:vc});return d.length!==a.length?!1:hc(d,a)}var Ic=We.object({password:We.string().min(1),label:We.string().min(1).max(256).optional(),ttlSec:We.number().int().positive().optional()}),bc=We.object({id:We.string().optional()}).optional();function Si(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Sc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Ic.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Ii())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await bi(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=bc.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function Sc(n){return n.ip||"unknown"}import{nanoid as Gn}from"nanoid";function Jn(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as Ai}from"crypto";import*as xi from"os";function _(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Mc(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function ie(n,e,t){let s=n.get(e);if(!s)throw _(I.SessionNotFound,t??`session ${e} not found`);return s}async function zn(n,e){let t=Mi(n),s;try{s=await n.manager.resurrect({...e,mcpServers:t?.descriptors})}catch(r){throw t!==void 0&&t.abandon(r instanceof Error?r:void 0),r}return t!==void 0&&t.bindToSession(s),$c(s,n),s}function Ci(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Wr({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Jn(t),a=new Ae(o),d={clientId:`hydra_client_${Gn(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,l)=>{if(d.attached.get(u)?.readonly)throw _(I.PermissionDenied,`${l} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let l=Rs.parse(u??{});l.clientInfo?.name&&(d.clientInfo={name:l.clientInfo.name,...l.clientInfo.version!==void 0?{version:l.clientInfo.version}:{}});let p=l.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),_c()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},g=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(m=>m!==void 0):[];return u.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let p=l??{},g=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let k={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(k.outputSchema=y.outputSchema),k}).filter(h=>h!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,g,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let l=u??{},p=Array.isArray(l.intercepts)?l.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let g=e.transformers.resolveChain([i.name])[0];if(g)for(let m of e.manager.liveSessions())m.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.method=="string"?l.method:void 0,m=l.envelope,h=l.route;if(!p||!g)throw _(-32602,"emit_message requires sessionId and method");let y=ie(e.manager,p),k=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(k)return y.dischargeClaim(k,m),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,g,m)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,g,m)};throw _(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw _(-32602,"hydra-acp/session/request_permission requires sessionId");return ie(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>Pc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let l=u??{},p=typeof l.agentId=="string"?l.agentId:e.defaultAgent,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,h=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,k=y&&typeof y.title=="string"?y.title:void 0;if(!g&&m){let N=e.manager.get(m);N&&(g=N.cwd)}if(!g)throw _(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let S=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:m,interactive:S,transformChain:[],title:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw _(I.InvalidParams,"fork_session requires sessionId");let p=typeof l.forkAt=="string"?l.forkAt:void 0,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...m!==void 0?{agentId:m}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw _(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.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 _(I.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0,g=l.until==="idle"?"idle":"turn_complete",m=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw _(-32602,"await_child requires childSessionId");let h=ie(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let A=[],N=[],H=0,X=!1,J,R,P=!1,j=()=>{P||(P=!0,clearTimeout(B),J?.(),R?.(),y(X?{entries:A,truncated:!0}:{entries:A}))};J=h.onBroadcast(q=>{let D=Mc(q);for(A.push(q),N.push(D),H+=D;A.length>0&&(A.length>1e3||H>1048576);)A.shift(),H-=N.shift()??0,X=!0;g==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&j()});let B=setTimeout(j,m);typeof B.unref=="function"&&B.unref(),R=h.onClose(()=>j())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!p)throw _(-32602,"close_child_session requires childSessionId");let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let l=u??{},p=typeof l.token=="string"?l.token:void 0,g=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let l=u??{};if(typeof l.sessionId!="string"||typeof l.hash!="string")throw _(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,g=await e.manager.loadToolBlob(p,l.hash);if(g===null)throw _(I.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async u=>Rc(u,e)),a.onRequest("session/new",async u=>{let l=Es.parse(u),p=Ye(u?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(R=>typeof R=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,k=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Ai(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let P={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};k=[...l.mcpServers??[],P]}let S=Mi(e);S!==void 0&&(k=[...k??[],...S.descriptors]);let A;try{A=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:k,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:ki(a),transformChain:m,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{}})}catch(R){throw y!==void 0&&y.abandon(R instanceof Error?R:void 0),S!==void 0&&S.abandon(R instanceof Error?R:void 0),R}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let R=h,P=e.mcpTokenRegistry;y.complete(A),A.onClose(()=>{P.unbind(R)})}S!==void 0&&S.bindToSession(A);let N,H;try{N=Vt(a,A,d),{entries:H}=await A.attach(N,"full")}catch(R){throw await A.close({deleteRecord:!1}).catch(()=>{}),R}d.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of H){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let X=Wn(A),J=Qn(A);return{sessionId:A.sessionId,...X?{modes:X}:{},...J?{models:J}:{},configOptions:A.buildConfigOptions(),_meta:Vn(e.manager,A,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let l=Ts.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=Ye(l._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!m} readonly=${h}`);let k=m?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(k);if(!S&&h){let P=await e.manager.loadFromDisk(k);if(!P)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);let j=await e.manager.loadHistory(k),B=l.clientId??`cli_${Gn(8)}`;d.attached.set(P.hydraSessionId,{sessionId:P.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${P.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${j.length}`);for(let q of j)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:P.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:j.length,_meta:Tc(P)}}if(!S){let P=await e.manager.loadFromDisk(k),j=P;if(m&&(j={...P,hydraSessionId:l.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!j)throw _(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let B=j.originatingClient?j:{...j,originatingClient:d.clientInfo},q=y!==void 0?{...B,forwardedEnv:y}:B;S=await zn(e,{...q,onInstallProgress:ki(a)})}let A=Vt(a,S,d,l.clientInfo,l.clientId),N=g.replayMode==="drip",{entries:H,appliedPolicy:X}=await S.attach(A,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:N,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(S.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${X} replayed=${H.length} readonly=${h}${N?" replayMode=drip":""}`),N){let P=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,j=750;(async()=>{let B=null;for(let q of H){let D=typeof q.recordedAt=="number"?q.recordedAt:null;if(B!==null&&D!==null){let he=Math.min(j,Math.max(0,(D-B)/P));he>0&&await new Promise(Zt=>setTimeout(Zt,he))}D!==null&&(B=D);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let P=0;P<H.length&&!a.isClosed();P++){let j=H[P],B=a.notify(j.method,j.params).catch(()=>{});(P+1)%200===0&&await B}S.replayPendingPermissions(A);let J=Wn(S),R=Qn(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:X,replayed:H.length,...J?{modes:J}:{},...R?{models:R}:{},configOptions:S.buildConfigOptions(),_meta:Vn(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=_s.parse(u),p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"client not attached to that session");let g=e.manager.get(l.sessionId);return g?.detach(p.clientId),d.attached.delete(l.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[Ge]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=$s.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==Mt).map(Fs)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw _(I.InternalError,"agent registry unavailable");return Oe(e.registry)}),a.onRequest("session/prompt",async u=>{let l=Os.parse(u);c(l.sessionId,"session/prompt");let p=d.attached.get(l.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${l.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),_(I.SessionNotFound,"not attached to session");let g=e.manager.get(l.sessionId);if(!g){let m=await e.manager.loadFromDisk(l.sessionId);if(!m)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),g=await zn(e,m);let h=Vt(a,g,d,void 0,p.clientId);await g.attach(h,"none")}return g.prompt(p.clientId,l)});let f=u=>{let l;try{l=It.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(l.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${l.sessionId}`);return}let g=e.manager.get(l.sessionId);g&&g.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${l.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=It.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=js.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),ie(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=It.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),ie(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Hs.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),ie(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Bs.parse(u);c(l.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"not attached to session");return ie(e.manager,l.sessionId).amendPrompt(p.clientId,l)}),a.onRequest("session/load",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw _(I.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let A=await e.manager.loadFromDisk(g);if(!A)throw _(I.SessionNotFound,`session ${p} not found in memory or on disk`);m=await zn(e,A)}let h=Vt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let A of y){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}m.replayPendingPermissions(h);let k=Wn(m),S=Qn(m);return{sessionId:m.sessionId,...k?{modes:k}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:Vn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=Ec(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),_(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:g}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:g});return p.session.applyModelChange(g),m}),a.onRequest("session/set_mode",async u=>{let l=u,p=l?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!l||typeof l.sessionId!="string")throw _(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof l.modeId!="string")throw _(I.InvalidParams,"session/set_mode requires string modeId");let g=ie(e.manager,l.sessionId),m=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(l.modeId),m}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>_(I.InvalidParams,y),g=l?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!l||typeof l.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof l.configId!="string")throw p("session/set_config_option requires string configId");if(typeof l.value!="string")throw p("session/set_config_option requires string value");let m=ie(e.manager,l.sessionId),h=m.buildConfigOptions().find(y=>y.id===l.configId);if(!h)throw p(`unknown configId ${JSON.stringify(l.configId)} for this session`);if(!h.options.some(y=>y.value===l.value))throw p(`value ${JSON.stringify(l.value)} is not valid for configId ${JSON.stringify(l.configId)}`);switch(l.configId){case"model":{l.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),m.applyModelChange(l.value);break}case"mode":{l.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),m.applyModeChange(l.value);break}case"agent":{l.value!==m.agentId&&await m.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,l)=>{if(!l.startsWith("session/")||u===null||typeof u!="object")throw _(I.MethodNotFound,`Method not found: ${l}`);let p=u.sessionId;if(typeof p!="string")throw _(I.MethodNotFound,`Method not found: ${l}`);return c(p,l),ie(e.manager,p).forwardRequest(l,u)})})}async function Rc(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw _(I.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let l=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let d=a.authMethods??[],c=d.find(l=>l.id===s);if(!c){let l=d.map(p=>p.id);throw _(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(p=>JSON.stringify(p)).join(", ")}]`)}let f=c._meta?.type;if((c.type??(f==="agent"||f==="terminal"?f:"agent"))==="terminal"){let l=c._meta?.args,p=[];if(l!==void 0){if(!Array.isArray(l))throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${l===null?"null":typeof l}`);for(let y of l)if(typeof y!="string")throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(y)}`);p=l}let g=await e.manager.planSpawnForAgent(a.agentId),m={};for(let[y,k]of Object.entries(process.env))typeof k=="string"&&(m[y]=k);Object.assign(m,g.env);let h=xi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g.command,args:[...g.args,...p],env:m,cwd:h}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Ce(l,a)}}function ki(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Us,t).catch(()=>{})}}function Wn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Qn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function Ec(n,e){if(!n||typeof n!="object")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:I.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=je(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:I.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function Pc(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw _(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw _(I.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw _(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ie(t.manager,r).addTransformer(i),{ok:!0}}function Tc(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[Ge]:vt(e,t)}}function Vn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot()};return Ve(e.agentMeta,vt(s,r))}function _c(){return{protocolVersion:1,agentInfo:{name:"hydra",version:G},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Ve(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function $c(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Vt(n,e,t,s,r){return{clientId:r??`cli_${Gn(8)}`,connection:n,clientInfo:s}}function Mi(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Ai(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var Gt=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Fc}from"crypto";import{McpServer as Oc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Nc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Q}from"zod";var Ri="Bearer ";function Yt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Ri))return;let t=e.slice(Ri.length).trim();return t.length>0?t:void 0}function jc(n){let e=new Oc({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:Q.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);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:Q.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);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:Q.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:Q.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Q.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:Q.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Q.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo(),o={outcome:r,writeCursor:i.writeCursor,closed:i.closed};return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent:o}}),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:Q.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Q.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Q.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Q.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Q.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Q.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Q.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Q.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Q.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s),i=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:i}}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}),e}var Hc=1e4;function Ei(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=jc(a),f=new Nc({sessionIdGenerator:()=>Fc()});await c.connect(f);let u={server:c,transport:f};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await f.close()}catch{}try{await c.close()}catch{}}),f}async function r(o,a){let d=Yt(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let f;if(c.session!==void 0)f=c.session;else{let l,p=new Promise(m=>{l=setTimeout(()=>m(void 0),Hc)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),g===void 0){a.code(503).send({error:"session not ready"});return}f=g}let u=await s(d,f);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var Kt=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as zc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Wc}from"crypto";import{Server as Bc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Uc,ListToolsRequestSchema as Dc}from"@modelcontextprotocol/sdk/types.js";var Lc=6e4;function Pi(n,e,t,s={}){let r=s.invokeTimeoutMs??Lc,i=typeof t=="function"?async()=>t():async()=>t,o=new Bc({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),a=new Map(e.tools.map(d=>[d.name,d]));return o.setRequestHandler(Dc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Uc,async d=>{let c=d.params.name;if(!a.has(c))return Xt(`unknown tool: ${c}`);try{let f=await i(),u=await qc(e.connection,n,c,d.params.arguments??{},f,r);return Jc(u,c)}catch(f){return Xt(f instanceof Error?f.message:String(f))}}),o}async function qc(n,e,t,s,r,i){let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Error(`extension timeout after ${i}ms`)),i)});try{return await Promise.race([n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function Jc(n,e){if(n===null||typeof n!="object")return Xt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Xt(`extension ${e} omitted content array`)}function Xt(n){return{content:[{type:"text",text:n}],isError:!0}}var Qc=1e4;function Ti(n,e,t,s={}){let r=new Map;async function i(f){try{await f.transport.close()}catch{}try{await f.server.close()}catch{}}function o(f){for(let u of r.values()){let l=u.get(f);l!==void 0&&(u.delete(f),i(l))}}t.onChange(f=>{o(f)});async function a(f,u){let l=r.get(f);l===void 0&&(l=new Map,r.set(f,l),e.addDisposer(f,async()=>{let k=r.get(f);if(k!==void 0){r.delete(f);for(let S of k.values())await i(S)}}));let p=l.get(u);if(p!==void 0)return p.transport;let g=t.lookup(u);if(g===void 0)return;let h=Pi(u,g,async()=>{let k=e.lookup(f);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let S,A=new Promise(H=>{S=setTimeout(()=>H(void 0),Qc)}),N=await Promise.race([k.sessionReady.catch(()=>{}),A]);if(S!==void 0&&clearTimeout(S),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new zc({sessionIdGenerator:()=>Wc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Yt(f);if(l===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){u.code(404).send({error:"unknown mcp token"});return}let g=f.params.name,m=await a(l,g);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await m.handleRequest(f.raw,u.raw,f.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.get("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.delete("/mcp/:name",c,async(f,u)=>{await d(f,u)})}async function Kc(n,e){Zc(n);let t=n.daemon.tls?{key:await Se.readFile(n.daemon.tls.key),cert:await Se.readFile(n.daemon.tls.cert)}:void 0;await Se.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await Xc(n.daemon.logLevel),i=Vc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Gc,{options:{handleProtocols:Zn}}),un(E=>{i.log.info(E)}),pn(E=>{i.log.info(E)});let o=await Bt.load(),a=new Jt,d=new qt,c=new Lt([new Ut(e),new Dt(o),d]),f=zr({validator:c});i.addHook("onRequest",async(E,fe)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await f(E,fe)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new Qe(n,{onFetched:()=>{Or(p,y)}});Bn(E=>i.log.info(E));let g={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},m=E=>pe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});ps(n.compressToolContent);let h=new jt,y=new ot(p,m,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,synopsisOnClose:n.synopsisOnClose,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),k=new Ot(os(n),void 0,{tokenRegistry:d}),S=new Nt(as(n),void 0,{tokenRegistry:d});gi(i,G,Hr(n)),fi(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),pi(i,p,y,{npmRegistry:n.npmRegistry}),mi(i,k),hi(i,S),yi(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},synopsisOnClose:n.synopsisOnClose,defaultTransformers:[...n.defaultTransformers]}),Si(i,{store:o,rateLimiter:a});let A=new Gt,N=new Kt;Ei(i,A),Ti(i,A,N);let H,X=()=>{if(H!==void 0)return H;let E=i.server.address(),fe=E&&typeof E=="object"?E.port:n.daemon.port;return H=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${fe}`,H};Ci(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,fe)=>k.reportVersion(E,fe),onTransformerVersion:(E,fe)=>S.reportVersion(E,fe),transformers:S,extensionCommands:h,mcpTokenRegistry:A,extensionMcp:N,getDaemonOrigin:X,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let J=i.server.address(),R=J&&typeof J=="object"?J.port:n.daemon.port;await Se.mkdir(w.home(),{recursive:!0}),await Se.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:R,startedAt:new Date().toISOString()})+`
112
- `,{encoding:"utf8",mode:384});let P=n.daemon.tls?"https":"http",j=n.daemon.tls?"wss":"ws",B={daemonUrl:`${P}://${n.daemon.host}:${R}`,daemonHost:n.daemon.host,daemonPort:R,serviceToken:e,daemonWsUrl:`${j}://${n.daemon.host}:${R}/acp`,hydraHome:w.home()};k.setContext(B),S.setContext(B),await k.start(),await S.start(),y.resurrectPendingQueues().catch(E=>{i.log.warn(`queue replay scan failed: ${E.message}`)});let q=n.daemon.agentSyncIntervalMinutes*60*1e3,D=q>0?Nr({registry:p,manager:y,intervalMs:q,logger:g}):void 0,he=n.daemon.sessionGcIntervalMinutes*60*1e3,Zt=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Yn=he>0?jr({manager:y,intervalMs:he,maxAgeMs:Zt,logger:g}):void 0;return{app:i,manager:y,registry:p,extensions:k,transformers:S,mcpTokenRegistry:A,extensionMcp:N,processRegistry:d,shutdown:async()=>{Yn&&Yn(),D&&D(),clearInterval(u),clearInterval(l);let E=async(fe,Kn)=>{try{await Kn()}catch(en){i.log.warn(`shutdown step ${fe} failed: ${en instanceof Error?en.message:String(en)}`)}};await E("sessionTokenStore.flush",()=>o.flush()),await E("extensions.stop",()=>k.stop()),await E("transformers.stop",()=>S.stop()),await E("manager.closeAll",()=>y.closeAll()),await E("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await E("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await E("manager.flushMetaWrites",()=>y.flushMetaWrites()),await E("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),un(null),pn(null),Bn(null),await E("app.close",()=>i.close());try{$i.unlinkSync(w.pidFile())}catch{}await E("fileStream.flushSync",()=>r.flushSync())}}}async function Xc(n){let e=await Yc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=_i.destination(2);return{stream:_i.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Zc(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{pe as AgentInstance,Ae as JsonRpcConnection,Qe as Registry,xe as Session,ot as SessionManager,eo as defaultConfig,ji as ensureServiceToken,gt as generateServiceToken,cs as loadConfig,Ni as loadServiceToken,yn as ndjsonStreamFromStdio,w as paths,se as planSpawn,Kc as startDaemon,Zi as writeConfig,Jn as wsToMessageStream};
110
+ `);let y=h;typeof y.recordedAt=="number"&&m.add(String(y.recordedAt))}for(;g.length>0;){let h=g.splice(0,g.length);for(let y of h){let A=y,S=typeof A.recordedAt=="number"?String(A.recordedAt):"";S&&m.has(S)||r.raw.write(JSON.stringify(y)+`
111
+ `)}}return l=!0,u||r.raw.end(),r})}function pi(n,e,t,s={}){n.get("/v1/agents",async()=>Oe(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await se(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===I.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function gi(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var pc=/^[A-Za-z0-9._-]+$/;function Qt(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=gc(a);if("error"in d){o.code(400).send({error:d.error});return}try{let c=t.register(d.config);o.code(201).send(c)}catch(c){pt(o,c)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){pt(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){pt(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){pt(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){pt(o,d)}})}function pt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function gc(n){let e=n.name;if(typeof e!="string"||!pc.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function mi(n,e){Qt(n,"extension",e)}function hi(n,e){Qt(n,"transformer",e)}function yi(n,e){n.get("/v1/config",async()=>e)}import{z as We}from"zod";import*as ze from"fs/promises";import*as wi from"path";import{randomBytes as Gp,scrypt as mc,timingSafeEqual as hc}from"crypto";import{promisify as yc}from"util";var wc=yc(mc);function vi(){return wi.join(w.home(),"password-hash")}var vc=128*1024*1024;async function Ii(){try{return(await ze.readFile(vi(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function bi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ze.readFile(vi(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await wc(n,o,a.length,{N:s,r,p:i,maxmem:vc});return d.length!==a.length?!1:hc(d,a)}var Ic=We.object({password:We.string().min(1),label:We.string().min(1).max(256).optional(),ttlSec:We.number().int().positive().optional()}),bc=We.object({id:We.string().optional()}).optional();function Si(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Sc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Ic.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Ii())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await bi(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=bc.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function Sc(n){return n.ip||"unknown"}import{nanoid as Gn}from"nanoid";function Jn(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as Ai}from"crypto";import*as xi from"os";function _(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Mc(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function ie(n,e,t){let s=n.get(e);if(!s)throw _(I.SessionNotFound,t??`session ${e} not found`);return s}async function zn(n,e){let t=Mi(n),s;try{s=await n.manager.resurrect({...e,mcpServers:t?.descriptors})}catch(r){throw t!==void 0&&t.abandon(r instanceof Error?r:void 0),r}return t!==void 0&&t.bindToSession(s),$c(s,n),s}function Ci(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Wr({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Jn(t),a=new Ae(o),d={clientId:`hydra_client_${Gn(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,l)=>{if(d.attached.get(u)?.readonly)throw _(I.PermissionDenied,`${l} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let l=Rs.parse(u??{});l.clientInfo?.name&&(d.clientInfo={name:l.clientInfo.name,...l.clientInfo.version!==void 0?{version:l.clientInfo.version}:{}});let p=l.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),_c()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},g=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(m=>m!==void 0):[];return u.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let p=l??{},g=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let A={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(A.outputSchema=y.outputSchema),A}).filter(h=>h!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,g,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let l=u??{},p=Array.isArray(l.intercepts)?l.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let g=e.transformers.resolveChain([i.name])[0];if(g)for(let m of e.manager.liveSessions())m.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.method=="string"?l.method:void 0,m=l.envelope,h=l.route;if(!p||!g)throw _(-32602,"emit_message requires sessionId and method");let y=ie(e.manager,p),A=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(A)return y.dischargeClaim(A,m),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,g,m)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,g,m)};throw _(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw _(-32602,"hydra-acp/session/request_permission requires sessionId");return ie(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>Pc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let l=u??{},p=typeof l.agentId=="string"?l.agentId:e.defaultAgent,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,h=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,A=y&&typeof y.title=="string"?y.title:void 0,S=y&&typeof y.model=="string"?y.model:void 0;if(!g&&m){let N=e.manager.get(m);N&&(g=N.cwd)}if(!g)throw _(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let k=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:m,interactive:k,transformChain:[],title:A,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw _(I.InvalidParams,"fork_session requires sessionId");let p=typeof l.forkAt=="string"?l.forkAt:void 0,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...m!==void 0?{agentId:m}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw _(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.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 _(I.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0,g=l.until==="idle"?"idle":"turn_complete",m=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw _(-32602,"await_child requires childSessionId");let h=ie(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let k=[],j=[],N=0,X=!1,J,R,P=!1,H=()=>{P||(P=!0,clearTimeout(B),J?.(),R?.(),y(X?{entries:k,truncated:!0}:{entries:k}))};J=h.onBroadcast(q=>{let D=Mc(q);for(k.push(q),j.push(D),N+=D;k.length>0&&(k.length>1e3||N>1048576);)k.shift(),N-=j.shift()??0,X=!0;g==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&H()});let B=setTimeout(H,m);typeof B.unref=="function"&&B.unref(),R=h.onClose(()=>H())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!p)throw _(-32602,"close_child_session requires childSessionId");let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let l=u??{},p=typeof l.token=="string"?l.token:void 0,g=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let l=u??{};if(typeof l.sessionId!="string"||typeof l.hash!="string")throw _(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,g=await e.manager.loadToolBlob(p,l.hash);if(g===null)throw _(I.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async u=>Rc(u,e)),a.onRequest("session/new",async u=>{let l=Es.parse(u),p=Ye(u?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(R=>typeof R=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,A=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Ai(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let P={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};A=[...l.mcpServers??[],P]}let S=Mi(e);S!==void 0&&(A=[...A??[],...S.descriptors]);let k;try{k=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:A,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:ki(a),transformChain:m,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{}})}catch(R){throw y!==void 0&&y.abandon(R instanceof Error?R:void 0),S!==void 0&&S.abandon(R instanceof Error?R:void 0),R}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let R=h,P=e.mcpTokenRegistry;y.complete(k),k.onClose(()=>{P.unbind(R)})}S!==void 0&&S.bindToSession(k);let j,N;try{j=Vt(a,k,d),{entries:N}=await k.attach(j,"full")}catch(R){throw await k.close({deleteRecord:!1}).catch(()=>{}),R}d.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:j.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of N){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let X=Wn(k),J=Qn(k);return{sessionId:k.sessionId,...X?{modes:X}:{},...J?{models:J}:{},configOptions:k.buildConfigOptions(),_meta:Vn(e.manager,k,{clientId:j.clientId})}}),a.onRequest("session/attach",async u=>{let l=Ts.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=Ye(l._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!m} readonly=${h}`);let A=m?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(A);if(!S&&h){let P=await e.manager.loadFromDisk(A);if(!P)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);let H=await e.manager.loadHistory(A),B=l.clientId??`cli_${Gn(8)}`;d.attached.set(P.hydraSessionId,{sessionId:P.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${P.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${H.length}`);for(let q of H)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:P.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:H.length,_meta:Tc(P)}}if(!S){let P=await e.manager.loadFromDisk(A),H=P;if(m&&(H={...P,hydraSessionId:l.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!H)throw _(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let B=H.originatingClient?H:{...H,originatingClient:d.clientInfo},q=y!==void 0?{...B,forwardedEnv:y}:B;S=await zn(e,{...q,onInstallProgress:ki(a)})}let k=Vt(a,S,d,l.clientInfo,l.clientId),j=g.replayMode==="drip",{entries:N,appliedPolicy:X}=await S.attach(k,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:j,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:k.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(S.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${k.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${X} replayed=${N.length} readonly=${h}${j?" replayMode=drip":""}`),j){let P=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,H=750;(async()=>{let B=null;for(let q of N){let D=typeof q.recordedAt=="number"?q.recordedAt:null;if(B!==null&&D!==null){let he=Math.min(H,Math.max(0,(D-B)/P));he>0&&await new Promise(Zt=>setTimeout(Zt,he))}D!==null&&(B=D);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let P=0;P<N.length&&!a.isClosed();P++){let H=N[P],B=a.notify(H.method,H.params).catch(()=>{});(P+1)%200===0&&await B}S.replayPendingPermissions(k);let J=Wn(S),R=Qn(S);return{sessionId:S.sessionId,clientId:k.clientId,connectedClients:S.connectedClients(k.clientId),historyPolicy:X,replayed:N.length,...J?{modes:J}:{},...R?{models:R}:{},configOptions:S.buildConfigOptions(),_meta:Vn(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=_s.parse(u),p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"client not attached to that session");let g=e.manager.get(l.sessionId);return g?.detach(p.clientId),d.attached.delete(l.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[Ge]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=$s.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==Mt).map(Fs)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw _(I.InternalError,"agent registry unavailable");return Oe(e.registry)}),a.onRequest("session/prompt",async u=>{let l=Os.parse(u);c(l.sessionId,"session/prompt");let p=d.attached.get(l.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${l.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),_(I.SessionNotFound,"not attached to session");let g=e.manager.get(l.sessionId);if(!g){let m=await e.manager.loadFromDisk(l.sessionId);if(!m)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),g=await zn(e,m);let h=Vt(a,g,d,void 0,p.clientId);await g.attach(h,"none")}return g.prompt(p.clientId,l)});let f=u=>{let l;try{l=It.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(l.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${l.sessionId}`);return}let g=e.manager.get(l.sessionId);g&&g.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${l.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=It.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=js.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),ie(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=It.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),ie(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Hs.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),ie(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Bs.parse(u);c(l.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"not attached to session");return ie(e.manager,l.sessionId).amendPrompt(p.clientId,l)}),a.onRequest("session/load",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw _(I.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let k=await e.manager.loadFromDisk(g);if(!k)throw _(I.SessionNotFound,`session ${p} not found in memory or on disk`);m=await zn(e,k)}let h=Vt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let k of y){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(h);let A=Wn(m),S=Qn(m);return{sessionId:m.sessionId,...A?{modes:A}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:Vn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=Ec(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),_(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:g}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:g});return p.session.applyModelChange(g),m}),a.onRequest("session/set_mode",async u=>{let l=u,p=l?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!l||typeof l.sessionId!="string")throw _(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof l.modeId!="string")throw _(I.InvalidParams,"session/set_mode requires string modeId");let g=ie(e.manager,l.sessionId),m=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(l.modeId),m}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>_(I.InvalidParams,y),g=l?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!l||typeof l.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof l.configId!="string")throw p("session/set_config_option requires string configId");if(typeof l.value!="string")throw p("session/set_config_option requires string value");let m=ie(e.manager,l.sessionId),h=m.buildConfigOptions().find(y=>y.id===l.configId);if(!h)throw p(`unknown configId ${JSON.stringify(l.configId)} for this session`);if(!h.options.some(y=>y.value===l.value))throw p(`value ${JSON.stringify(l.value)} is not valid for configId ${JSON.stringify(l.configId)}`);switch(l.configId){case"model":{l.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),m.applyModelChange(l.value);break}case"mode":{l.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),m.applyModeChange(l.value);break}case"agent":{l.value!==m.agentId&&await m.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,l)=>{if(!l.startsWith("session/")||u===null||typeof u!="object")throw _(I.MethodNotFound,`Method not found: ${l}`);let p=u.sessionId;if(typeof p!="string")throw _(I.MethodNotFound,`Method not found: ${l}`);return c(p,l),ie(e.manager,p).forwardRequest(l,u)})})}async function Rc(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw _(I.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let l=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let d=a.authMethods??[],c=d.find(l=>l.id===s);if(!c){let l=d.map(p=>p.id);throw _(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(p=>JSON.stringify(p)).join(", ")}]`)}let f=c._meta?.type;if((c.type??(f==="agent"||f==="terminal"?f:"agent"))==="terminal"){let l=c._meta?.args,p=[];if(l!==void 0){if(!Array.isArray(l))throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${l===null?"null":typeof l}`);for(let y of l)if(typeof y!="string")throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(y)}`);p=l}let g=await e.manager.planSpawnForAgent(a.agentId),m={};for(let[y,A]of Object.entries(process.env))typeof A=="string"&&(m[y]=A);Object.assign(m,g.env);let h=xi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g.command,args:[...g.args,...p],env:m,cwd:h}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Ce(l,a)}}function ki(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Us,t).catch(()=>{})}}function Wn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Qn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function Ec(n,e){if(!n||typeof n!="object")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:I.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=je(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:I.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function Pc(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw _(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw _(I.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw _(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ie(t.manager,r).addTransformer(i),{ok:!0}}function Tc(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[Ge]:vt(e,t)}}function Vn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot()};return Ve(e.agentMeta,vt(s,r))}function _c(){return{protocolVersion:1,agentInfo:{name:"hydra",version:G},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Ve(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function $c(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Vt(n,e,t,s,r){return{clientId:r??`cli_${Gn(8)}`,connection:n,clientInfo:s}}function Mi(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Ai(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var Gt=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Fc}from"crypto";import{McpServer as Oc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Nc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Q}from"zod";var Ri="Bearer ";function Yt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Ri))return;let t=e.slice(Ri.length).trim();return t.length>0?t:void 0}function jc(n){let e=new Oc({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:Q.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);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:Q.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);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:Q.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:Q.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Q.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:Q.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Q.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo(),o={outcome:r,writeCursor:i.writeCursor,closed:i.closed};return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent:o}}),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:Q.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Q.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Q.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Q.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Q.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Q.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Q.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Q.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Q.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s),i=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:i}}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}),e}var Hc=1e4;function Ei(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=jc(a),f=new Nc({sessionIdGenerator:()=>Fc()});await c.connect(f);let u={server:c,transport:f};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await f.close()}catch{}try{await c.close()}catch{}}),f}async function r(o,a){let d=Yt(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let f;if(c.session!==void 0)f=c.session;else{let l,p=new Promise(m=>{l=setTimeout(()=>m(void 0),Hc)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),g===void 0){a.code(503).send({error:"session not ready"});return}f=g}let u=await s(d,f);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var Kt=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as zc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Wc}from"crypto";import{Server as Bc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Uc,ListToolsRequestSchema as Dc}from"@modelcontextprotocol/sdk/types.js";var Lc=6e4;function Pi(n,e,t,s={}){let r=s.invokeTimeoutMs??Lc,i=typeof t=="function"?async()=>t():async()=>t,o=new Bc({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),a=new Map(e.tools.map(d=>[d.name,d]));return o.setRequestHandler(Dc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Uc,async d=>{let c=d.params.name;if(!a.has(c))return Xt(`unknown tool: ${c}`);try{let f=await i(),u=await qc(e.connection,n,c,d.params.arguments??{},f,r);return Jc(u,c)}catch(f){return Xt(f instanceof Error?f.message:String(f))}}),o}async function qc(n,e,t,s,r,i){let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Error(`extension timeout after ${i}ms`)),i)});try{return await Promise.race([n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function Jc(n,e){if(n===null||typeof n!="object")return Xt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Xt(`extension ${e} omitted content array`)}function Xt(n){return{content:[{type:"text",text:n}],isError:!0}}var Qc=1e4;function Ti(n,e,t,s={}){let r=new Map;async function i(f){try{await f.transport.close()}catch{}try{await f.server.close()}catch{}}function o(f){for(let u of r.values()){let l=u.get(f);l!==void 0&&(u.delete(f),i(l))}}t.onChange(f=>{o(f)});async function a(f,u){let l=r.get(f);l===void 0&&(l=new Map,r.set(f,l),e.addDisposer(f,async()=>{let A=r.get(f);if(A!==void 0){r.delete(f);for(let S of A.values())await i(S)}}));let p=l.get(u);if(p!==void 0)return p.transport;let g=t.lookup(u);if(g===void 0)return;let h=Pi(u,g,async()=>{let A=e.lookup(f);if(A===void 0)throw new Error("mcp token no longer bound");if(A.session!==void 0)return A.session.sessionId;let S,k=new Promise(N=>{S=setTimeout(()=>N(void 0),Qc)}),j=await Promise.race([A.sessionReady.catch(()=>{}),k]);if(S!==void 0&&clearTimeout(S),j===void 0)throw new Error("session not ready");return j.sessionId},s.buildOptions),y=new zc({sessionIdGenerator:()=>Wc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Yt(f);if(l===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){u.code(404).send({error:"unknown mcp token"});return}let g=f.params.name,m=await a(l,g);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await m.handleRequest(f.raw,u.raw,f.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.get("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.delete("/mcp/:name",c,async(f,u)=>{await d(f,u)})}async function Kc(n,e){Zc(n);let t=n.daemon.tls?{key:await Se.readFile(n.daemon.tls.key),cert:await Se.readFile(n.daemon.tls.cert)}:void 0;await Se.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await Xc(n.daemon.logLevel),i=Vc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Gc,{options:{handleProtocols:Zn}}),un(E=>{i.log.info(E)}),pn(E=>{i.log.info(E)});let o=await Bt.load(),a=new Jt,d=new qt,c=new Lt([new Ut(e),new Dt(o),d]),f=zr({validator:c});i.addHook("onRequest",async(E,fe)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await f(E,fe)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new Qe(n,{onFetched:()=>{Or(p,y)}});Bn(E=>i.log.info(E));let g={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},m=E=>pe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});ps(n.compressToolContent);let h=new jt,y=new ot(p,m,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,synopsisOnClose:n.synopsisOnClose,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),A=new Ot(os(n),void 0,{tokenRegistry:d}),S=new Nt(as(n),void 0,{tokenRegistry:d});gi(i,G,Hr(n)),fi(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),pi(i,p,y,{npmRegistry:n.npmRegistry}),mi(i,A),hi(i,S),yi(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},synopsisOnClose:n.synopsisOnClose,defaultTransformers:[...n.defaultTransformers]}),Si(i,{store:o,rateLimiter:a});let k=new Gt,j=new Kt;Ei(i,k),Ti(i,k,j);let N,X=()=>{if(N!==void 0)return N;let E=i.server.address(),fe=E&&typeof E=="object"?E.port:n.daemon.port;return N=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${fe}`,N};Ci(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,fe)=>A.reportVersion(E,fe),onTransformerVersion:(E,fe)=>S.reportVersion(E,fe),transformers:S,extensionCommands:h,mcpTokenRegistry:k,extensionMcp:j,getDaemonOrigin:X,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let J=i.server.address(),R=J&&typeof J=="object"?J.port:n.daemon.port;await Se.mkdir(w.home(),{recursive:!0}),await Se.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:R,startedAt:new Date().toISOString()})+`
112
+ `,{encoding:"utf8",mode:384});let P=n.daemon.tls?"https":"http",H=n.daemon.tls?"wss":"ws",B={daemonUrl:`${P}://${n.daemon.host}:${R}`,daemonHost:n.daemon.host,daemonPort:R,serviceToken:e,daemonWsUrl:`${H}://${n.daemon.host}:${R}/acp`,hydraHome:w.home()};A.setContext(B),S.setContext(B),await A.start(),await S.start(),y.resurrectPendingQueues().catch(E=>{i.log.warn(`queue replay scan failed: ${E.message}`)});let q=n.daemon.agentSyncIntervalMinutes*60*1e3,D=q>0?Nr({registry:p,manager:y,intervalMs:q,logger:g}):void 0,he=n.daemon.sessionGcIntervalMinutes*60*1e3,Zt=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Yn=he>0?jr({manager:y,intervalMs:he,maxAgeMs:Zt,logger:g}):void 0;return{app:i,manager:y,registry:p,extensions:A,transformers:S,mcpTokenRegistry:k,extensionMcp:j,processRegistry:d,shutdown:async()=>{Yn&&Yn(),D&&D(),clearInterval(u),clearInterval(l);let E=async(fe,Kn)=>{try{await Kn()}catch(en){i.log.warn(`shutdown step ${fe} failed: ${en instanceof Error?en.message:String(en)}`)}};await E("sessionTokenStore.flush",()=>o.flush()),await E("extensions.stop",()=>A.stop()),await E("transformers.stop",()=>S.stop()),await E("manager.closeAll",()=>y.closeAll()),await E("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await E("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await E("manager.flushMetaWrites",()=>y.flushMetaWrites()),await E("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),un(null),pn(null),Bn(null),await E("app.close",()=>i.close());try{$i.unlinkSync(w.pidFile())}catch{}await E("fileStream.flushSync",()=>r.flushSync())}}}async function Xc(n){let e=await Yc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=_i.destination(2);return{stream:_i.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Zc(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{pe as AgentInstance,Ae as JsonRpcConnection,Qe as Registry,xe as Session,ot as SessionManager,eo as defaultConfig,ji as ensureServiceToken,gt as generateServiceToken,cs as loadConfig,Ni as loadServiceToken,yn as ndjsonStreamFromStdio,w as paths,se as planSpawn,Kc as startDaemon,Zi as writeConfig,Jn as wsToMessageStream};