@hydra-acp/cli 0.1.165 → 0.1.166
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +18 -18
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -115,11 +115,11 @@ Use empty arrays/strings where a field doesn't apply.`;dy=`Reply with ONLY a JSO
|
|
|
115
115
|
"unresolved_errors": ["errors left open at session end"],
|
|
116
116
|
"tool_state": ["runtime state relevant for recall"]
|
|
117
117
|
}
|
|
118
|
-
Use empty arrays/strings where a field doesn't apply.`});import*as gd from"fs/promises";import*as l4 from"path";import{customAlphabet as dF}from"nanoid";import{z as Z}from"zod";function Vc(){return`${uF}${lF()}`}function wF(n){if(!cy.test(n))throw new Error(`unsafe session id: ${n}`)}function hy(n){let e=new Date().toISOString(),t=n.createdAt??e,r=(n.currentUsage?.cumulativeCost??0)+(n.currentUsage?.costAmount??0),s=n.upstreamGenerations??(n.upstreamSessionId?[{upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,startedAt:t,...r===0?{lifetimeCostAtStart:0}:{}}]:[]);return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,upstreamGenerations:s,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,workspace:n.workspace,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:t,updatedAt:n.updatedAt??e}}var cF,lF,uF,ly,uy,fF,fy,py,pF,hF,mF,gF,yF,cy,yf,my=j(()=>{"use strict";ve();us();qI();gf();cF="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",lF=dF(cF,16),uF="hydra_lineage_";ly=Z.object({name:Z.string(),description:Z.string().optional()}),uy=Z.object({id:Z.string(),name:Z.string().optional(),description:Z.string().optional()}),fF=Z.object({modelId:Z.string(),name:Z.string().optional(),description:Z.string().optional()}),fy=Z.object({used:Z.number().optional(),size:Z.number().optional(),costAmount:Z.number().optional(),costCurrency:Z.string().optional(),cumulativeCost:Z.number().optional()}),py=Z.object({name:Z.string(),version:Z.string().optional()}),pF=Z.object({path:Z.string(),sourceCwd:Z.string(),label:Z.string(),requestedLabel:Z.string().optional(),provider:Z.string(),snapshot:Z.string().optional(),line:Z.string().optional(),vcs:Z.record(Z.string(),Z.string()).optional(),clean:Z.boolean().optional()}),hF=Z.object({previousUpstreamSessionId:Z.string(),previousSummarizedThroughEntry:Z.number().int().nonnegative().optional(),runId:Z.string().optional()}),mF=Z.enum(["compaction","agent-swap","workspace-enter","workspace-leave","rollback","restart"]),gF=Z.object({upstreamSessionId:Z.string(),agentId:Z.string(),reason:mF.optional(),runId:Z.string().optional(),startedAt:Z.string().optional(),endedAt:Z.string().optional(),cost:Z.number().nonnegative().optional(),lifetimeCostAtStart:Z.number().nonnegative().optional(),usedAtStart:Z.number().nonnegative().optional(),usedAtEnd:Z.number().nonnegative().optional(),inferred:Z.boolean().optional()}),yF=Z.object({version:Z.literal(1),sessionId:Z.string(),lineageId:Z.string().optional(),upstreamSessionId:Z.string(),importedFromSessionId:Z.string().optional(),importedFromUpstreamSessionId:Z.string().optional(),importedFromMachine:Z.string().optional(),agentId:Z.string(),cwd:Z.string(),title:Z.string().optional(),synopsis:Gc.optional(),compactionState:zI.optional(),rollbackBreadcrumb:hF.optional(),upstreamGenerations:Z.array(gF).optional(),summarizedThroughEntry:Z.number().int().nonnegative().optional(),agentArgs:Z.array(Z.string()).optional(),currentModel:Z.string().optional(),currentMode:Z.string().optional(),currentUsage:fy.optional(),agentCommands:Z.array(ly).optional(),agentModes:Z.array(uy).optional(),agentModels:Z.array(fF).optional(),pendingHistorySync:Z.boolean().optional(),pendingAgentSwap:Z.string().optional(),parentSessionId:Z.string().optional(),forkedFromSessionId:Z.string().optional(),forkedFromMessageId:Z.string().optional(),forkSynthesisState:Z.enum(["running","failed"]).optional(),originatingClient:py.optional(),interactive:Z.boolean().optional(),priority:Z.number().int().nonnegative().optional(),forwardedEnv:Z.record(Z.string(),Z.string()).optional(),workspace:pF.optional(),attentionFlags:jI.default([]).optional(),extensionState:Z.record(Z.string(),Z.record(Z.string(),Z.unknown())).default({}).optional(),createdAt:Z.string(),updatedAt:Z.string()}),cy=/^[A-Za-z0-9_-]+$/;yf=class{async write(e){wF(e.sessionId);let t={version:1,...e};await mn(D.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!cy.test(e))return;let t=await Wt(D.sessionFile(e));if(t!==void 0)try{return yF.parse(t)}catch{return}}async delete(e){if(cy.test(e)){try{await gd.unlink(D.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await gd.rmdir(D.sessionDir(e))}catch(t){let r=t;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let r of t)if(r.lineageId===e)return r}async list(){let e;try{e=await gd.readdir(D.sessionsDir())}catch(s){if(s.code==="ENOENT")return[];throw s}let t=await Promise.all(e.map(s=>this.read(s).catch(()=>{}))),r=[];for(let s of t)s&&r.push(s);return r}}});import{fileURLToPath as _F}from"url";import*as Xc from"path";import*as Mf from"fs";function $F(){try{let n=Xc.dirname(_F(import.meta.url));for(let e=0;e<8;e+=1){let t=Xc.join(n,"package.json");if(Mf.existsSync(t)){let s=JSON.parse(Mf.readFileSync(t,"utf8"));if(typeof s.version=="string"&&s.version.length>0&&(typeof s.name!="string"||s.name.includes("hydra-acp")))return s.version}let r=Xc.dirname(n);if(r===n)break;n=r}}catch{}return"0.0.0"}var He,_i,er=j(()=>{"use strict";He=$F(),_i="hydra-acp-cat"});function Iy(n){let e=new Map;for(let t of yx(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,r])=>({name:t,count:r})).sort((t,r)=>r.count-t.count||t.name.localeCompare(r.name))}function hx(n){return Iy(n).map(e=>e.name)}function xy(n){let e=new Map;for(let t of yx(n).values())for(let r of t.paths){let s=e.get(r);s===void 0&&(s=new Map,e.set(r,s)),s.set(t.toolName,(s.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,r])=>{let s=[...r.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=s.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:s}}).sort((t,r)=>r.count-t.count||t.path.localeCompare(r.path))}function mx(n){return xy(n).map(e=>e.path)}function gx(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function yx(n){let e=new Map,t=0;for(let r of n){let o=r.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:fx(o),paths:new Set},e.set(d,c)):c.toolName=fx(o);for(let l of px(o.rawInput,o.locations))c.paths.add(l);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let d of px(o.rawInput,o.locations))a.paths.add(d)}return e}function fx(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function px(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n;typeof r.file_path=="string"?t.add(r.file_path):typeof r.path=="string"&&t.add(r.path);let s=r.edits;if(Array.isArray(s)){for(let o of s)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}for(let r of Wg(e))t.add(r);return t}var Cy=j(()=>{"use strict";Wc()});import{promises as Zc}from"fs";import*as My from"path";async function el(n){let e;try{e=await Zc.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return
|
|
118
|
+
Use empty arrays/strings where a field doesn't apply.`});import*as gd from"fs/promises";import*as l4 from"path";import{customAlphabet as dF}from"nanoid";import{z as Z}from"zod";function Vc(){return`${uF}${lF()}`}function wF(n){if(!cy.test(n))throw new Error(`unsafe session id: ${n}`)}function hy(n){let e=new Date().toISOString(),t=n.createdAt??e,r=(n.currentUsage?.cumulativeCost??0)+(n.currentUsage?.costAmount??0),s=n.upstreamGenerations??(n.upstreamSessionId?[{upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,startedAt:t,...r===0?{lifetimeCostAtStart:0}:{}}]:[]);return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,upstreamGenerations:s,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,workspace:n.workspace,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:t,updatedAt:n.updatedAt??e}}var cF,lF,uF,ly,uy,fF,fy,py,pF,hF,mF,gF,yF,cy,yf,my=j(()=>{"use strict";ve();us();qI();gf();cF="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",lF=dF(cF,16),uF="hydra_lineage_";ly=Z.object({name:Z.string(),description:Z.string().optional()}),uy=Z.object({id:Z.string(),name:Z.string().optional(),description:Z.string().optional()}),fF=Z.object({modelId:Z.string(),name:Z.string().optional(),description:Z.string().optional()}),fy=Z.object({used:Z.number().optional(),size:Z.number().optional(),costAmount:Z.number().optional(),costCurrency:Z.string().optional(),cumulativeCost:Z.number().optional()}),py=Z.object({name:Z.string(),version:Z.string().optional()}),pF=Z.object({path:Z.string(),sourceCwd:Z.string(),label:Z.string(),requestedLabel:Z.string().optional(),provider:Z.string(),snapshot:Z.string().optional(),line:Z.string().optional(),vcs:Z.record(Z.string(),Z.string()).optional(),clean:Z.boolean().optional()}),hF=Z.object({previousUpstreamSessionId:Z.string(),previousSummarizedThroughEntry:Z.number().int().nonnegative().optional(),runId:Z.string().optional()}),mF=Z.enum(["compaction","agent-swap","workspace-enter","workspace-leave","rollback","restart"]),gF=Z.object({upstreamSessionId:Z.string(),agentId:Z.string(),reason:mF.optional(),runId:Z.string().optional(),startedAt:Z.string().optional(),endedAt:Z.string().optional(),cost:Z.number().nonnegative().optional(),lifetimeCostAtStart:Z.number().nonnegative().optional(),usedAtStart:Z.number().nonnegative().optional(),usedAtEnd:Z.number().nonnegative().optional(),inferred:Z.boolean().optional()}),yF=Z.object({version:Z.literal(1),sessionId:Z.string(),lineageId:Z.string().optional(),upstreamSessionId:Z.string(),importedFromSessionId:Z.string().optional(),importedFromUpstreamSessionId:Z.string().optional(),importedFromMachine:Z.string().optional(),agentId:Z.string(),cwd:Z.string(),title:Z.string().optional(),synopsis:Gc.optional(),compactionState:zI.optional(),rollbackBreadcrumb:hF.optional(),upstreamGenerations:Z.array(gF).optional(),summarizedThroughEntry:Z.number().int().nonnegative().optional(),agentArgs:Z.array(Z.string()).optional(),currentModel:Z.string().optional(),currentMode:Z.string().optional(),currentUsage:fy.optional(),agentCommands:Z.array(ly).optional(),agentModes:Z.array(uy).optional(),agentModels:Z.array(fF).optional(),pendingHistorySync:Z.boolean().optional(),pendingAgentSwap:Z.string().optional(),parentSessionId:Z.string().optional(),forkedFromSessionId:Z.string().optional(),forkedFromMessageId:Z.string().optional(),forkSynthesisState:Z.enum(["running","failed"]).optional(),originatingClient:py.optional(),interactive:Z.boolean().optional(),priority:Z.number().int().nonnegative().optional(),forwardedEnv:Z.record(Z.string(),Z.string()).optional(),workspace:pF.optional(),attentionFlags:jI.default([]).optional(),extensionState:Z.record(Z.string(),Z.record(Z.string(),Z.unknown())).default({}).optional(),createdAt:Z.string(),updatedAt:Z.string()}),cy=/^[A-Za-z0-9_-]+$/;yf=class{async write(e){wF(e.sessionId);let t={version:1,...e};await mn(D.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!cy.test(e))return;let t=await Wt(D.sessionFile(e));if(t!==void 0)try{return yF.parse(t)}catch{return}}async delete(e){if(cy.test(e)){try{await gd.unlink(D.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await gd.rmdir(D.sessionDir(e))}catch(t){let r=t;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let r of t)if(r.lineageId===e)return r}async list(){let e;try{e=await gd.readdir(D.sessionsDir())}catch(s){if(s.code==="ENOENT")return[];throw s}let t=await Promise.all(e.map(s=>this.read(s).catch(()=>{}))),r=[];for(let s of t)s&&r.push(s);return r}}});import{fileURLToPath as _F}from"url";import*as Xc from"path";import*as Mf from"fs";function $F(){try{let n=Xc.dirname(_F(import.meta.url));for(let e=0;e<8;e+=1){let t=Xc.join(n,"package.json");if(Mf.existsSync(t)){let s=JSON.parse(Mf.readFileSync(t,"utf8"));if(typeof s.version=="string"&&s.version.length>0&&(typeof s.name!="string"||s.name.includes("hydra-acp")))return s.version}let r=Xc.dirname(n);if(r===n)break;n=r}}catch{}return"0.0.0"}var He,_i,er=j(()=>{"use strict";He=$F(),_i="hydra-acp-cat"});function Iy(n){let e=new Map;for(let t of yx(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,r])=>({name:t,count:r})).sort((t,r)=>r.count-t.count||t.name.localeCompare(r.name))}function hx(n){return Iy(n).map(e=>e.name)}function xy(n){let e=new Map;for(let t of yx(n).values())for(let r of t.paths){let s=e.get(r);s===void 0&&(s=new Map,e.set(r,s)),s.set(t.toolName,(s.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,r])=>{let s=[...r.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=s.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:s}}).sort((t,r)=>r.count-t.count||t.path.localeCompare(r.path))}function mx(n){return xy(n).map(e=>e.path)}function gx(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function yx(n){let e=new Map,t=0;for(let r of n){let o=r.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:fx(o),paths:new Set},e.set(d,c)):c.toolName=fx(o);for(let l of px(o.rawInput,o.locations))c.paths.add(l);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let d of px(o.rawInput,o.locations))a.paths.add(d)}return e}function fx(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function px(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n;typeof r.file_path=="string"?t.add(r.file_path):typeof r.path=="string"&&t.add(r.path);let s=r.edits;if(Array.isArray(s)){for(let o of s)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}for(let r of Wg(e))t.add(r);return t}var Cy=j(()=>{"use strict";Wc()});import{promises as Zc}from"fs";import*as My from"path";async function el(n){let e;try{e=await Zc.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return rL(e)}function rL(n){let e=[];for(let t of n.split(`
|
|
119
119
|
`))if(t.length!==0)try{let r=JSON.parse(t);typeof r=="string"&&e.push(r)}catch{}return e}function tl(n,e,t=Tx){let r=e.replace(/\n+$/,"");if(r.length===0||n.length>0&&n[n.length-1]===r)return n;let s=n.concat(r);return s.length>t?s.slice(s.length-t):s}function Ex(n,e){return e===null?!1:n>=e}async function $i(n,e){await Zc.mkdir(My.dirname(n),{recursive:!0});let t=e.map(r=>JSON.stringify(r));await Zc.writeFile(n,t.length>0?t.join(`
|
|
120
120
|
`)+`
|
|
121
121
|
`:"")}async function Px(n,e){let t=e.replace(/\n+$/,"");t.length!==0&&(await Zc.mkdir(My.dirname(n),{recursive:!0}),await Zc.appendFile(n,JSON.stringify(t)+`
|
|
122
|
-
`,{encoding:"utf8"}))}function Lf(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(s=>!t.has(s)),...e]}function _y(n,e,t=Tx){if(e.length===0)return n;let r=new Set(n),s=n;for(let o of e){let i=o.replace(/\n+$/,"");i.length!==0&&(r.has(i)||(r.add(i),s=tl(s,i,t)))}return s}var Tx,Nf=j(()=>{"use strict";Tx=500});import{z as it}from"zod";function nl(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 zr(n){return i1.parse(n)}var s1,o1,i1,Oi=j(()=>{"use strict";my();gf();s1=it.object({method:it.string(),params:it.unknown(),recordedAt:it.number()}),o1=it.object({sessionId:it.string(),lineageId:it.string(),upstreamSessionId:it.string().optional(),agentId:it.string(),cwd:it.string(),title:it.string().optional(),synopsis:Gc.optional(),summarizedThroughEntry:it.number().int().nonnegative().optional(),currentModel:it.string().optional(),currentMode:it.string().optional(),currentUsage:fy.optional(),agentCommands:it.array(ly).optional(),agentModes:it.array(uy).optional(),interactive:it.boolean().optional(),originatingClient:py.optional(),priority:it.number().int().nonnegative().optional(),createdAt:it.string(),updatedAt:it.string()}),i1=it.object({version:it.literal(1),exportedAt:it.string(),exportedFrom:it.object({hydraVersion:it.string(),machine:it.string(),hydraHost:it.string().optional()}),session:o1,history:it.array(s1),promptHistory:it.array(it.string()).optional(),toolBlobs:it.record(it.string()).optional()})});function rl(n){if(n&&!(n.costAmount===void 0&&n.cumulativeCost===void 0))return(n.cumulativeCost??0)+(n.costAmount??0)}function Fi(n){if(!n)return;let e={};n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size);let t=rl(n);return t&&(e.costAmount=t),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),e}var wd=j(()=>{"use strict"});import{createHash as x1}from"crypto";function ul(n){if(Array.isArray(n))return n.map(ul);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=ul(n[t]);return e}return n}function _o(n){let e={};for(let[r,s]of Object.entries(n)){let o=Sm(r);if(o.nested){let i={};for(let[a,d]of Object.entries(s??{}))Im(a).reload==="restart"&&(i[a]=d);Object.keys(i).length>0&&(e[r]=i);continue}o.reload==="restart"&&(e[r]=s)}let t=JSON.stringify(ul(e));return x1("sha256").update(t).digest("hex").slice(0,16)}function Wx(n,e){let t=[],r=(s,o)=>JSON.stringify(ul(s))!==JSON.stringify(ul(o));for(let s of Object.keys(e)){let o=Sm(s),i=e[s],a=n[s];if(o.nested){for(let d of Object.keys(i??{})){if(Im(d).reload!=="warn")continue;let c=i[d],l=(a??{})[d];r(l,c)&&t.push(`${s}.${d}`)}continue}o.reload==="warn"&&r(a,i)&&t.push(s)}return t}var Id=j(()=>{"use strict";ot();Cm()});function qy(n){return Math.floor(n/4)}function eC(n){let e=0,t=new Map;for(let r of n){let s=r.params;if(!s||typeof s!="object")continue;let o=s.update;if(!o||typeof o!="object")continue;let i=o;switch(i.sessionUpdate){case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":e+=Ni(i.content);break;case"tool_call":case"tool_call_update":{let a=typeof i.toolCallId=="string"?i.toolCallId:"",d=N1(i),c=t.get(a)??0;d>c&&t.set(a,d);break}default:break}}for(let r of t.values())e+=r;return e}function N1(n){let e=0;return typeof n.title=="string"&&(e+=n.title.length),e+=ep(n.rawInput),e+=Ni(n.content),e+=ep(n.rawOutput),e}function ep(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(typeof n=="number"||typeof n=="boolean")return String(n).length;if(Array.isArray(n)){let e=0;for(let t of n)e+=ep(t);return e}if(typeof n=="object"){let e=n.bytes;if(typeof n.__hydraBlob=="string"&&typeof e=="number")return e;let t=0;for(let r of Object.values(n))t+=ep(r);return t}return 0}function Ni(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(Array.isArray(n)){let t=0;for(let r of n)t+=Ni(r);return t}if(typeof n!="object")return 0;let e=n;return typeof e.__hydraBlob=="string"&&typeof e.bytes=="number"?e.bytes:e.text!==void 0?Ni(e.text):e.type==="diff"?Ni(e.oldText)+Ni(e.newText):e.content!==void 0?Ni(e.content):0}function tC(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e,t;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize,t=!0;else{let s=qy(n.unsummarizedChars),o=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/o,t=!1}if(t&&e>=n.config.hardCeilingFraction)return!0;let r=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&r>=n.config.idleBeforePromptMs}function nC(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var zy=j(()=>{"use strict"});function fl(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var rC=j(()=>{"use strict"});import{posix as B1}from"path";import D1 from"strip-ansi";function Gt(n){return D1(n).replace(H1,"")}function et(n){return Gt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Cs(n,e={}){if(!n||typeof n!="object")return null;let t=n,r=t.sessionUpdate??t.kind;if(typeof r!="string")return null;switch(r){case"agent_message_chunk":return K1(t);case"agent_thought_chunk":case"agent_thought":return G1(t);case"user_message_chunk":return V1(t);case"prompt_received":return J1(t);case"tool_call":return Y1(t,e);case"tool_call_update":return tL(t,e);case"plan":return sL(t);case"current_mode_update":return oL(t);case"_hydra_current_model_update":return iL(t);case"turn_complete":return aL(t);case"_hydra_turn_started":return iC(t,"turn-started");case"_hydra_turn_ended":return iC(t,"turn-ended");case"usage_update":return z1(t);case"available_commands_update":return j1(t);case"_hydra_available_modes_update":return q1(t);case"session_info_update":return W1(t);case"config_option_update":return U1(t);default:return{kind:"unknown",sessionUpdate:r,raw:n}}}function U1(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||typeof s.currentValue!="string"||!Array.isArray(s.options))continue;let o=[];for(let i of s.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:s.id,name:typeof s.name=="string"?s.name:s.id,type:"select",currentValue:s.currentValue,options:o,...typeof s.category=="string"?{category:s.category}:{}})}return{kind:"config-options",options:t}}function W1(n){let e=Lt(n,"title"),t=e!==void 0?et(e):void 0,r=n._meta,s,o;if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(s=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&s===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),s!==void 0&&(i.agentId=s),o!==void 0&&(i.pendingAgentSwap=o),i}function tp(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.name!="string"||r.name.length===0)continue;let s=r.name.startsWith("/")?r.name:`/${r.name}`,o={name:et(s)};typeof r.description=="string"&&(o.description=et(r.description)),e.push(o)}return e}function j1(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:tp(e)}:null}function q1(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||s.id.length===0)continue;let o={id:et(s.id)};typeof s.name=="string"&&(o.name=et(s.name)),typeof s.description=="string"&&(o.description=et(s.description)),t.push(o)}return{kind:"available-modes",modes:t}}function z1(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function K1(n){let e=pl(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:fl(n)}}function G1(n){let e=typeof n.text=="string"?Gt(n.text):pl(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:fl(n)}}function V1(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e["hydra-acp"];if(r&&typeof r=="object"&&!Array.isArray(r)&&r.compatFor==="prompt_received")return null}let t=pl(n.content);return t===null?null:{kind:"user-text",text:t}}function J1(n){let e=dL(n.prompt);return e===null?null:{kind:"user-text",text:e}}function aC(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function sC(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function np(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(s.type!=="diff")continue;let o=sC(s.oldText),i=sC(s.newText);if(o===void 0&&i===void 0)continue;let a=typeof s.path=="string"?s.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t,s=typeof r.file_path=="string"?r.file_path:typeof r.path=="string"?r.path:void 0;if(typeof r.old_string=="string"&&typeof r.new_string=="string")return{...s!==void 0?{path:s}:{},oldText:r.old_string,newText:r.new_string};if(typeof r.content=="string")return{...s!==void 0?{path:s}:{},oldText:"",newText:r.content}}return null}function dC(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:Gt(t)}function Y1(n,e={}){let t=Lt(n,"toolCallId")??Lt(n,"id");if(!t)return null;let r=Lt(n,"title")??Lt(n,"name")??Lt(n,"label")??"tool call",s=Lt(n,"name")??Lt(n,"title");if(aC(s)){let m=dC(n);if(m!==null){let h=Lt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:m};return h!==void 0&&(y.status=h),y}}let o=uC(et(r),n,e),i=Lt(n,"status"),a=Lt(n,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=np(n);c!==null&&(d.editDiff=c);let l=lC(n);l!==void 0&&(d.detail=l);let f=Ky(n);f!==void 0&&(d.detailFull=f);let u=cC(n);u!==void 0&&(d.locations=u);let p=fl(n);return p!==void 0&&(d.workerTaskId=p),d}function cC(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.path!="string"||s.path.length===0)continue;let o={path:s.path};typeof s.line=="number"&&Number.isFinite(s.line)&&s.line>=1&&(o.line=Math.floor(s.line)),t.push(o)}return t.length>0?t:void 0}function lC(n){let e=Ky(n);if(e===void 0)return;let t=et(e),r=n.rawInput;return r&&typeof r.command=="string"?Z1(t,oC):eL(t,oC)}function Ky(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return Gt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let r=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(r!==void 0&&r.length>0)return K(et(r))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let r=t.path;if(typeof r=="string"&&r.length>0)return K(et(r))}}}function X1(n){for(let e of Q1)if(n.startsWith(e))return!0;return!1}function uC(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return K(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let r=e.rawInput;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=[s.file_path,s.filePath,s.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return K(i)}return X1(n)?K(`/${n}`):t.cwd&&t.cwd.length>0?K(B1.resolve(t.cwd,n)):n}function Z1(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function eL(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),r=t.indexOf("/");return r>=0&&r<e/2?`\u2026${t.slice(r)}`:`\u2026${t}`}function tL(n,e={}){let t=Lt(n,"toolCallId")??Lt(n,"id");if(!t)return null;let r=Lt(n,"title"),s=r!==void 0?uC(et(r),n,e):void 0,o=Lt(n,"status"),i=np(n),a=lC(n),d=Gy(n);if(!(s!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let l=Lt(n,"name")??r;if(aC(l)){let h={kind:"exit-plan-mode",toolCallId:t},y=dC(n);return y!==null&&(h.plan=y),o!==void 0&&(h.status=o),h}let f={kind:"tool-call-update",toolCallId:t};s!==void 0&&(f.title=s),a!==void 0&&(f.detail=a);let u=Ky(n);u!==void 0&&(f.detailFull=u);let p=cC(n);if(p!==void 0&&(f.locations=p),d!==void 0&&(f.resultSummary=d),o!==void 0&&(f.status=o),i!==null&&(f.editDiff=i),o==="failed"){let h=nL(n);h!==null&&(f.errorText=h),rL(n,h)&&(f.upstreamInterrupted=!0)}let m=fl(n);return m!==void 0&&(f.workerTaskId=m),f}function Gy(n){if(!n||typeof n!="object")return;let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r=l=>{let f=t[l];return typeof f=="number"&&Number.isFinite(f)?f:void 0},s=(l,f,u=`${f}s`)=>`${l} ${l===1?f:u}`,o=[],i=r("totalMatches");i!==void 0&&o.push(s(i,"match","matches"));let a=r("totalFiles");a!==void 0&&o.push(s(a,"file"));let d=r("referenceCount");d!==void 0&&o.push(s(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let c=r("exitCode");return c!==void 0&&c!==0&&o.push(`exit ${c}`),o.length>0?o.join(", "):void 0}function fC(n){if(!n||typeof n!="object")return[];let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e,r=[];for(let s of["content","stdout","stderr"]){let o=t[s];typeof o=="string"?o.length>0&&r.push(o):o&&typeof o=="object"&&!Array.isArray(o)&&r.push(o)}return r}function nL(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=pl(r.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"&&r.length>0)return Gt(r)}return null}function rL(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.metadata;if(r&&typeof r=="object"&&r.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function sL(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r,o=typeof s.content=="string"?et(s.content):void 0;if(!o)continue;let i={content:o};typeof s.status=="string"&&(i.status=s.status),typeof s.priority=="string"&&(i.priority=s.priority),t.push(i)}return{kind:"plan",entries:t}}function oL(n){let e=Lt(n,"currentModeId")??Lt(n,"currentMode")??Lt(n,"mode");return e?{kind:"mode-changed",mode:et(e)}:null}function iL(n){let e=Lt(n,"currentModel")??Lt(n,"model");if(!e)return null;let t=n.availableModels,r=Array.isArray(t)?t.map(s=>typeof s=="object"&&s!==null?s.modelId:typeof s=="string"?s:void 0).filter(s=>typeof s=="string"&&s.length>0):void 0;return{kind:"model-changed",model:et(e),...r&&r.length>0?{availableModels:r}:{}}}function aL(n){let e=Lt(n,"stopReason"),t=n._meta,r=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,s={kind:"turn-complete"};return e!==void 0&&(s.stopReason=e),r&&(s.amended=!0),s}function iC(n,e){let r=n._meta?.["hydra-acp"],s=r?.unsolicited===!0;if(e==="turn-started"){let i=r?.cause?.label,a={kind:e,unsolicited:s};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:s};return typeof r?.reason=="string"&&(o.reason=r.reason),o}function pl(n){if(typeof n=="string")return Gt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?Gt(e.text):null}function dL(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let r=pl(t);r!==null&&e.push(r)}return e.length===0?null:e.join("")}function Lt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var H1,oC,Q1,$o=j(()=>{"use strict";ve();rC();H1=/[\x00-\x08\x0b-\x1f\x7f]/g;oC=64;Q1=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function xd(n){let e=new Map,t=new Map;for(let s of n){let i=s.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=lL(i);if(c.length===0)continue;let l=c;if(d!==void 0){let f=e.get(d)??[],u=[];for(let p of c)f.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(d,[...f,...u]),l=u}for(let f of l)cL(t,f)}let r=[];for(let[s,o]of t)r.push({path:s,hunks:o.hunks,created:o.created});return r}function Cd(n){let e=[];for(let t of n){let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){r=o;break}if(r===-1){e.push(t);continue}let s=e[r];e.splice(r,1,{oldText:s.oldText,newText:t.newText})}return e}function cL(n,e){let t={oldText:e.oldText,newText:e.newText},r=n.get(e.path);if(r===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}r.hunks.push(t)}function lL(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,f=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||f===void 0||e.push({path:i,oldText:l,newText:f})}if(e.length>0)return e}}let r=n.content;if(Array.isArray(r)){for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let d=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let s=np(n);return s&&s.path&&e.push({path:s.path,oldText:s.oldText,newText:s.newText}),e}var rp=j(()=>{"use strict";$o()});function vL(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,r=[],s;for(;(s=t.exec(e))!==null;)r.push(s[0]);let o="OR",i=!1,a=!1,d=[];for(let l of r){let f=l.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:d.push(l)}i?o="AND":a&&(o="OR");let c=d.map(l=>SL(l)).filter(l=>l.term.length>0);return{operator:o,terms:c}}function SL(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:mC(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let r=/^(prompt|response|tool|edit|edited):([\s\S]*)$/i.exec(n);return r?{scope:mC(r[1]),term:r[2].trim()}:{scope:"all",term:n.trim()}}function mC(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";case"edit":case"edited":return"edit";default:return"all"}}function IL(n,e){return e==="edit"?n==="edit":n==="edit"?!1:n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}function kC(n){return Number.isFinite(n)?Math.max(AL,Math.min(RL,Math.floor(n))):ip}async function vC(n,e,t={}){let r=vL(e);if(r.terms.length===0)return{query:e,truncated:!1,results:[]};let s=t.maxSnippetsPerSession??xL,o=t.maxSessions??CL,i=kC(t.snippetWidth??ip),a=t.sessionIds?new Set(t.sessionIds):null,d=await n.list(),c=a?d.filter(u=>a.has(u.sessionId)):d,l=[],f=!1;for(let u of c){if(l.length>=o){f=!0;break}let p=await n.loadHistory(u.sessionId,{tools:"references"}).catch(()=>[]),m=TL(p,r,s,i,Ad(u));if(m.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:m.totalMatches,snippets:m.snippets};u.title!==void 0&&(h.title=u.title),l.push(h)}return{query:e,truncated:f,results:l}}function Ad(n){let e=n.workspace?.sourceCwd;if(e===void 0||e.length===0||n.cwd.length===0)return;let t=n.cwd.endsWith("/")?n.cwd:n.cwd+"/";return r=>r.startsWith(t)?e.replace(/\/+$/,"")+"/"+r.slice(t.length):r}function TL(n,e,t,r=ip,s){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let o=0,i=[],a=Math.max(1,Math.floor(t/e.terms.length)),d=[];for(let{scope:c,term:l}of e.terms){let f=EL(n,l,c,t,r,s);if(e.operator==="AND"&&f.totalMatches===0)return{totalMatches:0,snippets:[]};o+=f.totalMatches,i.push(...f.snippets.slice(0,a)),d.push(...f.snippets.slice(a))}for(let c of d){if(i.length>=t)break;i.push(c)}return{totalMatches:o,snippets:i.slice(0,t)}}function EL(n,e,t,r,s,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let l of n){let f=PL(l).filter(u=>IL(t,u.kind));for(let u of f){let p=u.text.toLowerCase();if(u.kind==="edit"){let y=o?.(u.text);if(!(gC(u.text,e)||(y!==void 0&&y!==u.text?gC(y,e):!1))||c.has(u.text))continue;if(c.add(u.text),a+=1,d.length<r){let k={kind:"edit",text:u.text,recordedAt:l.recordedAt};u.toolName!==void 0&&(k.toolName=u.toolName),d.push(k)}continue}let m=p.indexOf(i);if(m===-1)continue;let h=0;for(;m!==-1;)h++,m=p.indexOf(i,m+i.length);if(a+=h,d.length<r){let y=p.indexOf(i),w={kind:u.kind,text:NL(u.text,y,i.length,s),recordedAt:l.recordedAt};u.toolName!==void 0&&(w.toolName=u.toolName),d.push(w)}}}return{totalMatches:a,snippets:d}}function PL(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let r=t,s=typeof r.sessionUpdate=="string"?r.sessionUpdate:r.kind;if(typeof s!="string")return[];switch(s){case"agent_message_chunk":{let o=op(r.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof r.text=="string"?Gt(r.text):op(r.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(FL(r))return[];let o=op(r.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=LL(r.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return ML(r);default:return[]}}function ML(n){let e=wC(n,"name"),t=wC(n,"title"),r=[];if(t!==void 0){let a=et(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),r.push(d)}}if(e!==void 0&&e!==t){let a=et(e);a.length>0&&r.push({kind:"tool",toolName:e,text:a})}let s=n.rawInput;if(s&&typeof s=="object"){let a=bC(s);if(a.length>0){let d={kind:"tool-input",text:et(a)};e!==void 0&&(d.toolName=e),r.push(d)}}for(let a of _L(n)){let d={kind:"edit",text:a};e!==void 0&&(d.toolName=e),r.push(d)}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=bC(o);if(a.length>0){let d={kind:"tool-input",text:et(a)};e!==void 0&&(d.toolName=e),r.push(d)}}let i=$L(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),r.push(a)}return r}function _L(n){let e=[],t=new Set,r=i=>{typeof i!="string"||i.length===0||t.has(i)||(t.add(i),e.push(i))},s=n.content;if(Array.isArray(s))for(let i of s){if(!i||typeof i!="object")continue;let a=i;a.type==="diff"&&r(a.path)}let o=n.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o;(i.old_string!==void 0||i.new_string!==void 0||i.content!==void 0||Array.isArray(i.edits))&&r(typeof i.file_path=="string"?i.file_path:i.path)}return e}function gC(n,e){let t=yC(n.toLowerCase()),r=yC(e.toLowerCase());if(r.length===0)return!1;if(r.startsWith("/"))return t===r||t.startsWith(r+"/");let s="/"+r,o=t.indexOf(s);for(;o!==-1;){let i=o+s.length;if(i===t.length||t[i]==="/")return!0;o=t.indexOf(s,o+1)}return t===r||t.startsWith(r+"/")}function yC(n){return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function $L(n){if(!OL(n.status))return null;let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=r.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=et(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"){let s=et(r);if(s.length>0)return s}}return null}function OL(n){return n==="failed"||n==="rejected"||n==="cancelled"}function FL(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 op(n){if(typeof n=="string")return Gt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?Gt(e.text):""}function LL(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let r=op(t);r.length>0&&e.push(r)}return e.join("")}function wC(n,e){let t=n[e];return typeof t=="string"?t:void 0}function bC(n){try{return JSON.stringify(n)}catch{return""}}function NL(n,e,t,r=ip){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let o=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),a=i.length>0?o.indexOf(i):0;a===-1&&(a=0);let d=kC(r),c=Math.max(0,d-i.length),l=Math.floor(c/2),f=Math.min(l,a),u=Math.min(c-f,s.length-(a+i.length)),p=Math.max(0,a-(c-u)),m=Math.min(s.length,a+i.length+u),h=p>0?"\u2026":"",y=m<s.length?"\u2026":"";return`${h}${s.slice(p,m)}${y}`}var xL,CL,ip,AL,RL,ap=j(()=>{"use strict";$o();xL=5,CL=200,ip=72,AL=24,RL=512});function As(n){let e=[],t=[],r=!1,s=o=>{if(!r){r=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:G.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>s()),n.on("error",o=>s(o)),{async send(o){if(r)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{n.send(i,c=>{if(c){d(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){r||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(d),o())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),s())}}}var Td=j(()=>{"use strict";rn()});import{spawn as jN}from"child_process";import{dirname as qN,resolve as zN}from"path";import{fileURLToPath as KN}from"url";import{setTimeout as dA}from"timers/promises";async function cA(){let n=await ps();if(n&&pr(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function GN(n){let e=await Di(n,500);return e?e.home!==void 0&&e.home!==D.home()||e.configDigest===void 0?"mismatch":e.configDigest===_o(n)?"match":"mismatch":"missing"}async function No(n,e){let t=await GN(n);if(t==="mismatch"){let r=En();throw new Error(`config changed since daemon started \u2014 run \`${r} daemon restart\` to apply.`)}if(t==="missing"&&(process.stderr.write(`hydra-acp: daemon not running; starting it...
|
|
122
|
+
`,{encoding:"utf8"}))}function Lf(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(s=>!t.has(s)),...e]}function _y(n,e,t=Tx){if(e.length===0)return n;let r=new Set(n),s=n;for(let o of e){let i=o.replace(/\n+$/,"");i.length!==0&&(r.has(i)||(r.add(i),s=tl(s,i,t)))}return s}var Tx,Nf=j(()=>{"use strict";Tx=500});import{z as it}from"zod";function nl(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 zr(n){return iL.parse(n)}var sL,oL,iL,Oi=j(()=>{"use strict";my();gf();sL=it.object({method:it.string(),params:it.unknown(),recordedAt:it.number()}),oL=it.object({sessionId:it.string(),lineageId:it.string(),upstreamSessionId:it.string().optional(),agentId:it.string(),cwd:it.string(),title:it.string().optional(),synopsis:Gc.optional(),summarizedThroughEntry:it.number().int().nonnegative().optional(),currentModel:it.string().optional(),currentMode:it.string().optional(),currentUsage:fy.optional(),agentCommands:it.array(ly).optional(),agentModes:it.array(uy).optional(),interactive:it.boolean().optional(),originatingClient:py.optional(),priority:it.number().int().nonnegative().optional(),createdAt:it.string(),updatedAt:it.string()}),iL=it.object({version:it.literal(1),exportedAt:it.string(),exportedFrom:it.object({hydraVersion:it.string(),machine:it.string(),hydraHost:it.string().optional()}),session:oL,history:it.array(sL),promptHistory:it.array(it.string()).optional(),toolBlobs:it.record(it.string()).optional()})});function rl(n){if(n&&!(n.costAmount===void 0&&n.cumulativeCost===void 0))return(n.cumulativeCost??0)+(n.costAmount??0)}function Fi(n){if(!n)return;let e={};n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size);let t=rl(n);return t&&(e.costAmount=t),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),e}var wd=j(()=>{"use strict"});import{createHash as xL}from"crypto";function ul(n){if(Array.isArray(n))return n.map(ul);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=ul(n[t]);return e}return n}function _o(n){let e={};for(let[r,s]of Object.entries(n)){let o=Sm(r);if(o.nested){let i={};for(let[a,d]of Object.entries(s??{}))Im(a).reload==="restart"&&(i[a]=d);Object.keys(i).length>0&&(e[r]=i);continue}o.reload==="restart"&&(e[r]=s)}let t=JSON.stringify(ul(e));return xL("sha256").update(t).digest("hex").slice(0,16)}function Wx(n,e){let t=[],r=(s,o)=>JSON.stringify(ul(s))!==JSON.stringify(ul(o));for(let s of Object.keys(e)){let o=Sm(s),i=e[s],a=n[s];if(o.nested){for(let d of Object.keys(i??{})){if(Im(d).reload!=="warn")continue;let c=i[d],l=(a??{})[d];r(l,c)&&t.push(`${s}.${d}`)}continue}o.reload==="warn"&&r(a,i)&&t.push(s)}return t}var Id=j(()=>{"use strict";ot();Cm()});function qy(n){return Math.floor(n/4)}function eC(n){let e=0,t=new Map;for(let r of n){let s=r.params;if(!s||typeof s!="object")continue;let o=s.update;if(!o||typeof o!="object")continue;let i=o;switch(i.sessionUpdate){case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":e+=Ni(i.content);break;case"tool_call":case"tool_call_update":{let a=typeof i.toolCallId=="string"?i.toolCallId:"",d=NL(i),c=t.get(a)??0;d>c&&t.set(a,d);break}default:break}}for(let r of t.values())e+=r;return e}function NL(n){let e=0;return typeof n.title=="string"&&(e+=n.title.length),e+=ep(n.rawInput),e+=Ni(n.content),e+=ep(n.rawOutput),e}function ep(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(typeof n=="number"||typeof n=="boolean")return String(n).length;if(Array.isArray(n)){let e=0;for(let t of n)e+=ep(t);return e}if(typeof n=="object"){let e=n.bytes;if(typeof n.__hydraBlob=="string"&&typeof e=="number")return e;let t=0;for(let r of Object.values(n))t+=ep(r);return t}return 0}function Ni(n){if(n==null)return 0;if(typeof n=="string")return n.length;if(Array.isArray(n)){let t=0;for(let r of n)t+=Ni(r);return t}if(typeof n!="object")return 0;let e=n;return typeof e.__hydraBlob=="string"&&typeof e.bytes=="number"?e.bytes:e.text!==void 0?Ni(e.text):e.type==="diff"?Ni(e.oldText)+Ni(e.newText):e.content!==void 0?Ni(e.content):0}function tC(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e,t;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize,t=!0;else{let s=qy(n.unsummarizedChars),o=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/o,t=!1}if(t&&e>=n.config.hardCeilingFraction)return!0;let r=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&r>=n.config.idleBeforePromptMs}function nC(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var zy=j(()=>{"use strict"});function fl(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var rC=j(()=>{"use strict"});import{posix as BL}from"path";import DL from"strip-ansi";function Gt(n){return DL(n).replace(HL,"")}function et(n){return Gt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Cs(n,e={}){if(!n||typeof n!="object")return null;let t=n,r=t.sessionUpdate??t.kind;if(typeof r!="string")return null;switch(r){case"agent_message_chunk":return KL(t);case"agent_thought_chunk":case"agent_thought":return GL(t);case"user_message_chunk":return VL(t);case"prompt_received":return JL(t);case"tool_call":return YL(t,e);case"tool_call_update":return t1(t,e);case"plan":return s1(t);case"current_mode_update":return o1(t);case"_hydra_current_model_update":return i1(t);case"turn_complete":return a1(t);case"_hydra_turn_started":return iC(t,"turn-started");case"_hydra_turn_ended":return iC(t,"turn-ended");case"usage_update":return zL(t);case"available_commands_update":return jL(t);case"_hydra_available_modes_update":return qL(t);case"session_info_update":return WL(t);case"config_option_update":return UL(t);default:return{kind:"unknown",sessionUpdate:r,raw:n}}}function UL(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||typeof s.currentValue!="string"||!Array.isArray(s.options))continue;let o=[];for(let i of s.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:s.id,name:typeof s.name=="string"?s.name:s.id,type:"select",currentValue:s.currentValue,options:o,...typeof s.category=="string"?{category:s.category}:{}})}return{kind:"config-options",options:t}}function WL(n){let e=Lt(n,"title"),t=e!==void 0?et(e):void 0,r=n._meta,s,o;if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(s=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&s===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),s!==void 0&&(i.agentId=s),o!==void 0&&(i.pendingAgentSwap=o),i}function tp(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.name!="string"||r.name.length===0)continue;let s=r.name.startsWith("/")?r.name:`/${r.name}`,o={name:et(s)};typeof r.description=="string"&&(o.description=et(r.description)),e.push(o)}return e}function jL(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:tp(e)}:null}function qL(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||s.id.length===0)continue;let o={id:et(s.id)};typeof s.name=="string"&&(o.name=et(s.name)),typeof s.description=="string"&&(o.description=et(s.description)),t.push(o)}return{kind:"available-modes",modes:t}}function zL(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function KL(n){let e=pl(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:fl(n)}}function GL(n){let e=typeof n.text=="string"?Gt(n.text):pl(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:fl(n)}}function VL(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e["hydra-acp"];if(r&&typeof r=="object"&&!Array.isArray(r)&&r.compatFor==="prompt_received")return null}let t=pl(n.content);return t===null?null:{kind:"user-text",text:t}}function JL(n){let e=d1(n.prompt);return e===null?null:{kind:"user-text",text:e}}function aC(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function sC(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function np(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(s.type!=="diff")continue;let o=sC(s.oldText),i=sC(s.newText);if(o===void 0&&i===void 0)continue;let a=typeof s.path=="string"?s.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t,s=typeof r.file_path=="string"?r.file_path:typeof r.path=="string"?r.path:void 0;if(typeof r.old_string=="string"&&typeof r.new_string=="string")return{...s!==void 0?{path:s}:{},oldText:r.old_string,newText:r.new_string};if(typeof r.content=="string")return{...s!==void 0?{path:s}:{},oldText:"",newText:r.content}}return null}function dC(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:Gt(t)}function YL(n,e={}){let t=Lt(n,"toolCallId")??Lt(n,"id");if(!t)return null;let r=Lt(n,"title")??Lt(n,"name")??Lt(n,"label")??"tool call",s=Lt(n,"name")??Lt(n,"title");if(aC(s)){let m=dC(n);if(m!==null){let h=Lt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:m};return h!==void 0&&(y.status=h),y}}let o=uC(et(r),n,e),i=Lt(n,"status"),a=Lt(n,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=np(n);c!==null&&(d.editDiff=c);let l=lC(n);l!==void 0&&(d.detail=l);let f=Ky(n);f!==void 0&&(d.detailFull=f);let u=cC(n);u!==void 0&&(d.locations=u);let p=fl(n);return p!==void 0&&(d.workerTaskId=p),d}function cC(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.path!="string"||s.path.length===0)continue;let o={path:s.path};typeof s.line=="number"&&Number.isFinite(s.line)&&s.line>=1&&(o.line=Math.floor(s.line)),t.push(o)}return t.length>0?t:void 0}function lC(n){let e=Ky(n);if(e===void 0)return;let t=et(e),r=n.rawInput;return r&&typeof r.command=="string"?ZL(t,oC):e1(t,oC)}function Ky(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return Gt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let r=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(r!==void 0&&r.length>0)return K(et(r))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let r=t.path;if(typeof r=="string"&&r.length>0)return K(et(r))}}}function XL(n){for(let e of QL)if(n.startsWith(e))return!0;return!1}function uC(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return K(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let r=e.rawInput;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=[s.file_path,s.filePath,s.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return K(i)}return XL(n)?K(`/${n}`):t.cwd&&t.cwd.length>0?K(BL.resolve(t.cwd,n)):n}function ZL(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function e1(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),r=t.indexOf("/");return r>=0&&r<e/2?`\u2026${t.slice(r)}`:`\u2026${t}`}function t1(n,e={}){let t=Lt(n,"toolCallId")??Lt(n,"id");if(!t)return null;let r=Lt(n,"title"),s=r!==void 0?uC(et(r),n,e):void 0,o=Lt(n,"status"),i=np(n),a=lC(n),d=Gy(n);if(!(s!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let l=Lt(n,"name")??r;if(aC(l)){let h={kind:"exit-plan-mode",toolCallId:t},y=dC(n);return y!==null&&(h.plan=y),o!==void 0&&(h.status=o),h}let f={kind:"tool-call-update",toolCallId:t};s!==void 0&&(f.title=s),a!==void 0&&(f.detail=a);let u=Ky(n);u!==void 0&&(f.detailFull=u);let p=cC(n);if(p!==void 0&&(f.locations=p),d!==void 0&&(f.resultSummary=d),o!==void 0&&(f.status=o),i!==null&&(f.editDiff=i),o==="failed"){let h=n1(n);h!==null&&(f.errorText=h),r1(n,h)&&(f.upstreamInterrupted=!0)}let m=fl(n);return m!==void 0&&(f.workerTaskId=m),f}function Gy(n){if(!n||typeof n!="object")return;let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r=l=>{let f=t[l];return typeof f=="number"&&Number.isFinite(f)?f:void 0},s=(l,f,u=`${f}s`)=>`${l} ${l===1?f:u}`,o=[],i=r("totalMatches");i!==void 0&&o.push(s(i,"match","matches"));let a=r("totalFiles");a!==void 0&&o.push(s(a,"file"));let d=r("referenceCount");d!==void 0&&o.push(s(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let c=r("exitCode");return c!==void 0&&c!==0&&o.push(`exit ${c}`),o.length>0?o.join(", "):void 0}function fC(n){if(!n||typeof n!="object")return[];let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e,r=[];for(let s of["content","stdout","stderr"]){let o=t[s];typeof o=="string"?o.length>0&&r.push(o):o&&typeof o=="object"&&!Array.isArray(o)&&r.push(o)}return r}function n1(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=pl(r.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"&&r.length>0)return Gt(r)}return null}function r1(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.metadata;if(r&&typeof r=="object"&&r.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function s1(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r,o=typeof s.content=="string"?et(s.content):void 0;if(!o)continue;let i={content:o};typeof s.status=="string"&&(i.status=s.status),typeof s.priority=="string"&&(i.priority=s.priority),t.push(i)}return{kind:"plan",entries:t}}function o1(n){let e=Lt(n,"currentModeId")??Lt(n,"currentMode")??Lt(n,"mode");return e?{kind:"mode-changed",mode:et(e)}:null}function i1(n){let e=Lt(n,"currentModel")??Lt(n,"model");if(!e)return null;let t=n.availableModels,r=Array.isArray(t)?t.map(s=>typeof s=="object"&&s!==null?s.modelId:typeof s=="string"?s:void 0).filter(s=>typeof s=="string"&&s.length>0):void 0;return{kind:"model-changed",model:et(e),...r&&r.length>0?{availableModels:r}:{}}}function a1(n){let e=Lt(n,"stopReason"),t=n._meta,r=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,s={kind:"turn-complete"};return e!==void 0&&(s.stopReason=e),r&&(s.amended=!0),s}function iC(n,e){let r=n._meta?.["hydra-acp"],s=r?.unsolicited===!0;if(e==="turn-started"){let i=r?.cause?.label,a={kind:e,unsolicited:s};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:s};return typeof r?.reason=="string"&&(o.reason=r.reason),o}function pl(n){if(typeof n=="string")return Gt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?Gt(e.text):null}function d1(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let r=pl(t);r!==null&&e.push(r)}return e.length===0?null:e.join("")}function Lt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var HL,oC,QL,$o=j(()=>{"use strict";ve();rC();HL=/[\x00-\x08\x0b-\x1f\x7f]/g;oC=64;QL=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function xd(n){let e=new Map,t=new Map;for(let s of n){let i=s.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=l1(i);if(c.length===0)continue;let l=c;if(d!==void 0){let f=e.get(d)??[],u=[];for(let p of c)f.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(d,[...f,...u]),l=u}for(let f of l)c1(t,f)}let r=[];for(let[s,o]of t)r.push({path:s,hunks:o.hunks,created:o.created});return r}function Cd(n){let e=[];for(let t of n){let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){r=o;break}if(r===-1){e.push(t);continue}let s=e[r];e.splice(r,1,{oldText:s.oldText,newText:t.newText})}return e}function c1(n,e){let t={oldText:e.oldText,newText:e.newText},r=n.get(e.path);if(r===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}r.hunks.push(t)}function l1(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,f=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||f===void 0||e.push({path:i,oldText:l,newText:f})}if(e.length>0)return e}}let r=n.content;if(Array.isArray(r)){for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let d=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let s=np(n);return s&&s.path&&e.push({path:s.path,oldText:s.oldText,newText:s.newText}),e}var rp=j(()=>{"use strict";$o()});function v1(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,r=[],s;for(;(s=t.exec(e))!==null;)r.push(s[0]);let o="OR",i=!1,a=!1,d=[];for(let l of r){let f=l.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:d.push(l)}i?o="AND":a&&(o="OR");let c=d.map(l=>S1(l)).filter(l=>l.term.length>0);return{operator:o,terms:c}}function S1(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:mC(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let r=/^(prompt|response|tool|edit|edited):([\s\S]*)$/i.exec(n);return r?{scope:mC(r[1]),term:r[2].trim()}:{scope:"all",term:n.trim()}}function mC(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";case"edit":case"edited":return"edit";default:return"all"}}function I1(n,e){return e==="edit"?n==="edit":n==="edit"?!1:n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}function kC(n){return Number.isFinite(n)?Math.max(A1,Math.min(R1,Math.floor(n))):ip}async function vC(n,e,t={}){let r=v1(e);if(r.terms.length===0)return{query:e,truncated:!1,results:[]};let s=t.maxSnippetsPerSession??x1,o=t.maxSessions??C1,i=kC(t.snippetWidth??ip),a=t.sessionIds?new Set(t.sessionIds):null,d=await n.list(),c=a?d.filter(u=>a.has(u.sessionId)):d,l=[],f=!1;for(let u of c){if(l.length>=o){f=!0;break}let p=await n.loadHistory(u.sessionId,{tools:"references"}).catch(()=>[]),m=T1(p,r,s,i,Ad(u));if(m.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:m.totalMatches,snippets:m.snippets};u.title!==void 0&&(h.title=u.title),l.push(h)}return{query:e,truncated:f,results:l}}function Ad(n){let e=n.workspace?.sourceCwd;if(e===void 0||e.length===0||n.cwd.length===0)return;let t=n.cwd.endsWith("/")?n.cwd:n.cwd+"/";return r=>r.startsWith(t)?e.replace(/\/+$/,"")+"/"+r.slice(t.length):r}function T1(n,e,t,r=ip,s){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let o=0,i=[],a=Math.max(1,Math.floor(t/e.terms.length)),d=[];for(let{scope:c,term:l}of e.terms){let f=E1(n,l,c,t,r,s);if(e.operator==="AND"&&f.totalMatches===0)return{totalMatches:0,snippets:[]};o+=f.totalMatches,i.push(...f.snippets.slice(0,a)),d.push(...f.snippets.slice(a))}for(let c of d){if(i.length>=t)break;i.push(c)}return{totalMatches:o,snippets:i.slice(0,t)}}function E1(n,e,t,r,s,o){let i=e.toLowerCase(),a=0,d=[],c=new Set;for(let l of n){let f=P1(l).filter(u=>I1(t,u.kind));for(let u of f){let p=u.text.toLowerCase();if(u.kind==="edit"){let y=o?.(u.text);if(!(gC(u.text,e)||(y!==void 0&&y!==u.text?gC(y,e):!1))||c.has(u.text))continue;if(c.add(u.text),a+=1,d.length<r){let k={kind:"edit",text:u.text,recordedAt:l.recordedAt};u.toolName!==void 0&&(k.toolName=u.toolName),d.push(k)}continue}let m=p.indexOf(i);if(m===-1)continue;let h=0;for(;m!==-1;)h++,m=p.indexOf(i,m+i.length);if(a+=h,d.length<r){let y=p.indexOf(i),w={kind:u.kind,text:N1(u.text,y,i.length,s),recordedAt:l.recordedAt};u.toolName!==void 0&&(w.toolName=u.toolName),d.push(w)}}}return{totalMatches:a,snippets:d}}function P1(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let r=t,s=typeof r.sessionUpdate=="string"?r.sessionUpdate:r.kind;if(typeof s!="string")return[];switch(s){case"agent_message_chunk":{let o=op(r.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof r.text=="string"?Gt(r.text):op(r.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(F1(r))return[];let o=op(r.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=L1(r.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return M1(r);default:return[]}}function M1(n){let e=wC(n,"name"),t=wC(n,"title"),r=[];if(t!==void 0){let a=et(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),r.push(d)}}if(e!==void 0&&e!==t){let a=et(e);a.length>0&&r.push({kind:"tool",toolName:e,text:a})}let s=n.rawInput;if(s&&typeof s=="object"){let a=bC(s);if(a.length>0){let d={kind:"tool-input",text:et(a)};e!==void 0&&(d.toolName=e),r.push(d)}}for(let a of _1(n)){let d={kind:"edit",text:a};e!==void 0&&(d.toolName=e),r.push(d)}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=bC(o);if(a.length>0){let d={kind:"tool-input",text:et(a)};e!==void 0&&(d.toolName=e),r.push(d)}}let i=$1(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),r.push(a)}return r}function _1(n){let e=[],t=new Set,r=i=>{typeof i!="string"||i.length===0||t.has(i)||(t.add(i),e.push(i))},s=n.content;if(Array.isArray(s))for(let i of s){if(!i||typeof i!="object")continue;let a=i;a.type==="diff"&&r(a.path)}let o=n.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o;(i.old_string!==void 0||i.new_string!==void 0||i.content!==void 0||Array.isArray(i.edits))&&r(typeof i.file_path=="string"?i.file_path:i.path)}return e}function gC(n,e){let t=yC(n.toLowerCase()),r=yC(e.toLowerCase());if(r.length===0)return!1;if(r.startsWith("/"))return t===r||t.startsWith(r+"/");let s="/"+r,o=t.indexOf(s);for(;o!==-1;){let i=o+s.length;if(i===t.length||t[i]==="/")return!0;o=t.indexOf(s,o+1)}return t===r||t.startsWith(r+"/")}function yC(n){return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function $1(n){if(!O1(n.status))return null;let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=r.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=et(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"){let s=et(r);if(s.length>0)return s}}return null}function O1(n){return n==="failed"||n==="rejected"||n==="cancelled"}function F1(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 op(n){if(typeof n=="string")return Gt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?Gt(e.text):""}function L1(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let r=op(t);r.length>0&&e.push(r)}return e.join("")}function wC(n,e){let t=n[e];return typeof t=="string"?t:void 0}function bC(n){try{return JSON.stringify(n)}catch{return""}}function N1(n,e,t,r=ip){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let o=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),a=i.length>0?o.indexOf(i):0;a===-1&&(a=0);let d=kC(r),c=Math.max(0,d-i.length),l=Math.floor(c/2),f=Math.min(l,a),u=Math.min(c-f,s.length-(a+i.length)),p=Math.max(0,a-(c-u)),m=Math.min(s.length,a+i.length+u),h=p>0?"\u2026":"",y=m<s.length?"\u2026":"";return`${h}${s.slice(p,m)}${y}`}var x1,C1,ip,A1,R1,ap=j(()=>{"use strict";$o();x1=5,C1=200,ip=72,A1=24,R1=512});function As(n){let e=[],t=[],r=!1,s=o=>{if(!r){r=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:G.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>s()),n.on("error",o=>s(o)),{async send(o){if(r)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,d)=>{n.send(i,c=>{if(c){d(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){r||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(d),o())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),s())}}}var Td=j(()=>{"use strict";rn()});import{spawn as jN}from"child_process";import{dirname as qN,resolve as zN}from"path";import{fileURLToPath as KN}from"url";import{setTimeout as dA}from"timers/promises";async function cA(){let n=await ps();if(n&&pr(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function GN(n){let e=await Di(n,500);return e?e.home!==void 0&&e.home!==D.home()||e.configDigest===void 0?"mismatch":e.configDigest===_o(n)?"match":"mismatch":"missing"}async function No(n,e){let t=await GN(n);if(t==="mismatch"){let r=En();throw new Error(`config changed since daemon started \u2014 run \`${r} daemon restart\` to apply.`)}if(t==="missing"&&(process.stderr.write(`hydra-acp: daemon not running; starting it...
|
|
123
123
|
`),kp(n),await vp(n)),e!==void 0){let r=await ps();if(r&&pr(r.pid)){let s=`http://127.0.0.1:${r.loopbackPort}`;e.baseUrl=s,e.wsUrl=`ws://127.0.0.1:${r.loopbackPort}/acp`}await JN(`${e.baseUrl}/v1/health`)}}async function bp(n){let e=await cA();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Di(n,e=1e3){let t=await cA();if(t)try{let r=await fetch(t,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!r.ok)return;let s=await r.json();return{version:typeof s.version=="string"?s.version:void 0,configDigest:typeof s.configDigest=="string"?s.configDigest:void 0,home:typeof s.home=="string"?s.home:void 0,driftedKeys:Array.isArray(s.driftedKeys)?s.driftedKeys.filter(o=>typeof o=="string"):void 0}}catch{return}}function kp(n){let e=qN(KN(import.meta.url)),t=zN(e,"./daemon.js");n&&Lc(n.daemon.scrubEnv),jN(process.execPath,[t],{detached:!0,stdio:"ignore",env:Za()}).unref()}async function VN(n,e=500){try{return(await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}})).ok}catch{return!1}}async function JN(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await VN(n))return;await dA(150)}throw new Error(`hydra-acp daemon did not answer ${n} within ${e}ms`)}async function vp(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await bp(n))return;await dA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Hi=j(()=>{"use strict";Ua();Id();ed();Wa();ve()});import*as lA from"fs";import*as _d from"fs/promises";async function $d(n,e,t){let r=QN(e),s;try{s=await _d.stat(n)}catch(d){if(d.code==="ENOENT"){process.stderr.write(`${t} (${n})
|
|
124
124
|
`),process.exit(1);return}throw d}let o=await YN(n,s.size,r.tail);if(!r.follow)return;process.stdout.write(`-- following ${n} --
|
|
125
125
|
`);let i=!1,a=lA.watch(n,()=>{i||(i=!0,setImmediate(async()=>{i=!1;try{let d=await _d.stat(n);if(d.size<=o){d.size<o&&(o=d.size);return}let c=await _d.open(n,"r");try{let l=Buffer.alloc(d.size-o);await c.read(l,0,l.length,o),process.stdout.write(l),o=d.size}finally{await c.close()}}catch{}}))});await new Promise(d=>{let c=()=>{a.close(),d()};process.once("SIGINT",c),process.once("SIGTERM",c)})}async function YN(n,e,t){if(t<=0||e===0)return e;let r=64*1024,s=await _d.open(n,"r");try{let o=e,i="",a=0;for(;o>0&&a<=t;){let l=Math.min(r,o);o-=l;let f=Buffer.alloc(l);await s.read(f,0,l,o),i=f.toString("utf8")+i,a=(i.match(/\n/g)??[]).length}let c=i.split(`
|
|
@@ -232,7 +232,7 @@ failed to spawn ${e.command}: ${a.message}
|
|
|
232
232
|
`;io.writeFileSync(D.ttySessionFile(e),t,{mode:384})}catch{}}function rj(n){let e=n.trim();if(e.length===0)return null;if(!e.includes(":"))return{hydraPid:0,parentPid:0,sessionId:e};let t=e.split(":");if(t.length<3)return null;let r=Number.parseInt(t[0],10),s=Number.parseInt(t[1],10),o=t.slice(2).join(":");return!Number.isFinite(r)||!Number.isFinite(s)||o.length===0?null:{hydraPid:r,parentPid:s,sessionId:o}}function sj(){let n=rE();if(!n)return null;try{let e=io.readFileSync(D.ttySessionFile(n),"utf8");return rj(e)}catch{return null}}function oj(){let n=sj();return!n||n.parentPid>0&&n.parentPid!==process.ppid?null:n.sessionId}function Ob(n){!n.startsWith("/")||!process.stdout.isTTY||process.stdout.write(`${tE}7;${QA(n)}${ej}`)}function sE(){let n;try{n=process.cwd()}catch{return}Ob(n)}function Fb(n){nE("hydra_session",n),nj(n)}function oE(){nE("hydra_session","")}function iE(){return oj()}var tE,ZW,ej,$b,Lb=j(()=>{"use strict";ve();no();tE="\x1B]",ZW="\x07",ej="\x1B\\"});import ij from"string-width";function aE(n,e){if(!n||e<=0)return 0;let t=0;for(let r of aj.segment(n)){let s=ij(r.segment);if(e<t+s)return r.index;if(t+=s,e===t)return r.index+r.segment.length}return n.length}function dE(n,e){if(e<=0)return 0;let t=0,r=0;for(let s of n)if(s.width>0&&e<t+s.width||(t+=s.width,r+=s.text.length,s.width>0&&e===t))return r;return r}var aj,cE=j(()=>{"use strict";aj=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function cj(){let n=dj.map(e=>{let t=process.listeners(e);for(let s of t)process.off(e,s);let r=()=>{};return process.on(e,r),{signal:e,listeners:t,noop:r}});return()=>{for(let{signal:e,listeners:t,noop:r}of n){process.off(e,r);for(let s of t)process.on(e,s)}}}async function lE(n,e){let t=e.spawn??(await import("child_process")).spawn,r=e.write??(o=>{process.stdout.write(o)}),s=cj();return e.suspend(),r(NR),n.banner!==void 0&&r(n.banner),await new Promise(o=>{let i=!1,a=d=>{if(!i){i=!0;try{e.resume()}finally{s()}d.error?e.notify?.(`${n.program} failed: ${d.error.message}`):d.exitCode!==null&&d.exitCode!==0&&e.notify?.(`${n.program} exited ${d.exitCode}`),o(d)}};try{let d=t(n.program,n.args,{stdio:"inherit",cwd:n.cwd});d.on("exit",c=>a({exitCode:c})),d.on("error",c=>a({exitCode:null,error:c}))}catch(d){a({exitCode:null,error:d})}})}var dj,uE=j(()=>{"use strict";Yi();dj=process.platform==="win32"?["SIGINT"]:["SIGINT","SIGQUIT"]});function uj(n){return(n.split(/[/\\]/).pop()??n).replace(/\.exe$/i,"").toLowerCase()}function fE(n,e,t){let[r,...s]=n;if(!r)return null;let o=t===null?"":String(t),i=!1,a=!1,d=[];for(let l of s)l.includes("%f")&&(i=!0),!(l.includes("%n")&&(a=!0,o===""))&&d.push(l.replaceAll("%f",e).replaceAll("%n",o));if(i)return{program:r,args:d};let c=o===""||a?void 0:lj[uj(r)];return c==="plus"?d.push(`+${o}`,e):c==="colon"?d.push(`${e}:${o}`):d.push(e),{program:r,args:d}}var lj,pE=j(()=>{"use strict";lj={vi:"plus",vim:"plus","vim.basic":"plus","vim.tiny":"plus",vimdiff:"plus",view:"plus",ex:"plus",nvim:"plus",nvimdiff:"plus",gvim:"plus",mvim:"plus",nano:"plus",pico:"plus",micro:"plus",kak:"plus",joe:"plus",emacs:"plus",emacsclient:"plus",hx:"colon",helix:"colon"}});function fj(){Gl===0&&ge(KR),Gl++}function pj(){Gl!==0&&(Gl--,Gl===0&&ge(GR))}function at(n){fj();try{n()}finally{pj()}}var Gl,Nb=j(()=>{"use strict";Yi();Gl=0});function hj(n=Bb){let e=`
|
|
233
233
|
\r`+hE;for(let t of n)e+=t+hE;return e+"\r\x1B[K"}function mj(n){let e=[],t=/\u001b\[(\d+);(\d+)R/g,r;for(;(r=t.exec(n))!==null;)e.push([Number(r[1]),Number(r[2])]);return e}function mE(n){return/\u001b\[\d+;\d+R/.test(n)}function gE(n){return n.replace(/\u001b\[\d+;\d+R/g,"")}function gj(n,e=Bb){if(n.length<e.length+1)return;let t={};for(let r=0;r<e.length;r++){let[s,o]=n[r],[i,a]=n[r+1];if(i!==s)return;let d=a-o;if(d!==1&&d!==2)return;t[e[r]]=d}return t}function yj(n){let e=Object.values(n);return e.length===0?!1:e.filter(r=>r===2).length>e.length/2}async function yE(n={input:process.stdin,output:process.stdout},e=200,t=Bb){let{input:r,output:s}=n;if(!(r.isTTY!==!0||s.isTTY!==!0)&&!((s.columns??80)<t.length+2))return await new Promise(o=>{let i="",a=!1,d=r.isPaused?.()??!1,c,l=u=>{if(!a){a=!0,c!==void 0&&clearTimeout(c);try{(r.off??r.removeListener)?.call(r,"data",f),r.setRawMode?.(!1),d&&r.pause?.()}catch{}o(u)}},f=u=>{i+=typeof u=="string"?u:u.toString("latin1");let p=mj(i);if(p.length<t.length+1)return;let m=gj(p,t);l(m===void 0?void 0:{wide:yj(m),widths:m})};try{r.setRawMode?.(!0),r.resume?.(),r.on("data",f),s.write(hj(t))}catch{l(void 0);return}c=setTimeout(()=>l(void 0),e),c.unref?.()})}var hE,Bb,Db=j(()=>{"use strict";hE="\x1B[6n",Bb=["\u2500","\u2502","\xB7","\u258F","\u2026","\u2713","\u25B8"]});function kj(){let n="\x1B]10;?\x07\x1B]11;?\x07";for(let e=0;e<16;e++)n+=`\x1B]4;${e};?\x07`;return n}function wE(n){let e=/\u001b\]11;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:Hb(e[1])}function vj(n){let e=/\u001b\]10;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:Hb(e[1])}function Sj(n){let e=new Map;for(let t of n.matchAll(/\u001b\]4;(\d+);([^\u0007\u001b]*)(?:\u0007|\u001b\\)/g)){let r=Number(t[1]);if(!Number.isInteger(r)||r<0||r>15)continue;let s=Hb(t[2]);s!==void 0&&e.set(r,s)}return e}function Hb(n){let e=n.trim();if(/^#[0-9a-f]+$/i.test(e))return xo(e)??void 0;let t=/^rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(e);if(t===null)return;let r=a=>{if(!(a.length===0||a.length>4))return Math.round(parseInt(a,16)/(16**a.length-1)*255)},s=r(t[1]),o=r(t[2]),i=r(t[3]);if(!(s===void 0||o===void 0||i===void 0))return Pn(s,o,i)}function Ij(n){return n.replace(/\u001b\](?:10|11|4);[^\u0007\u001b]*(?:\u0007|\u001b\\)/g,"")}function xj(n){return/\u001b\](?:10|11|4);/.test(n)}async function bE(n={input:process.stdin,output:process.stdout},e=wj){let{input:t,output:r}=n;return t.isTTY!==!0||r.isTTY!==!0?{palette:new Map}:await new Promise(s=>{let o="",i=!1,a=t.isPaused?.()??!1,d,c,l=()=>({foreground:vj(o),background:wE(o),palette:Sj(o)}),f=p=>{o+=typeof p=="string"?p:p.toString("latin1");let m=l();if(m.foreground!==void 0&&m.background!==void 0&&m.palette.size===16){u();return}c!==void 0&&clearTimeout(c),c=setTimeout(u,bj),c.unref?.()},u=()=>{if(i)return;i=!0;for(let m of[d,c])m!==void 0&&clearTimeout(m);let p=l();try{(t.off??t.removeListener)?.call(t,"data",f),t.setRawMode?.(!1),a&&t.pause?.()}catch{}s(p)};try{t.setRawMode?.(!0),t.resume?.(),t.on("data",f),r.write(kj())}catch{u();return}d=setTimeout(u,e),d.unref?.()})}function Cj(n){let e=/\u001b\[\?997;([12])n/.exec(n);if(e!==null)return e[1]==="1"?"dark":"light"}function Aj(n){return n.replace(/\u001b\[\?997;\d+n/g,"")}function SE(n){return n==="dark"?Pn(0,0,0):Pn(255,255,255)}function IE(n,e={}){if(n===null||typeof n!="object")return;let t=n,r=t.onStdin;typeof r=="function"&&(t.onStdin=function(o){let i=o.toString("latin1");if(!xj(i)&&!/\u001b\[\?997;/.test(i)&&!mE(i)){r.call(this,o);return}let a=wE(i),d=Cj(i),c=gE(Aj(Ij(i)));c.length>0&&r.call(this,Buffer.from(c,"latin1")),a!==void 0&&e.onBackground?.(a),d!==void 0&&e.onScheme?.(d)})}var wj,bj,kE,vE,Ub=j(()=>{"use strict";Va();Db();wj=200,bj=50;kE="\x1B[?2031h",vE="\x1B[?2031l"});import{spawn as Rj}from"child_process";import{statSync as Vl}from"fs";import{homedir as Ah}from"os";import{isAbsolute as Rh,join as xE,resolve as CE,sep as Th}from"path";import OE from"string-width";import Tj from"wrap-ansi";function Yj(n){let e=n.replace(/\r\n?$|\n$/,"");return Jj.test(e)?e:null}function Qj(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function Xj(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function Zj(n,e){if(n.body!==e.body||(n.prefix??"")!==(e.prefix??"")||(n.bodyStyle??"")!==(e.bodyStyle??"")||(n.prefixStyle??"")!==(e.prefixStyle??"")||!!n.ansi!=!!e.ansi||!!n.fillRow!=!!e.fillRow||!!n.collapsed!=!!e.collapsed||(n.blockKey??"")!==(e.blockKey??"")||(n.hoverSubKey??"")!==(e.hoverSubKey??"")||(n.maxWrapRows??0)!==(e.maxWrapRows??0)||(n.hangingIndent??0)!==(e.hangingIndent??0))return!1;let t=n.links,r=e.links;if(t===void 0!=(r===void 0))return!1;if(t&&r){if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++){let o=t[s],i=r[s];if(o.start!==i.start||o.end!==i.end||o.url!==i.url)return!1}}return!0}function Yb(n,e,t,r=null,s=null,o=null){let i=s===null?"":`a${s}`,a=o===null?"":`s${o.start}:${o.end}${o.toEndOfLine?"f":""}`;return t?`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${r??""}|${i}|${a}`:`${n}|${e}|empty|${r??""}|${i}|${a}`}function Ns(n,e){let t=[];for(let r=0;r<n.length;r++){let s=n[r]??"";if(s.length===0){t.push({bufferIdx:r,startCol:0,endCol:0});continue}let o=0;for(;o<s.length;){if(s.length-o<=e){t.push({bufferIdx:r,startCol:o,endCol:s.length}),o=s.length;break}let i=-1;for(let a=o+e-1;a>=o;a--){let d=s[a];if(d===" "||d===" "){i=a+1;break}}i===-1&&(i=o+e),t.push({bufferIdx:r,startCol:o,endCol:i}),o=i}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function ao(n,e,t){let r=0,s=0,o=-1;for(let d=0;d<n.length;d++){let c=n[d];if(!(!c||c.bufferIdx!==e.row)&&(o=d,e.col>=c.startCol&&e.col<c.endCol)){r=d,s=e.col-c.startCol,o=-1;break}}if(o!==-1){let d=n[o];d&&(r=o,s=e.col-d.startCol)}let i=Math.min(t,Math.max(1,n.length)),a=0;return n.length>i&&(a=Math.max(0,Math.min(n.length-i,r-(i-1))),r<a&&(a=r),r>=a+i&&(a=r-i+1)),{cursorVisualRow:r,cursorVisualCol:s,windowStart:a,rendered:i}}function FE(n,e){if(e.length===0)return[];if(!n.includes("\x1B")){let c=[],l=n.toLowerCase(),f=0;for(;f<l.length;){let u=l.indexOf(e,f);if(u===-1)break;c.push({start:u,end:u+e.length}),f=u+e.length}return c}let t="",r=[],s=[],o=0;for(;o<n.length;){let c=Cr(n,o);if(c!==null&&c.width===0){o+=c.text.length;continue}t+=n[o],r.push(o),s.push(o+1),o+=1}let i=[],a=t.toLowerCase(),d=0;for(;d<a.length;){let c=a.indexOf(e,d);if(c===-1)break;let l=c+e.length-1;i.push({start:r[c],end:s[l]}),d=c+e.length}return i}function e2(n,e,t,r,s=null,o=0,i=!1){if(e.length===0)return;if(r.length===0){Ls(n,e,t,i);return}let a=0;for(let d of FE(e,r)){if(d.start<a)continue;d.start>a&&Ls(n,e.slice(a,d.start),t,i);let c=s!==null&&d.start===s;Ls(n,_h(e.slice(d.start,d.end)),c?"search-highlight-active":"search-highlight",i),a=d.end}a<e.length&&Ls(n,e.slice(a),t,i)}function Ql(n){return cS(n)}function Ls(n,e,t,r=!1){if(e.length===0)return;let s=Ja(n),o=(r?lS(t,s):void 0)??Xa(t,s),i=o.transform?o.transform(e):e;s==="none"&&(i=i.replace(Pj,""));let a=d=>{d.length>0&&n.noFormat(d)};a(o.open),n.noFormat(i),o.inlineSgr&&Ej.test(i)&&a(Ur),a(o.close)}function t2(n,e){return e<=0?[n]:n.length===0?[""]:Tj(n,e,{hard:!0,trim:!1}).split(`
|
|
234
234
|
`)}function BE(n){NE=n}function DE(n,e,t){if(n==="wide")return!0;if(n==="narrow")return!1;if(t!==void 0)return t;let r=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!/^(ja|ko|zh)(_|\.|@|$)/i.test(r)}function xt(n){return OE(n,{ambiguousIsNarrow:!NE})}function n2(n,e){if(!n.startsWith("\x1B]8;",e))return null;for(let t=e+4;t<n.length;t++){if(n[t]==="\x07")return n.slice(e,t+1);if(n[t]==="\x1B"&&n[t+1]==="\\")return n.slice(e,t+2)}return null}function r2(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let s=n.charCodeAt(t);if(s<48||s>63)break;t+=1}for(;t<n.length;){let s=n.charCodeAt(t);if(s<32||s>47)break;t+=1}if(t>=n.length)return null;let r=n.charCodeAt(t);return r<64||r>126?null:n.slice(e,t+1)}function Cr(n,e){if(n.charCodeAt(e)===27){let t=n2(n,e);if(t!==null)return{text:t,width:0};let r=r2(n,e);return r!==null?{text:r,width:0}:null}return null}function Mh(n){let e=new Array(n.length+1).fill(0),t="",r=0;for(;r<n.length;){e[r]=t.length;let s=Cr(n,r);if(s){s.width>0&&(t+="^");for(let o=1;o<s.text.length;o++)e[r+o]=t.length;r+=s.text.length;continue}t+=n[r],r+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function s2(n){let{clean:e,rawToClean:t}=Mh(n),r=new Array(e.length+1).fill(n.length);for(let s=n.length;s>=0;s--){let o=t[s];o!==void 0&&(r[o]=s)}return r}function Qb(n,e,t){let r=0,s=e;for(;s<t;){let o=Cr(n,s);if(o){s+=o.text.length,o.width>0&&(r+=1);continue}r+=1,s+=1}return r}function Xb(n,e,t){let r=e;for(;t>0&&r<n.length;){let s=Cr(n,r);if(s){r+=s.text.length,s.width>0&&(t-=1);continue}r+=1,t-=1}return r}function _h(n){if(!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let r=Cr(n,t);if(r){r.width>0&&(e+="^"),t+=r.text.length;continue}e+=n[t],t+=1}return e}function o2(n){if(!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let r=Cr(n,t);if(r){if(r.width===0){let s=r.text.charCodeAt(0);(s===94||s===27&&r.text.charCodeAt(1)===91)&&(e+=r.text)}t+=r.text.length;continue}t+=1}return e}function HE(n){if(!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if(Cr(n,e))return!0;return!1}function PE(n,e){return n.indexOf("\x1B",e)}function*nk(n){let e=0;for(;e<n.length;){let t=Cr(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let r=n.length,s=PE(n,e);for(;s!==-1&&s<n.length;){if(Cr(n,s)){r=s;break}s=PE(n,s+1)}if(r===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:o}of tk.segment(n.slice(e,r)))yield{text:o,width:xt(o)};e=r}}function i2(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let r=t.escapeAware===!0&&HE(n);return!r&&!LE.test(n)?a2(n,e):d2(n,e,r)}function a2(n,e){let t=[],r=n;for(;r.length>e;){let s=r.slice(0,e+1),o=-1;for(let i=Math.min(e,s.length-1);i>=0;i--)if(s[i]===" "){o=i;break}o<=0?(t.push(r.slice(0,e)),r=r.slice(e)):(t.push(r.slice(0,o)),r=r.slice(o+1))}return t.push(r),t}function d2(n,e,t){let r=[],s=t?[...nk(n)]:c2(n),o=0;for(;o<s.length;){let i="",a=0,d=-1,c="";for(;o<s.length;){let l=s[o];if(a+l.width>e){l.text===" "&&l.width===1&&(d=o,c=i);break}l.text===" "&&l.width===1&&(d=o,c=i),i+=l.text,a+=l.width,o+=1}if(o>=s.length){r.push(i);break}d>=0?(r.push(c),o=d+1):i.length===0?(r.push(s[o].text),o+=1):r.push(i)}return r}function c2(n){let e=[];for(let{segment:t}of tk.segment(n))e.push({text:t,width:xt(t)});return e}function Zt(n,e,t={}){if(e<=0)return"";let r=t.escapeAware===!0&&HE(n);if(!r&&n.length<=e&&!LE.test(n))return n;if(!r)return xt(n)<=e?n:e<=1?ek(n,e):ek(n,e-1)+"\u2026";let s=[...nk(n)],o=0;for(let i of s)o+=i.width;return o<=e?n:e<=1?ME(s,e):ME(s,e-1)+"\u2026"}function ek(n,e){if(e<=0)return"";let t="",r=0;for(let{segment:s}of tk.segment(n)){let o=xt(s);if(r+o>e)break;t+=s,r+=o}return t}function ME(n,e){if(e<=0)return"";let t="",r=0;for(let s of n){if(r+s.width>e)break;t+=s.text,r+=s.width}return t}function l2(n,e,t){if(n<=t||t<=0)return 0;let r=Math.floor((t-1)/2);return Math.max(0,Math.min(e-r,n-t))}function u2(n,e,t,r){if(e<=r||r<=0)return 0;let s=e-r,o=Math.max(0,Math.min(n,s));return t<o?o=t:t>o+r-1&&(o=t-r+1),Math.max(0,Math.min(o,s))}function Zb(n,e){let t=Math.max(0,e-1),r=[],s=" \xB7 ",o="";for(let i of n){let a=o.length===0?i.label:`${s}${i.label}`;if(1+xt(o)+xt(a)>t)break;let d=1+xt(o)+xt(a)-xt(i.label)+1;o+=a,i.action!==void 0&&r.push({start:d,end:d+xt(i.label)-1,action:i.action})}return{text:o,spans:r}}function _E(n,e,t,r){let s=Math.max(0,e-1),o=n.rows.length>1,i=o?Math.max(...n.rows.map((c,l)=>`${l+1}. `.length)):0,a=Math.max(0,...n.rows.map(c=>xt(c.kind==="text"?`${c.label} `:c.label))),d=[];for(let c=t;c<Math.min(n.rows.length,t+r);c++){let l=n.rows[c];if(!l)continue;let f=c===n.selectedIndex,u=f?"\u276F":" ",p=o?`${c+1}. `.padStart(i):"";if(l.kind==="text"){let b=Zt(` ${u} ${p}${l.label} `,s),{field:S,caretOffset:C,fieldStart:I}=h2(l.text,l.cursor,s-xt(b));d.push({kind:"text",index:c,selected:f,body:"",prefix:b,field:S,fieldStart:I,caretCol:1+xt(b)+C,sig:`form|r|${e}|${c}|${f?1:0}|text|${b}|${S}`});continue}let m=` ${u} ${p}`,h=l.kind==="choice"?l.current===!0?"\u2022 ":" ":"",y=l.kind==="select"?l.value:l.note??"",w=y.length>0?`${h}${p2(l.label,a)} ${y}`:`${h}${l.label}`,k=`${m}${Zt(w,s-xt(m))}`;d.push({kind:l.kind,index:c,selected:f,body:k,prefix:"",field:"",fieldStart:0,caretCol:1,sig:`form|r|${e}|${c}|${f?1:0}|${l.kind}|${k}`})}return d}function p2(n,e){let t=e-xt(n);return t>0?n+" ".repeat(t):n}function h2(n,e,t){if(t<=0)return{field:"",caretOffset:0,fieldStart:0};let r=Math.max(0,Math.min(e,n.length));if(xt(n)+1<=t)return{field:n,caretOffset:xt(n.slice(0,r)),fieldStart:0};let s=r,o=1;for(;s>0;){let i=xt(n[s-1]??"");if(o+i>t)break;o+=i,s-=1}return{field:ek(n.slice(s),t),caretOffset:xt(n.slice(s,r)),fieldStart:s}}function m2(n){let e=n.indexOf(`
|
|
235
|
-
`);return e===-1?n:`${n.slice(0,e)} \u21B5`}function Oh(n){switch(n){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_P":case"META_P":return"alt-p";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function zo(){let n=[Ur,Hd,Ud,UR,Wd,WR,Nw,so,Vi,Ji,Gi,Ki,"\x1B>",Rl,zp,Kp,vE,"\x1B]9;4;0\x07",LR].join("");try{ge(n)}catch{}}function UE(n){let e=[["width",80],["height",24]];for(let[t,r]of e){let s=Object.getOwnPropertyDescriptor(n,t);if(s&&s.get)continue;let o=Symbol(`raw-${t}`),i=n;i[o]=s?s.value:void 0,Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){let a=this[o];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:r},set(a){this[o]=a}})}}function $E(n,e){let t={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===112||n===80?"alt-p":n===95?"alt-underscore":null:null}var Ej,Pj,Jl,Eh,Mj,Ph,AE,Wb,jb,_j,RE,$j,Tt,Nt,Oj,Bt,qb,TE,Fj,Yl,zb,Lj,Nj,Kb,Bj,Dj,EE,Hj,Uj,Wj,jj,Gb,Vb,Jb,qj,zj,Kj,Gj,Vj,Jj,$h,LE,tk,NE,f2,g2,rk=j(()=>{"use strict";wb();bh();RT();kh();TT();ot();qT();Eb();ve();yr();fh();_b();Lb();no();cE();mh();uE();pE();Nb();gn();Ub();Si();bi();Yi();Ej=/\x1b\[[0-9;]*m/,Pj=/\x1b\[[0-9;]*m/g,Jl=500,Eh=1,Mj=700,Ph=/[A-Za-z0-9_:\-]/,AE=/[:\-]/,Wb=/[A-Za-z0-9_./\-~+@]/,jb=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,_j=/[.,;:!?)\]}'"]/,RE=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,$j=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Tt=1,Nt=0,Oj=1,Bt=1,qb=8,TE=20,Fj=36,Yl=2,zb=1,Lj=80,Nj=12,Kb=5,Bj=12,Dj=12,EE=350,Hj=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"1-9 quick-pick"}],Uj=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"y/n quick-pick"}],Wj=3,jj=30,Gb=6,Vb=4,Jb=2,qj=1e3,zj=1e4,Kj=30,Gj=.45,Vj=2,Jj=/^(https?|ftp):\/\/\S+$/;$h=class n{term;dispatcher;onKey;onSidebarCollapseChange;onBlockClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;onLayoutChange;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;sidebarVisible=!1;sidebarConfiguredWidth=null;sidebarRenderer=new Ih;sidebarBorder="frame";sidebarSnapshot=UT();sidebarRowPaths=new Map;sidebarRowDoubleActions=new Map;sidebarRowActions=new Map;sidebarPages={};sidebarCollapsed=new Set;lastSidebarClick=null;sidebarScrollOffset=0;sidebarOverflowRows=0;permissionPrompt=null;formPrompt=null;formRowHits=new Map;formHintHits=[];formRegion=null;formPressHit=null;formWindowTop=0;formWindowKey=null;permissionRowHits=new Map;permissionHintHits=[];permissionRegion=null;permissionPressHit=null;permissionArmedAt=0;confirmPrompt=null;compactionPrompt=null;compactionRowHits=new Map;compactionHintHits=[];compactionRegion=null;compactionPressHit=null;compactionArmedAt=0;helpRegion=null;helpPressed=!1;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;slideTarget=0;slideTimer=null;slideEnabled;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;workspaceIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayScroll=0;btwOverlayRegion=null;btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:xb,queued:0};barHits=new Map;hoveredBarHit=null;composerBottomRow=null;hintZoneStart=null;hintHoverReveal=!1;hintHoverHideTimer=null;hintKeyReveal=!1;barPressHit=null;lastBarClick=null;onBarAction;onFormClick;onPermissionClick;onCompactionClick;onHelpClick;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};barConfig={composer:{top:{left:fi,right:pi},bottom:{left:$a,right:Oa}},sessionbar:{left:Fa,right:La}};lastWindowTitle=null;lastReportedCwd=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;openFileForeground;runForeground;foregroundChildActive=!1;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=o=>{this.selection!==null&&o.length>0&&this.clearSelection(),t(o)},this.onBlockClick=e.onBlockClick,this.onSidebarCollapseChange=e.onSidebarCollapseChange,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onBarAction=e.onBarAction,this.onFormClick=e.onFormClick,this.onPermissionClick=e.onPermissionClick,this.onCompactionClick=e.onCompactionClick,this.onHelpClick=e.onHelpClick,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.onLayoutChange=e.onLayoutChange,this.contentRepaintThrottleMs=e.repaintThrottleMs??qj,this.painter=new Qd(this.term),this.scheduler=new gh({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??zj,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let r=e.openFileCommand,s=typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):r;this.openFileCommand=s&&s.length>0?s:null,this.openFileForeground=e.openFileInTerminal??e.openFileSource==="env",this.runForeground=e.runForeground??lE,this.progressIndicatorEnabled=e.progressIndicator??!0,this.slideEnabled=e.turnSlide??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>{this.painter.clearCache(),this.sidebarRenderer.invalidate(),this.onLayoutChange?.(),this.repaint()},this.keyHandler=(o,i,a)=>this.handleKey(o,a),this.mouseHandler=(o,i)=>this.handleMouse(o,i),this.rawStdinHandler=o=>this.handleRawStdin(o)}start(e={}){this.started||(this.started=!0,Mb(!1),e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,ge(Lw),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),he({src:"grab",site:"screen.start",on:!0}),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(Mb(!0),this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.cancelHintHoverHide(),this.cancelSlide(),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),he({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(ge(Kp),this.currentPointerShape="default"),e.keepFullscreen||ge(Rl),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(zo(),this.term.fullscreen(!1),this.term(`
|
|
235
|
+
`);return e===-1?n:`${n.slice(0,e)} \u21B5`}function Oh(n){switch(n){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_P":case"META_P":return"alt-p";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function zo(){let n=[Ur,Hd,Ud,UR,Wd,WR,Nw,so,Vi,Ji,Gi,Ki,"\x1B>",Rl,zp,Kp,vE,"\x1B]9;4;0\x07",LR].join("");try{ge(n)}catch{}}function UE(n){let e=[["width",80],["height",24]];for(let[t,r]of e){let s=Object.getOwnPropertyDescriptor(n,t);if(s&&s.get)continue;let o=Symbol(`raw-${t}`),i=n;i[o]=s?s.value:void 0,Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){let a=this[o];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:r},set(a){this[o]=a}})}}function $E(n,e){let t={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===112||n===80?"alt-p":n===95?"alt-underscore":null:null}var Ej,Pj,Jl,Eh,Mj,Ph,AE,Wb,jb,_j,RE,$j,Tt,Nt,Oj,Bt,qb,TE,Fj,Yl,zb,Lj,Nj,Kb,Bj,Dj,EE,Hj,Uj,Wj,jj,Gb,Vb,Jb,qj,zj,Kj,Gj,Vj,Jj,$h,LE,tk,NE,f2,g2,rk=j(()=>{"use strict";wb();bh();RT();kh();TT();ot();qT();Eb();ve();yr();fh();_b();Lb();no();cE();mh();uE();pE();Nb();gn();Ub();Si();bi();Yi();Ej=/\x1b\[[0-9;]*m/,Pj=/\x1b\[[0-9;]*m/g,Jl=500,Eh=1,Mj=700,Ph=/[A-Za-z0-9_:\-]/,AE=/[:\-]/,Wb=/[A-Za-z0-9_./\-~+@]/,jb=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,_j=/[.,;:!?)\]}'"]/,RE=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,$j=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Tt=1,Nt=0,Oj=1,Bt=1,qb=8,TE=20,Fj=36,Yl=2,zb=1,Lj=80,Nj=12,Kb=5,Bj=12,Dj=12,EE=350,Hj=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"1-9 quick-pick"}],Uj=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"y/n quick-pick"}],Wj=3,jj=30,Gb=6,Vb=4,Jb=2,qj=1e3,zj=1e4,Kj=30,Gj=.45,Vj=2,Jj=/^(https?|ftp):\/\/\S+$/;$h=class n{term;dispatcher;onKey;onSidebarCollapseChange;onBlockClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;onLayoutChange;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;sidebarVisible=!1;sidebarConfiguredWidth=null;sidebarRenderer=new Ih;sidebarBorder="frame";sidebarSnapshot=UT();sidebarRowPaths=new Map;sidebarRowDoubleActions=new Map;sidebarRowActions=new Map;sidebarPages={};sidebarCollapsed=new Set;lastSidebarClick=null;sidebarScrollOffset=0;sidebarOverflowRows=0;permissionPrompt=null;formPrompt=null;formRowHits=new Map;formHintHits=[];formRegion=null;formPressHit=null;formWindowTop=0;formWindowKey=null;permissionRowHits=new Map;permissionHintHits=[];permissionRegion=null;permissionPressHit=null;permissionArmedAt=0;confirmPrompt=null;compactionPrompt=null;compactionRowHits=new Map;compactionHintHits=[];compactionRegion=null;compactionPressHit=null;compactionArmedAt=0;helpRegion=null;helpPressed=!1;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;slideTarget=0;slideTimer=null;slideEnabled;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;workspaceIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayScroll=0;btwOverlayRegion=null;btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:xb,queued:0};barHits=new Map;hoveredBarHit=null;composerBottomRow=null;hintZoneStart=null;hintHoverReveal=!1;hintHoverHideTimer=null;hintKeyReveal=!1;barPressHit=null;lastBarClick=null;onBarAction;onFormClick;onPermissionClick;onCompactionClick;onHelpClick;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};barConfig={composer:{top:{left:fi,right:pi},bottom:{left:$a,right:Oa}},sessionbar:{left:Fa,right:La}};lastWindowTitle=null;lastReportedCwd=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;selectionGranularity="char";selectionAnchorWordBounds=null;selectionAnchorLineId=null;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;openFileForeground;runForeground;foregroundChildActive=!1;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=o=>{this.selection!==null&&o.length>0&&this.clearSelection(),t(o)},this.onBlockClick=e.onBlockClick,this.onSidebarCollapseChange=e.onSidebarCollapseChange,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onBarAction=e.onBarAction,this.onFormClick=e.onFormClick,this.onPermissionClick=e.onPermissionClick,this.onCompactionClick=e.onCompactionClick,this.onHelpClick=e.onHelpClick,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.onLayoutChange=e.onLayoutChange,this.contentRepaintThrottleMs=e.repaintThrottleMs??qj,this.painter=new Qd(this.term),this.scheduler=new gh({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??zj,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let r=e.openFileCommand,s=typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):r;this.openFileCommand=s&&s.length>0?s:null,this.openFileForeground=e.openFileInTerminal??e.openFileSource==="env",this.runForeground=e.runForeground??lE,this.progressIndicatorEnabled=e.progressIndicator??!0,this.slideEnabled=e.turnSlide??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>{this.painter.clearCache(),this.sidebarRenderer.invalidate(),this.onLayoutChange?.(),this.repaint()},this.keyHandler=(o,i,a)=>this.handleKey(o,a),this.mouseHandler=(o,i)=>this.handleMouse(o,i),this.rawStdinHandler=o=>this.handleRawStdin(o)}start(e={}){this.started||(this.started=!0,Mb(!1),e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,ge(Lw),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),he({src:"grab",site:"screen.start",on:!0}),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(Mb(!0),this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.cancelHintHoverHide(),this.cancelSlide(),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),he({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(ge(Kp),this.currentPointerShape="default"),e.keepFullscreen||ge(Rl),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(zo(),this.term.fullscreen(!1),this.term(`
|
|
236
236
|
`)))}installBracketedPaste(){ge(qp),ge(DR),ge(HR),ge(BR),ge(Gp);let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){ge(so),ge(Vi),ge(Ji),ge(Gi),ge(Tl),ge(Ki),ge("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,ge(jR),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(ge(Nw),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>zo(),this.onProcessSignal=e=>{zo(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{zo(),process.stderr.write(`
|
|
237
237
|
uncaught: ${e.stack??e.message}
|
|
238
238
|
`),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,ge(qR),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let t=/\x1b\[<(64|65);\d+;\d+M/g,r="",s=0,o;for(;(o=t.exec(e))!==null;)r+=e.slice(s,o.index),o[1]==="64"?this.scrollBy(3):this.scrollBy(-3),s=o.index+o[0].length;return r+=e.slice(s),r}handleRawStdin(e){if(process.env.HYDRA_TUI_KEY_TRACE){let r=Array.from(e).map(s=>"0x"+s.toString(16).padStart(2,"0")).join(" ");he({tag:"raw",bytes:r,len:e.length})}let t=e.toString("binary");if(t=this.consumeSelectiveMouseSequences(t),t.includes("\x1B[I")||t.includes("\x1B[O")){let r=this.terminalFocused;for(;;){let s=t.indexOf("\x1B[I"),o=t.indexOf("\x1B[O"),i=s===-1?o:o===-1?s:Math.min(s,o);if(i===-1)break;let a=i===s;this.terminalFocused=a,a&&(this.lastFocusInAt=Date.now()),t=t.slice(0,i)+t.slice(i+"\x1B[I".length)}this.terminalFocused!==r&&this.scheduleRepaint()}if(t.length!==0){if(this.pasteActive){this.handleRawStdinSegment(t);return}if(t===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(t==="\x1B[27;5;122~"||t==="\x1B[122;5u")){this.onSuspend();return}if(t===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(t==="\x1B"||t==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(t==="\x1B\x7F"||t==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(t.startsWith("\x1B\x7F")||t.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(t.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(t)){this.handleCsi27Stdin(t);return}if(t.includes(Dd)){this.handleRawStdinSegment(t);return}if(t.includes(`
|
|
@@ -240,7 +240,7 @@ uncaught: ${e.stack??e.message}
|
|
|
240
240
|
`);if(r.filter(o=>o.length>0).length>1){this.onKey([{type:"paste",text:t.replace(/\r/g,"")}]);return}for(let o=0;o<r.length;o++)r[o].length>0&&this.handleRawStdin(Buffer.from(r[o],"binary")),o<r.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(t.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(t)){this.handleCsiUStdin(t);return}this.handleRawStdinSegment(t)}}handleCsi27Stdin(e){let t=/\x1b\[27;(\d+);(\d+)~/g,r=0,s;for(;(s=t.exec(e))!==null;){s.index>r&&this.handleRawStdin(Buffer.from(e.slice(r,s.index),"binary"));let o=parseInt(s[1],10),i=parseInt(s[2],10),a=$E(i,o);a!==null?this.onKey([{type:"key",name:a}]):(o===1||o===2)&&i>=32&&i<127&&this.handleRawStdinSegment(String.fromCharCode(i)),r=s.index+s[0].length}r<e.length&&this.handleRawStdin(Buffer.from(e.slice(r),"binary"))}handleCsiUStdin(e){let t=/\x1b\[(\d+)(?:;(\d+))?u/g,r=0,s;for(;(s=t.exec(e))!==null;){s.index>r&&this.handleRawStdin(Buffer.from(e.slice(r,s.index),"binary"));let o=parseInt(s[1],10),i=s[2]!==void 0?parseInt(s[2],10):1,a=$E(o,i);a!==null&&this.onKey([{type:"key",name:a}]),r=s.index+s[0].length}r<e.length&&this.handleRawStdin(Buffer.from(e.slice(r),"binary"))}handleRawStdinSegment(e){let t=Dd,r=Al;for(;e.length>0;){if(this.pasteActive){let o=e.indexOf(r);if(o===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,o),e=e.slice(o+r.length),this.pasteActive=!1;let i=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
|
|
241
241
|
`);this.pasteBuffer="";let a=uT(i);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:i}]);continue}let s=e.indexOf(t);if(s===-1){let o=Yj(e);o!==null?this.onKey([{type:"paste",text:o}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}s>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,s),"binary")),e=e.slice(s+t.length),this.pasteActive=!0}}width(){return this.contentWidth()}termWidth(){return this.term.width||0}sidebarReserved(){if(!this.sidebarVisible)return 0;let e=this.term.width||0;if(e<Lj)return 0;let t=this.sidebarConfiguredWidth??Math.min(Fj,Math.max(TE,Math.floor(e*.28))),r=e-Nj-Yl-zb;return Math.min(t,Math.max(TE,r))+Yl+zb}sidebarOverlay(){let e=this.sidebarReserved();return e>0&&e*2>(this.term.width||0)}sidebarColumnStart(){let e=this.sidebarReserved();return e===0?0:(this.term.width||0)-e+1}contentWidth(){let e=this.term.width||0;return this.sidebarOverlay()?e:Math.max(0,e-this.sidebarReserved())}transcriptVisibleWidth(){let e=this.sidebarColumnStart();return e===0?this.contentWidth():e-1}sidebarBodyWidth(){let e=this.sidebarReserved();return e===0?0:e-Yl-zb}isSidebarVisible(){return this.sidebarVisible}isSidebarSuppressed(){return this.sidebarVisible&&this.sidebarReserved()===0}isSidebarOverlay(){return this.sidebarOverlay()}setSidebarVisible(e){this.sidebarVisible!==e&&(this.sidebarVisible=e,this.lastSidebarClick=null,this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarPages={},this.sidebarScrollOffset=0,this.sidebarOverflowRows=0,this.sidebarRenderer.invalidate(),this.painter.clearCache())}toggleSidebar(){return this.setSidebarVisible(!this.sidebarVisible),this.sidebarVisible}setSidebarGadgets(e){this.sidebarRenderer.setGadgets(e),this.scheduleRepaint()}isSidebarGadgetConfigured(e){return this.sidebarRenderer.isConfigured(e)}isSidebarGadgetActive(e){return this.sidebarRenderer.isConfigured(e)&&!this.sidebarCollapsed.has(e)}toggleSidebarGadgetCollapsed(e){let t=!this.sidebarCollapsed.has(e);return t?this.sidebarCollapsed.add(e):this.sidebarCollapsed.delete(e),this.sidebarRenderer.invalidate(),this.onSidebarCollapseChange?.(e,t),t}setSidebarCollapsed(e){this.sidebarCollapsed=new Set(e),this.sidebarRenderer.invalidate()}sidebarCollapsedIds(){return[...this.sidebarCollapsed]}setSidebarBorder(e){this.sidebarBorder!==e&&(this.sidebarBorder=e,this.sidebarRenderer.invalidate(),this.painter.clearCache(),this.scheduleRepaint())}setSidebarWidth(e){this.sidebarConfiguredWidth=e,this.painter.clearCache()}setSidebarSnapshot(e){this.sidebarSnapshot={...this.sidebarSnapshot,...e},this.sidebarVisible&&this.scheduleRepaint()}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.cancelSlide(!0),this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let t=this.contentWidth();return this.wrapCacheWidth!==t&&(this.wrapCache.clear(),this.wrapCacheWidth=t),this.wrapOne(e,t).length}wrappedRowsOfMany(e){let t=0;for(let r of e)t+=this.wrappedRowsOf(r);return t}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let t of e)this.trackLine(t)}forgetLine(e){let t=this.lineIds.get(e);t!==void 0&&this.wrapCache.delete(t)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let t=this.lines.splice(0,e);for(let r of t)this.forgetLine(r);this.invalidateSelectionIfTouches(t);for(let[r,s]of[...this.keyedBlocks.entries()])s.start-=e,s.start<0&&this.keyedBlocks.delete(r)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let i of t)i.blockKey=e;let r=this.keyedBlocks.get(e),s=!1,o=0;if(r){let i=r.start+r.count;s=i>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(r.start,i)),d=t.length-r.count,c=this.lines.slice(r.start,i),l=new Array(t.length),f=[];for(let u=0;u<t.length;u++){let p=c[u],m=t[u];p!==void 0&&Zj(p,m)?l[u]=p:(p!==void 0&&f.push(p),l[u]=m)}for(let u=t.length;u<c.length;u++)f.push(c[u]);this.lines.splice(r.start,r.count,...l);for(let u of f)this.forgetLine(u);for(let u of l)this.lineIds.has(u)||this.trackLine(u);if(this.invalidateSelectionIfTouches(f),r.count=t.length,d!==0)for(let[u,p]of this.keyedBlocks)u!==e&&p.start>r.start&&(p.start+=d);o=this.wrappedRowsOfMany(t)-a}else s=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),o=this.wrappedRowsOfMany(t);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(o),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,r,s){if(e.length===0)return;let o=e.split(`
|
|
242
242
|
`),[i,...a]=o,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=i??"",d+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:t,body:i??"",bodyStyle:r};s!==void 0&&(l.prefixStyle=s),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(t.length);for(let l of a){let f={prefix:c,body:l,bodyStyle:r};this.lines.push(f),this.trackLine(f),d+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setBarConfig(e){this.barConfig=AT(e),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.syncReportedCwd(),YT({sessionId:this.sessionbar.sessionId,agent:this.sessionbar.agent,title:this.sessionbar.title,model:this.sessionbar.model,costAmount:this.sessionbar.usage?.costAmount,cwd:this.sessionbar.cwd}),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=g2(this.sessionbar.sessionId)||"hydra",r=e&&e.length>0?e:t,o=(this.readonly?`${r} [VIEW ONLY]`:r).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);o!==this.lastWindowTitle&&(this.lastWindowTitle=o,ge(`\x1B]0;${o}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,ge("\x1B]0;\x1B\\")}syncReportedCwd(){let e=this.sessionbar.cwd?.trim();e&&e!==this.lastReportedCwd&&(this.lastReportedCwd=e,Ob(e))}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),QT({status:this.banner.status,queued:this.banner.queued}),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&at(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}sessionTitle(){return this.sessionbar.title}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setWorkspaceIndicator(e){this.workspaceIndicator!==e&&(this.workspaceIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),he({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,t){let r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.sourceLineId),o=r<s||r===s&&e.offset<=t.offset,i=o?e:t,a=o?t:e;if(i.sourceLineId===a.sourceLineId&&i.offset===a.offset){this.clearSelection();return}let d={startLineId:i.sourceLineId,startOffset:i.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}farEndpointFrom(e){if(this.selection===null)return null;let t=this.selection,r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.startLineId),o=this.lineIndexById(t.endLineId);if(r<0||s<0||o<0)return null;let i=(f,u,p,m)=>f!==p?f-p:u-m,a=i(r,e.offset,s,t.startOffset),d=i(r,e.offset,o,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(d>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let c=Math.abs(r-s)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(r-o)*1e6+Math.abs(e.offset-t.endOffset)>=c?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];for(let r=e.loIdx;r<=e.hiIdx;r++){let s=this.lines[r];if(!s)continue;let o=this.lineIds.get(s),i=o===void 0?void 0:e.byId.get(o);if(!i)continue;let d=(s.body??"").slice(i.start,i.end);(Ql(s.bodyStyle)||s.ansi)&&(d=_h(d)),t.push(d)}return t.join(`
|
|
243
|
-
`)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),r=this.lineIndexById(e.endLineId);if(t===-1||r===-1)return null;let s=t,o=r,i=e.startOffset,a=e.endOffset;t>r&&(s=r,o=t,i=e.endOffset,a=e.startOffset);let d=new Map,c=-1;for(let l=o;l>=s;l--){let f=this.lines[l];if(f&&!this.isHiddenLine(f)){c=l;break}}for(let l=s;l<=o;l++){let f=this.lines[l];if(!f||this.isHiddenLine(f))continue;let u=this.lineIds.get(f);if(u===void 0)continue;let p=(f.body??"").length,m=l===s?Math.max(0,Math.min(p,i)):0,h=l===o?Math.max(0,Math.min(p,a)):p;d.set(u,{start:m,end:h,toEnd:l<c})}return{loIdx:s,hiIdx:o,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let r=this.wrapOrigin.get(e);if(!r)return null;let s=t.get(r.sourceLineId);if(!s)return null;let o=r.sourceColOffset,i=r.bodyDisplayShift??0,a=r.sourceColEnd??o+e.body.length-i,d=Math.max(s.start,o),c=Math.min(s.end,a);if(c<=d)return null;let l,f;if(r.sourceColEnd!==void 0){let u=this.sourceBodyForId(r.sourceLineId);if(u===null)return null;let p=Qb(u,o,d),m=Qb(u,d,c);l=Xb(e.body,i,p),f=Xb(e.body,l,m)}else l=d-o+i,f=c-o+i;return{start:l,end:f,toEndOfLine:s.toEnd||s.end>a}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.lines[t]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.workspaceIndicator!==null?{text:this.workspaceIndicator,kind:"workspace"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let t of e){let r=this.lineIds.get(t);if(r!==void 0&&(r===this.selection.startLineId||r===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count,s=r>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(t.start,r)),i=this.lines.splice(t.start,t.count);for(let a of i)this.forgetLine(a);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-o),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let t=e.start+e.count;if(t>=this.lines.length)return;let r=this.lines.splice(e.start,e.count);for(let[s,o]of this.keyedBlocks)s!==this.stickyBottomKey&&o.start>=t&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...r),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count>=this.lines.length,s=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),o=this.lines.splice(t.start,t.count);for(let i of o)this.forgetLine(i);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>t.start&&(i.start-=t.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-s),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let r=[...t].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),s=r.findIndex(d=>d.key===e);if(s<0)return[];let o=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!t.has(l)&&f.start>=d&&f.start<c)return!0;return!1},i=s;for(;i>0&&!o(r[i-1].start+r[i-1].count,r[i].start);)i--;let a=s;for(;a<r.length-1&&!o(r[a].start+r[a].count,r[a+1].start);)a++;return r.slice(i,a+1).map(d=>d.key)}setRunCollapsed(e,t,r){if(e.length===0)return;let s=e[0];if(!this.keyedBlocks.has(s))return;this.upsertLines(s,r);let o=this.keyedBlocks.get(s),i=o.start+o.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(i=Math.max(i,d.start+d.count))}for(let a=o.start+o.count;a<i;a++){let d=this.lines[a];d&&(d.collapsed=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,ge(Lw),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&(this.clearSelection(),this.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),ZT(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(t=>({...t}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&(this.clearSelection(),this.compactionArmedAt=Date.now()),this.compactionPrompt=e?{...e}:null,e===null&&(this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion=null,this.compactionPressHit=null),this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,e===null&&(this.helpRegion=null,this.helpPressed=!1),this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlayScroll=0,this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!0),e.usage!==void 0){let r=this.btwOverlayUsage,s=e.usage;(!r||r.used!==s.used||r.size!==s.size||r.costAmount!==s.costAmount||r.costCurrency!==s.costCurrency)&&(this.btwOverlayUsage={...s},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let r=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){r=!1;break}if(r)return}let t=this.btwOverlayLines.length;if(this.btwOverlayLines=[...e],this.btwOverlayScroll>0&&e.length>t){let r=this.term.width,s=0;for(let o=t;o<this.btwOverlayLines.length;o++)s+=r>4?this.wrapOne(this.btwOverlayLines[o],r).length:1;this.btwOverlayScroll+=s}this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,r=this.btwOverlayStatus===e.style;t&&r||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayRegion=null,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((r,s)=>{let o=this.completions[s];return o!==void 0&&o.name===r.name&&o.description===r.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,r=t!==void 0&&t.start+t.count===this.lines.length,s=r?t.start-1:this.lines.length-1;if(s<0)return;let o=this.lines[s];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),r?(this.lines.splice(t.start,0,i),t.start+=1):this.lines.push(i),this.trackLine(i),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(i)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,t){if(process.env.HYDRA_TUI_KEY_TRACE&&he({tag:"key",name:e,isChar:!!t.isCharacter}),t.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.scrollToNextTurn();return}let r=Oh(e);if(r){this.onKey([{type:"key",name:r}]);return}e.startsWith("CTRL_")&&this.revealHints()}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let f=e==="MOUSE_WHEEL_UP"?3:-3,u=this.mouseCell(t);if(u!==null&&this.isFormCell(u.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(u!==null&&this.isCompactionCell(u.y)){this.stepCompactionCursor(e==="MOUSE_WHEEL_UP"?-1:1);return}if(u!==null&&this.isSidebarCell(u.x,u.y)&&this.scrollSidebarBy(f)||u!==null&&this.isBtwOverlayCell(u.y)&&this.scrollBtwOverlayBy(f))return;this.scrollBy(f);return}let s=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||s)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let i=this.mouseCell(t),a=Xj(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&i!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:i.x,y:i.y,name:e});let c=i!==null?this.barHitAt(i.x,i.y):null;if(d==="move"){let f=c?.id??null,u=i!==null&&i.y===this.composerBottomRow&&this.hintZoneStart!==null&&i.x>=this.hintZoneStart,p=this.trackHintHover(u);if((f!==this.hoveredBarHit||p)&&(this.hoveredBarHit=f,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),i!==null&&this.isPermissionCell(i.y)){let m=this.permissionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.permissionPrompt!==null&&m.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isCompactionCell(i.y)){let m=this.compactionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.compactionPrompt!==null&&m.index!==this.compactionPrompt.selectedIndex&&this.onCompactionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isFormCell(i.y)){let m=this.formHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="row"&&this.formPrompt!==null&&m.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:m.row,select:!0})}}let l=i!==null&&c===null&&this.barHits.get(i.y)===void 0&&i.x>=1&&i.x<=this.transcriptVisibleWidth();if(i!==null&&l&&d!=="release"){let f=this.keyAndSubAtRow(i.y),u=f!==null&&f.key.startsWith("agent:")?null:f;if(u===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(i.y),m=this.nearestKeyBelowRow(i.y);p!==null&&m!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(m)&&(u={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(u!==null?"pointer":"default"),d==="move"){let p=u?.key??null,m=u?.sub??null;(p!==this.hoveredBlockKey||m!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=m,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(i!==null&&!l&&this.setPointerShape("default"),(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback())));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let f=this.lastLeftClick;if(f!==null&&i!==null&&Math.abs(i.x-f.x)<=Eh&&Math.abs(i.y-f.y)<=Eh&&Date.now()-f.t<=Jl||this.flushPendingBlockClick(),i!==null&&this.handleBarPress(i)){this.pressCell=null;return}if(i!==null&&this.handlePermissionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleCompactionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleHelpPress(i)){this.pressCell=null;return}if(i!==null&&this.handleFormPress(i)){this.pressCell=null;return}if(this.handleSidebarPress(i)){this.pressCell=null,this.clearSelection();return}this.pressCell=i,this.handleSelectionPress(i,Qj(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&i!==null&&this.extendSelectionByClick(i))){if(e==="MOUSE_DRAG"&&i!==null){this.handleSelectionDrag(i);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){if(this.handleBarRelease(i)){this.pressCell=null;return}if(this.handlePermissionRelease(i)){this.pressCell=null;return}if(this.handleCompactionRelease(i)){this.pressCell=null;return}if(this.handleHelpRelease(i)){this.pressCell=null;return}if(this.handleFormRelease(i)){this.pressCell=null;return}let f=this.pressCell;this.pressCell=null;let u=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(f!==null&&i!==null&&i.x===f.x&&i.y===f.y&&!u&&this.onBlockClick){let p=this.keyAndSubAtRow(i.y),m=p?.key??null;if(m!==null){let h=i.y;for(;h>1&&this.keyAtRow(h-1)===m;)h-=1;this.schedulePendingBlockClick(m,i.y-h,p?.sub??null)}}(i===null||!this.isSidebarCell(i.x,i.y))&&this.handleSelectionRelease(i)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let r=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(r===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(r)){this.lastLeftClick=null;return}this.selectionAnchor=r;let s=Date.now(),o=this.lastLeftClick,i=o!==null&&s-o.t<=Jl&&Math.abs(e.x-o.x)<=Eh&&Math.abs(e.y-o.y)<=Eh&&o.sourceLineId!==null&&o.sourceLineId===r.sourceLineId;if(i&&o.count===2&&e.x===o.x&&e.y===o.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(r.sourceLineId),this.doubleClickPending=!0;return}if(i&&o.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(r,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(r);c!==null&&(this.setSelection({sourceLineId:r.sourceLineId,offset:c.start},{sourceLineId:r.sourceLineId,offset:c.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let r=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:r})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let r=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return r===null?!1:this.extendSelectionByClickResolved(r)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let r=this.contentWidth(),{rows:s}=this.wrapTail(r,t+this.scrollOffset),o=s.length-this.scrollOffset,i=Math.max(0,o-t),a=s.slice(i,o),d=Math.max(0,t-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=c<d;if(c===0&&l||u){let p=this.lines[0];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:0}}}if(c>=t-1&&f){let p=this.lines[this.lines.length-1];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let r=this.scrollbackVisibleRows();if(r<=0)return null;let s=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let o=1;o<r;o++){let i=t-o;if(i>=1){let d=this.resolveCellToSource(s,i);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+o;if(a<=r){let d=this.resolveCellToSource(s,a);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let r=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===r){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,r=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let s=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:s?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||r){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Mh(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length,a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!Ph.test(s[a])&&!jb.test(s[a]))return null;let d=a;for(;d>0&&jb.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&jb.test(s[c]);)c++;for(;c>d+1&&_j.test(s[c-1]);)c--;if(s.slice(d,c).includes("://")){let p=d,m=c;return this.projectCleanRangeToRaw(o,r.length,p,m)}if(!Ph.test(s[a]))return null;let f=a;for(;f>0&&Ph.test(s[f-1]);)f--;let u=a+1;for(;u<s.length&&Ph.test(s[u]);)u++;for(;u>f+1&&AE.test(s[u-1]);)u--;for(;f<u-1&&AE.test(s[f]);)f++;return this.projectCleanRangeToRaw(o,r.length,f,u)}projectCleanRangeToRaw(e,t,r,s){let o=t,i=t;for(let a=0;a<e.length;a++)if(e[a]===r&&o===t&&(o=a),e[a]===s&&i===t){i=a;break}return{start:o,end:i}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Mh(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;if(t.links){for(let p of t.links)if(i>=p.start&&i<p.end){let m=p.url,h=m.startsWith("file://")?m.slice(7):m,y=null,w=h.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(h=w[1],y=Number.parseInt(w[2],10)),{raw:h,line:y}}}let a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!Wb.test(s[a]))return null;let d=a;for(;d>0&&Wb.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&Wb.test(s[c]);)c++;let l=s.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=s.slice(c).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||!t.links||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Mh(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;for(let a of t.links)if(i>=a.start&&i<a.end)return a.url;return null}osc8UrlFor(e){if(RE.test(e))return null;if(e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;let t=e.indexOf("#"),r=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t);if(r.length===0)return null;let o=r;return r==="~"||r.startsWith("~/")?o=r==="~"?Ah():`${Ah()}/${r.slice(2)}`:Rh(r)||(o=CE(this.sessionbar.cwd,r)),hw(o+s)}linkSpansForWindow(e,t,r,s,o){let i=s2(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=i[d.start]??e.length,f=i[d.end]??e.length,u=Math.max(l,r),p=Math.min(f,s);p>u&&a.push({start:u-r+o,end:p-r+o,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Ah():`${Ah()}/${t.slice(2)}`);let r=Rh(t)||e.startsWith("~"),s=Rh(t)?t:CE(this.sessionbar.cwd,t);if(r)return s;try{if(Vl(s).isFile())return s}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+r)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.raw;if(!$j.test(r))return!1;let s=r.startsWith(wn)?[r]:[wn+r,r],o=null;for(let i of s)try{if(Vl(D.sessionFile(i)).isFile()){o=i;break}}catch{}return o===null?!1:this.onHydraLinkClick(o)}dispatchLinkUrl(e){let t=e.match(RE);if(t){let o=t[1]??null;return o!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(o):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let r=e;if(r.startsWith("file://")){let o=r.slice(7),i=o.indexOf("/");r=i===-1?"":o.slice(i);try{r=decodeURIComponent(r)}catch{}}if(r.length===0)return!1;let s=r.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return s?this.tryOpenPathString(`${s[1]}:${s[2]}`):this.tryOpenPathString(r)}tryOpenLinkAt(e,t){let r=this.findLinkUrlAt(e);if(r!==null)return this.dispatchLinkUrl(r);let o=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(o!==void 0)return this.dispatchLinkUrl(o);if(t!==null){let i=this.blockLinkUrlAt(t);if(i!==null)return this.dispatchLinkUrl(i)}return!1}reconcileWorkspacePath(e){let t=xE(D.home(),"workspaces")+Th;if(!e.startsWith(t))return e;let s=this.sessionbar.cwd;if(s.length>0&&(e===s||e.startsWith(s+Th)))return e;let o=!1;try{Vl(e),o=!0}catch{o=!1}if(o)return this.notify("opening a file in a workspace this session left \u2014 edits there will not reach your project",5e3),e;let i=e.slice(t.length).split(Th).slice(2).join(Th);if(i.length>0&&s.length>0){let a=xE(s,i);try{if(Vl(a).isFile())return this.notify("that workspace is gone \u2014 opened the file in your project instead",4e3),a}catch{}}return this.notify("that file was in a workspace that no longer exists",4e3),null}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let t=e,r=null,s=e.match(/^(.*?):(\d+)(?::\d+)?$/);s&&(t=s[1],r=Number.parseInt(s[2],10));let o=this.resolvePathToken(t);if(o===null)return!1;let i=this.reconcileWorkspacePath(o);if(i===null)return!1;let a=fE(this.openFileCommand,i,r);if(a===null)return!1;let d=r===null?i:`${i}:${r}`;if(this.openFileForeground)return this.openInForeground(a,d),!0;try{let c=Rj(a.program,a.args,{detached:!0,stdio:"ignore",cwd:this.spawnCwd()});c.on("error",l=>{this.notify(`open file failed: ${l.message}`)}),c.unref(),this.notify(`opening ${d}`)}catch(c){this.notify(`open file failed: ${c.message}`)}return!0}spawnCwd(){let e=this.sessionbar.cwd;if(!(!e||!Rh(e)))try{return Vl(e).isDirectory()?e:void 0}catch{return}}openInForeground(e,t){this.foregroundChildActive||(this.foregroundChildActive=!0,this.runForeground({program:e.program,args:e.args,cwd:this.spawnCwd(),banner:`\u2500 ${e.program} ${t} \u2014 quit the editor to return to hydra \u2500
|
|
243
|
+
`)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),r=this.lineIndexById(e.endLineId);if(t===-1||r===-1)return null;let s=t,o=r,i=e.startOffset,a=e.endOffset;t>r&&(s=r,o=t,i=e.endOffset,a=e.startOffset);let d=new Map,c=-1;for(let l=o;l>=s;l--){let f=this.lines[l];if(f&&!this.isHiddenLine(f)){c=l;break}}for(let l=s;l<=o;l++){let f=this.lines[l];if(!f||this.isHiddenLine(f))continue;let u=this.lineIds.get(f);if(u===void 0)continue;let p=(f.body??"").length,m=l===s?Math.max(0,Math.min(p,i)):0,h=l===o?Math.max(0,Math.min(p,a)):p;d.set(u,{start:m,end:h,toEnd:l<c})}return{loIdx:s,hiIdx:o,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let r=this.wrapOrigin.get(e);if(!r)return null;let s=t.get(r.sourceLineId);if(!s)return null;let o=r.sourceColOffset,i=r.bodyDisplayShift??0,a=r.sourceColEnd??o+e.body.length-i,d=Math.max(s.start,o),c=Math.min(s.end,a);if(c<=d)return null;let l,f;if(r.sourceColEnd!==void 0){let u=this.sourceBodyForId(r.sourceLineId);if(u===null)return null;let p=Qb(u,o,d),m=Qb(u,d,c);l=Xb(e.body,i,p),f=Xb(e.body,l,m)}else l=d-o+i,f=c-o+i;return{start:l,end:f,toEndOfLine:s.toEnd||s.end>a}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.lines[t]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.workspaceIndicator!==null?{text:this.workspaceIndicator,kind:"workspace"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let t of e){let r=this.lineIds.get(t);if(r!==void 0&&(r===this.selection.startLineId||r===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count,s=r>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(t.start,r)),i=this.lines.splice(t.start,t.count);for(let a of i)this.forgetLine(a);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-o),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let t=e.start+e.count;if(t>=this.lines.length)return;let r=this.lines.splice(e.start,e.count);for(let[s,o]of this.keyedBlocks)s!==this.stickyBottomKey&&o.start>=t&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...r),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count>=this.lines.length,s=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),o=this.lines.splice(t.start,t.count);for(let i of o)this.forgetLine(i);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>t.start&&(i.start-=t.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-s),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let r=[...t].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),s=r.findIndex(d=>d.key===e);if(s<0)return[];let o=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!t.has(l)&&f.start>=d&&f.start<c)return!0;return!1},i=s;for(;i>0&&!o(r[i-1].start+r[i-1].count,r[i].start);)i--;let a=s;for(;a<r.length-1&&!o(r[a].start+r[a].count,r[a+1].start);)a++;return r.slice(i,a+1).map(d=>d.key)}setRunCollapsed(e,t,r){if(e.length===0)return;let s=e[0];if(!this.keyedBlocks.has(s))return;this.upsertLines(s,r);let o=this.keyedBlocks.get(s),i=o.start+o.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(i=Math.max(i,d.start+d.count))}for(let a=o.start+o.count;a<i;a++){let d=this.lines[a];d&&(d.collapsed=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,ge(Lw),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&(this.clearSelection(),this.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),ZT(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(t=>({...t}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&(this.clearSelection(),this.compactionArmedAt=Date.now()),this.compactionPrompt=e?{...e}:null,e===null&&(this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion=null,this.compactionPressHit=null),this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,e===null&&(this.helpRegion=null,this.helpPressed=!1),this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlayScroll=0,this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!0),e.usage!==void 0){let r=this.btwOverlayUsage,s=e.usage;(!r||r.used!==s.used||r.size!==s.size||r.costAmount!==s.costAmount||r.costCurrency!==s.costCurrency)&&(this.btwOverlayUsage={...s},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let r=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){r=!1;break}if(r)return}let t=this.btwOverlayLines.length;if(this.btwOverlayLines=[...e],this.btwOverlayScroll>0&&e.length>t){let r=this.term.width,s=0;for(let o=t;o<this.btwOverlayLines.length;o++)s+=r>4?this.wrapOne(this.btwOverlayLines[o],r).length:1;this.btwOverlayScroll+=s}this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,r=this.btwOverlayStatus===e.style;t&&r||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayRegion=null,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((r,s)=>{let o=this.completions[s];return o!==void 0&&o.name===r.name&&o.description===r.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,r=t!==void 0&&t.start+t.count===this.lines.length,s=r?t.start-1:this.lines.length-1;if(s<0)return;let o=this.lines[s];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),r?(this.lines.splice(t.start,0,i),t.start+=1):this.lines.push(i),this.trackLine(i),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(i)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,t){if(process.env.HYDRA_TUI_KEY_TRACE&&he({tag:"key",name:e,isChar:!!t.isCharacter}),t.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.scrollToNextTurn();return}let r=Oh(e);if(r){this.onKey([{type:"key",name:r}]);return}e.startsWith("CTRL_")&&this.revealHints()}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let f=e==="MOUSE_WHEEL_UP"?3:-3,u=this.mouseCell(t);if(u!==null&&this.isFormCell(u.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(u!==null&&this.isCompactionCell(u.y)){this.stepCompactionCursor(e==="MOUSE_WHEEL_UP"?-1:1);return}if(u!==null&&this.isSidebarCell(u.x,u.y)&&this.scrollSidebarBy(f)||u!==null&&this.isBtwOverlayCell(u.y)&&this.scrollBtwOverlayBy(f))return;this.scrollBy(f);return}let s=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||s)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let i=this.mouseCell(t),a=Xj(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&i!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:i.x,y:i.y,name:e});let c=i!==null?this.barHitAt(i.x,i.y):null;if(d==="move"){let f=c?.id??null,u=i!==null&&i.y===this.composerBottomRow&&this.hintZoneStart!==null&&i.x>=this.hintZoneStart,p=this.trackHintHover(u);if((f!==this.hoveredBarHit||p)&&(this.hoveredBarHit=f,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),i!==null&&this.isPermissionCell(i.y)){let m=this.permissionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.permissionPrompt!==null&&m.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isCompactionCell(i.y)){let m=this.compactionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.compactionPrompt!==null&&m.index!==this.compactionPrompt.selectedIndex&&this.onCompactionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isFormCell(i.y)){let m=this.formHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="row"&&this.formPrompt!==null&&m.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:m.row,select:!0})}}let l=i!==null&&c===null&&this.barHits.get(i.y)===void 0&&i.x>=1&&i.x<=this.transcriptVisibleWidth();if(i!==null&&l&&d!=="release"){let f=this.keyAndSubAtRow(i.y),u=f!==null&&f.key.startsWith("agent:")?null:f;if(u===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(i.y),m=this.nearestKeyBelowRow(i.y);p!==null&&m!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(m)&&(u={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(u!==null?"pointer":"default"),d==="move"){let p=u?.key??null,m=u?.sub??null;(p!==this.hoveredBlockKey||m!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=m,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(i!==null&&!l&&this.setPointerShape("default"),(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback())));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let f=this.lastLeftClick;if(f!==null&&i!==null&&Math.abs(i.x-f.x)<=Eh&&Math.abs(i.y-f.y)<=Eh&&Date.now()-f.t<=Jl||this.flushPendingBlockClick(),i!==null&&this.handleBarPress(i)){this.pressCell=null;return}if(i!==null&&this.handlePermissionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleCompactionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleHelpPress(i)){this.pressCell=null;return}if(i!==null&&this.handleFormPress(i)){this.pressCell=null;return}if(this.handleSidebarPress(i)){this.pressCell=null,this.clearSelection();return}this.pressCell=i,this.handleSelectionPress(i,Qj(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&i!==null&&this.extendSelectionByClick(i))){if(e==="MOUSE_DRAG"&&i!==null){this.handleSelectionDrag(i);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){if(this.handleBarRelease(i)){this.pressCell=null;return}if(this.handlePermissionRelease(i)){this.pressCell=null;return}if(this.handleCompactionRelease(i)){this.pressCell=null;return}if(this.handleHelpRelease(i)){this.pressCell=null;return}if(this.handleFormRelease(i)){this.pressCell=null;return}let f=this.pressCell;this.pressCell=null;let u=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(f!==null&&i!==null&&i.x===f.x&&i.y===f.y&&!u&&this.onBlockClick){let p=this.keyAndSubAtRow(i.y),m=p?.key??null;if(m!==null){let h=i.y;for(;h>1&&this.keyAtRow(h-1)===m;)h-=1;this.schedulePendingBlockClick(m,i.y-h,p?.sub??null)}}(i===null||!this.isSidebarCell(i.x,i.y))&&this.handleSelectionRelease(i)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,this.selectionGranularity="char",this.selectionAnchorWordBounds=null,this.selectionAnchorLineId=null,!this.inAppSelectionEnabled||e===null)return;let r=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(r===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(r)){this.lastLeftClick=null;return}this.selectionAnchor=r;let s=Date.now(),o=this.lastLeftClick,i=o!==null&&s-o.t<=Jl&&Math.abs(e.x-o.x)<=Eh&&Math.abs(e.y-o.y)<=Eh&&o.sourceLineId!==null&&o.sourceLineId===r.sourceLineId;if(i&&o.count===2&&e.x===o.x&&e.y===o.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(r.sourceLineId),this.selectionGranularity="line",this.selectionAnchorLineId=r.sourceLineId,this.doubleClickPending=!0;return}if(i&&o.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(r,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(r);c!==null&&(this.setSelection({sourceLineId:r.sourceLineId,offset:c.start},{sourceLineId:r.sourceLineId,offset:c.end}),this.doubleClickPending=!0,this.selectionGranularity="word",this.selectionAnchorWordBounds={sourceLineId:r.sourceLineId,start:c.start,end:c.end})}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let r=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:r})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null)return;this.extendSelectionForGesture(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionForGesture(e){this.selectionGranularity==="word"?this.extendWordSelectionToCell(e):this.selectionGranularity==="line"?this.extendLineSelectionToCell(e):this.extendSelectionToCell(e)}extendWordSelectionToCell(e){if(this.selectionAnchorWordBounds===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.selectionAnchorWordBounds,s=this.lineIndexById(r.sourceLineId),o=this.lineIndexById(t.sourceLineId);if(s<0||o<0)return;let i=o<s||o===s&&t.offset<r.start,a=o>s||o===s&&t.offset>r.end,d={sourceLineId:r.sourceLineId,offset:r.start},c={sourceLineId:r.sourceLineId,offset:r.end};if(i){let l=this.wordBoundsAt(t);d=l!==null?{sourceLineId:t.sourceLineId,offset:l.start}:t}else if(a){let l=this.wordBoundsAt(t);c=l!==null?{sourceLineId:t.sourceLineId,offset:l.end}:t}this.selectionDragStarted=!0,this.setSelection(d,c)}extendLineSelectionToCell(e){if(this.selectionAnchorLineId===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.lineIndexById(this.selectionAnchorLineId),s=this.lineIndexById(t.sourceLineId);if(r<0||s<0)return;let o=s<=r?t.sourceLineId:this.selectionAnchorLineId,i=s<=r?this.selectionAnchorLineId:t.sourceLineId,a=this.lineById(i);a!==null&&(this.selectionDragStarted=!0,this.setSelection({sourceLineId:o,offset:0},{sourceLineId:i,offset:(a.body??"").length}))}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let r=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return r===null?!1:this.extendSelectionByClickResolved(r)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let r=this.contentWidth(),{rows:s}=this.wrapTail(r,t+this.scrollOffset),o=s.length-this.scrollOffset,i=Math.max(0,o-t),a=s.slice(i,o),d=Math.max(0,t-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=c<d;if(c===0&&l||u){let p=this.lines[0];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:0}}}if(c>=t-1&&f){let p=this.lines[this.lines.length-1];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let r=this.scrollbackVisibleRows();if(r<=0)return null;let s=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let o=1;o<r;o++){let i=t-o;if(i>=1){let d=this.resolveCellToSource(s,i);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+o;if(a<=r){let d=this.resolveCellToSource(s,a);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let r=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===r){this.stopAutoscroll();return}this.extendSelectionForGesture(this.autoscrollCell)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,r=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let s=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:s?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||r){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Mh(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length,a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!Ph.test(s[a])&&!jb.test(s[a]))return null;let d=a;for(;d>0&&jb.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&jb.test(s[c]);)c++;for(;c>d+1&&_j.test(s[c-1]);)c--;if(s.slice(d,c).includes("://")){let p=d,m=c;return this.projectCleanRangeToRaw(o,r.length,p,m)}if(!Ph.test(s[a]))return null;let f=a;for(;f>0&&Ph.test(s[f-1]);)f--;let u=a+1;for(;u<s.length&&Ph.test(s[u]);)u++;for(;u>f+1&&AE.test(s[u-1]);)u--;for(;f<u-1&&AE.test(s[f]);)f++;return this.projectCleanRangeToRaw(o,r.length,f,u)}projectCleanRangeToRaw(e,t,r,s){let o=t,i=t;for(let a=0;a<e.length;a++)if(e[a]===r&&o===t&&(o=a),e[a]===s&&i===t){i=a;break}return{start:o,end:i}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Mh(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;if(t.links){for(let p of t.links)if(i>=p.start&&i<p.end){let m=p.url,h=m.startsWith("file://")?m.slice(7):m,y=null,w=h.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(h=w[1],y=Number.parseInt(w[2],10)),{raw:h,line:y}}}let a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!Wb.test(s[a]))return null;let d=a;for(;d>0&&Wb.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&Wb.test(s[c]);)c++;let l=s.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=s.slice(c).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||!t.links||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Mh(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;for(let a of t.links)if(i>=a.start&&i<a.end)return a.url;return null}osc8UrlFor(e){if(RE.test(e))return null;if(e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;let t=e.indexOf("#"),r=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t);if(r.length===0)return null;let o=r;return r==="~"||r.startsWith("~/")?o=r==="~"?Ah():`${Ah()}/${r.slice(2)}`:Rh(r)||(o=CE(this.sessionbar.cwd,r)),hw(o+s)}linkSpansForWindow(e,t,r,s,o){let i=s2(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=i[d.start]??e.length,f=i[d.end]??e.length,u=Math.max(l,r),p=Math.min(f,s);p>u&&a.push({start:u-r+o,end:p-r+o,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Ah():`${Ah()}/${t.slice(2)}`);let r=Rh(t)||e.startsWith("~"),s=Rh(t)?t:CE(this.sessionbar.cwd,t);if(r)return s;try{if(Vl(s).isFile())return s}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+r)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.raw;if(!$j.test(r))return!1;let s=r.startsWith(wn)?[r]:[wn+r,r],o=null;for(let i of s)try{if(Vl(D.sessionFile(i)).isFile()){o=i;break}}catch{}return o===null?!1:this.onHydraLinkClick(o)}dispatchLinkUrl(e){let t=e.match(RE);if(t){let o=t[1]??null;return o!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(o):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let r=e;if(r.startsWith("file://")){let o=r.slice(7),i=o.indexOf("/");r=i===-1?"":o.slice(i);try{r=decodeURIComponent(r)}catch{}}if(r.length===0)return!1;let s=r.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return s?this.tryOpenPathString(`${s[1]}:${s[2]}`):this.tryOpenPathString(r)}tryOpenLinkAt(e,t){let r=this.findLinkUrlAt(e);if(r!==null)return this.dispatchLinkUrl(r);let o=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(o!==void 0)return this.dispatchLinkUrl(o);if(t!==null){let i=this.blockLinkUrlAt(t);if(i!==null)return this.dispatchLinkUrl(i)}return!1}reconcileWorkspacePath(e){let t=xE(D.home(),"workspaces")+Th;if(!e.startsWith(t))return e;let s=this.sessionbar.cwd;if(s.length>0&&(e===s||e.startsWith(s+Th)))return e;let o=!1;try{Vl(e),o=!0}catch{o=!1}if(o)return this.notify("opening a file in a workspace this session left \u2014 edits there will not reach your project",5e3),e;let i=e.slice(t.length).split(Th).slice(2).join(Th);if(i.length>0&&s.length>0){let a=xE(s,i);try{if(Vl(a).isFile())return this.notify("that workspace is gone \u2014 opened the file in your project instead",4e3),a}catch{}}return this.notify("that file was in a workspace that no longer exists",4e3),null}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let t=e,r=null,s=e.match(/^(.*?):(\d+)(?::\d+)?$/);s&&(t=s[1],r=Number.parseInt(s[2],10));let o=this.resolvePathToken(t);if(o===null)return!1;let i=this.reconcileWorkspacePath(o);if(i===null)return!1;let a=fE(this.openFileCommand,i,r);if(a===null)return!1;let d=r===null?i:`${i}:${r}`;if(this.openFileForeground)return this.openInForeground(a,d),!0;try{let c=Rj(a.program,a.args,{detached:!0,stdio:"ignore",cwd:this.spawnCwd()});c.on("error",l=>{this.notify(`open file failed: ${l.message}`)}),c.unref(),this.notify(`opening ${d}`)}catch(c){this.notify(`open file failed: ${c.message}`)}return!0}spawnCwd(){let e=this.sessionbar.cwd;if(!(!e||!Rh(e)))try{return Vl(e).isDirectory()?e:void 0}catch{return}}openInForeground(e,t){this.foregroundChildActive||(this.foregroundChildActive=!0,this.runForeground({program:e.program,args:e.args,cwd:this.spawnCwd(),banner:`\u2500 ${e.program} ${t} \u2014 quit the editor to return to hydra \u2500
|
|
244
244
|
`},{suspend:()=>this.stop(),resume:()=>this.start(),notify:r=>this.notify(r)}).finally(()=>{this.foregroundChildActive=!1}))}schedulePendingBlockClick(e,t,r){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t,r);return}this.cancelPendingBlockClick();let s=this.onBlockClick,o=setTimeout(()=>{this.pendingBlockClick=null,s(e,t,r)},Jl);typeof o.unref=="function"&&o.unref(),this.pendingBlockClick={timer:o,key:e,rowOffset:t,subKey:r}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset,e.subKey))}lineById(e){for(let t of this.lines)if(this.lineIds.get(t)===e)return t;return null}lineIndexById(e){for(let t=0;t<this.lines.length;t++){let r=this.lines[t];if(r&&this.lineIds.get(r)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&hb(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,r=Number(t.x),s=Number(t.y);return!Number.isFinite(r)||!Number.isFinite(s)?null:{x:r,y:s}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,ge(e==="pointer"?zR:Kp))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null)return null;let r=this.contentWidth(),s=this.scrollbackVisibleRows();if(s<=0)return null;let{rows:o}=this.wrapTail(r,s+this.scrollOffset);for(let i of o)if(i.blockKey===t&&i.linkSpans!==void 0&&i.linkSpans.length>0)return i.linkSpans[0]?.url??null;return null}keyAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),f=o-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let r=this.keyAtRow(t);if(r!==null)return r}return null}nearestKeyBelowRow(e){let r=this.scrollbackVisibleRows();for(let s=e+1;s<=r;s++){let o=this.keyAtRow(s);if(o!==null)return o}return null}keyAndSubAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),f=o-l;if(f<0||f>=c.length)return null;let u=c[f];return u?.blockKey?{key:u.blockKey,sub:u.hoverSubKey??null}:null}resolveCellToSource(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let i=t-s;if(i<0||i>=o||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(r,o+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-o),l=a.slice(c,d),f=Math.max(0,o-l.length),u=i-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=xt(p.prefix??""),y=m.bodyDisplayShift??0,w=e-1-h;if(w<y)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let k=w,S=Ql(p.bodyStyle)||p.ansi===!0?dE(nk(p.body),k):aE(p.body,k);if(m.sourceColEnd!==void 0){let C=this.sourceBodyForId(m.sourceLineId);if(C!==null){let I=Qb(p.body,y,S),T=Xb(C,m.sourceColOffset,I);return{sourceLineId:m.sourceLineId,offset:T}}}return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset+S-y}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),r=Math.min(t,Math.max(0,this.scrollOffset+e));r!==this.scrollOffset&&(this.scrollOffset=r,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){if(this.pageWhenNoTurns(1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=e.find(s=>s>t);this.stepToTurnStop(r??this.maxScrollOffset())}scrollToNextTurn(){if(this.pageWhenNoTurns(-1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=0;for(let s of e){if(s>=t)break;r=s}this.stepToTurnStop(r)}pageWhenNoTurns(e){return this.turnScrollOffsets().length>0?!1:(this.scrollBy(e*this.scrollPageSize()),!0)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),t=[0,...this.turnScrollOffsets(),e].filter(r=>r>=0&&r<=e).sort((r,s)=>r-s);return t.filter((r,s)=>s===0||r!==t[s-1])}notifyTurnPosition(e){let t=this.turnScrollOffsets();if(t.length===0)return;let r=t.findIndex(o=>o>=e),s=r===-1?1:t.length-r;this.notify(`turn ${s}/${t.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),t=this.scrollbackVisibleRows();if(t<=0)return[];let r=[],s=0,o=null;for(let i=this.lines.length-1;i>=0;i--){let a=this.lines[i];if(!(!a||this.isHiddenLine(a))){if(s+=this.wrapOne(a,e).length,a.bodyStyle==="user"){o={offset:Math.max(0,s-t),lineIndex:i,recordedAt:a.recordedAt};continue}o!==null&&(r.push(o),o=null)}}return o!==null&&r.push(o),r}scrollToTurnAt(e){let t=this.turnAnchors();if(t.length===0)return;let r=t.find(s=>s.recordedAt!==void 0&&s.recordedAt<=e)??t[t.length-1];this.setScrollOffset(r.offset),this.notifyTurnPosition(r.offset)}slideScrollTo(e){this.cancelSlide();let t=Math.min(this.maxScrollOffset(),Math.max(0,e)),r=Math.abs(t-this.scrollOffset);if(r!==0){if(r<=Vj||!this.slideEnabled){this.setScrollOffset(t);return}this.slideTarget=t,this.slideTimer=setInterval(()=>{let s=this.slideTarget-this.scrollOffset,o=Math.sign(s)*Math.max(1,Math.round(Math.abs(s)*Gj)),i=Math.abs(s)<=Math.abs(o)?this.slideTarget:this.scrollOffset+o;this.scrollOffset=i,this.syncedPartialRepaint(()=>this.drawScrollback()),i===this.slideTarget&&this.cancelSlide()},Kj)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=Math.min(this.maxScrollOffset(),Math.max(0,e));t!==this.scrollOffset&&(this.scrollOffset=t,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let t=e.toLowerCase(),r=[];if(t.length>0)for(let s=this.lines.length-1;s>=0;s--){let o=this.lines[s];if(!o||o.body.length===0||o.ansi)continue;let i=FE(o.body,t);for(let a=i.length-1;a>=0;a--)r.push({lineIdx:s,col:i[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=r,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=t.length>0?t:null,r.length>0&&this.scrollToMatch(r[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let t=this.lines[e.lineIdx];if(!t)return null;let r=this.lineIds.get(t);return r===void 0?null:{lineId:r,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let r=this.wrapOrigin.get(e);if(!r||r.sourceLineId!==t.lineId)return null;let s=r.bodyDisplayShift??0,o=t.col-r.sourceColOffset+s;return o<s||o>=e.body.length?null:o}scrollToMatch(e){let t=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return;let s=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(s+=this.wrapOne(f,t).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,t),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let m=p.body.length;if(e.col<f+m){i=l.length-1-u;break}f+=m}}let a=s+i,d=Math.max(0,a-Math.floor(r/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Tt-Bt-Nt-Oj-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,t,r,s){return this.started?this.painter.paintRow(e,t,r,s):!1}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),this.barHits.clear(),at(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let r=this.promptRows(),s=t-r-Nt-Bt-Tt;this.drawBar("composerTop",s),this.drawPrompt(),this.drawBar("composerBottom",t-Tt),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=r}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:this.hintsRevealed()}}trackHintHover(e){return e?(this.cancelHintHoverHide(),this.hintHoverReveal?!1:(this.hintHoverReveal=!0,!0)):(!this.hintHoverReveal||this.hintHoverHideTimer!==null||(this.hintHoverHideTimer=setTimeout(()=>{this.hintHoverHideTimer=null,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars())},Mj)),!1)}cancelHintHoverHide(){this.hintHoverHideTimer!==null&&(clearTimeout(this.hintHoverHideTimer),this.hintHoverHideTimer=null)}hintsRevealed(){return this.terminalFocused?this.hintHoverReveal||this.hintKeyReveal:!1}revealHints(){this.hintKeyReveal||(this.hintKeyReveal=!0,this.syncedPartialRepaint(()=>this.drawBars()))}clearHintReveal(){this.cancelHintHoverHide(),!(!this.hintKeyReveal&&!this.hintHoverReveal)&&(this.hintKeyReveal=!1,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars()))}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:[],queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:!1}}drawBar(e,t){let r=Ib[e],s=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,o=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top;e==="composerBottom"&&(this.composerBottomRow=t);let i=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?ST(i):null,d=a!==null?[a]:ql(e,o.right,i),c=bb(s,ql(e,o.left,i),d,r);e==="composerBottom"&&(this.hintZoneStart=this.hintZoneStartFor(s,o,i,a,c));let l=this.terminalFocused?this.hoveredBarHit:null,f=`${e}|${s}|${l??""}|${c.signature}`;this.paintRow(t,f,()=>{for(let u of c.chunks){let p=u.id!==void 0&&u.id===l?"hint-hover":u.token;N(this.term,p,u.text)}}),this.barHits.set(t,c.hits)}hintZoneStartFor(e,t,r,s,o){if(s!==null)return null;if(r.hintsRevealed)return o.rightStart;let i={...r,hintsRevealed:!0};return bb(e,ql("composerBottom",t.left,i),ql("composerBottom",t.right,i),Ib.composerBottom).rightStart}barHitAt(e,t){let r=this.barHits.get(t);return r===void 0?null:r.find(s=>e>=s.start&&e<=s.end)??null}bannerHitAt(e,t){let r=this.barHitAt(e,t);if(r===null)return null;let s=r.id.slice(r.id.indexOf(":")+1);return xb.some(o=>o.id===s)?s:null}stepFormCursor(e){let t=this.formPrompt;if(t===null||t.rows.length===0)return;let r=Math.max(0,Math.min(t.rows.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onFormClick?.({kind:"row",row:r,select:!0})}isFormCell(e){let t=this.formRegion;return this.formPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}formHitAt(e,t){if(!this.isFormCell(t))return null;for(let s of this.formHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.formRowHits.get(t);if(r===void 0)return null;if(r.field!==void 0&&e>=r.field.startCol){let{slice:s,sliceStart:o,startCol:i}=r.field,a=o,d=i;for(let c of s){let l=d+xt(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:r.row,caretOffset:a}}return{kind:"row",row:r.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let t=this.formPressHit;if(this.formPressHit=null,t===null||e===null||!this.isFormCell(e.y))return t!==null;let r=this.formHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="row"&&t.kind==="row"&&r.row!==t.row||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action||this.onFormClick?.(r),!0}handleBarPress(e){let t=this.barHitAt(e.x,e.y);if(t===null)return this.barPressHit=null,!1;let r=Date.now(),s=this.lastBarClick;return s!==null&&s.id===t.id&&r-s.t<=Jl&&t.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(t.doubleAction,t.value),!0):(this.lastBarClick={id:t.id,t:r},this.barPressHit=t,!0)}handleBarRelease(e){let t=this.barPressHit;if(this.barPressHit=null,t===null||e===null)return!1;let r=this.barHitAt(e.x,e.y);return r===null||r.id!==t.id?!1:(r.action==="none"||this.dispatchBarAction(r.action,r.value),!0)}dispatchBarAction(e,t){if(e!=="none"){if(e==="copy"){hb(t,{target:this.selectionClipboard}).then(r=>{this.notify(r.ok?`copied ${t}`:`clipboard copy failed: ${r.reason}`)},r=>{this.notify(`clipboard copy failed: ${r.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(t);return}if(e==="open"){this.tryOpenPathString(t)||this.notify(this.hasOpenFileCommand()?`can't open ${t}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,t)}}drawScrollback(){let e=this.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),r=this.sidebarBodyWidth()>0,s=1,o=this.scrollbackVisibleRows();if(o<=0)return;let{rows:i,exhausted:a}=this.wrapTail(e,o+this.scrollOffset);if(a){let y=Math.max(0,i.length-o);this.scrollOffset>y&&(this.scrollOffset=y)}let d=i.length-this.scrollOffset,c=Math.max(0,d-o),l=i.slice(c,d),f=Math.max(0,o-l.length),u=this.currentMatchInfo(),p=u?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let m=-1,h=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let y=0;y<l.length;y++){let w=l[y]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(m===-1&&(m=y),h=y)}for(let y=0;y<o;y++){let w=s+y,k=y-f,b=k>=0?l[k]:void 0,S=this.activeMatchCol(b,u),C=b?this.selectionRangeForChunk(b):null,I=b!==void 0&&b.blockKey!==void 0&&(b.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(b.blockKey)),T=b!==void 0&&b.blockKey===void 0&&m!==-1&&k>=m&&k<=h,O=I||T,E=this.terminalFocused&&O&&(this.hoveredSubKey===null||(b.hoverSubKey??null)===this.hoveredSubKey),$=Yb("sb",e,b,this.scrollbackHighlight,S,C)+(E?"|H":"");this.paintRow(w,$,()=>{b?this.writeFormattedLine(b,e,S,p,C,E,t,b.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&r&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let y=new Set;for(let k of l)k.blockKey!==void 0&&y.add(k.blockKey);let w=[];for(let k of this.pendingVisibleKeys)y.has(k)&&w.push(k);for(let k of w)this.pendingVisibleKeys.delete(k),this.onBlockVisible(k)}}drawSidebar(e,t){let r=this.sidebarBodyWidth();if(r<=0||t<=0){this.sidebarOverflowRows=0;return}let s=this.sidebarColumnStart(),o={metrics:{cellWidth:xt,truncate:Zt},width:r,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:t},i={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(i,o);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear();let c=s+Yl;for(let l=0;l<t;l++){let f=e+l,u=l+d,p=a[u];p?.openPath!==void 0&&this.sidebarRowPaths.set(f,p.openPath),p?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(f,p.doubleAction),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(f,p.actions.map(w=>({start:c+w.start-1,end:c+w.end-1,..."page"in w?{gadget:w.page.gadget,index:w.page.index}:{gadget:w.collapse.gadget,collapse:!0}})));let m=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",h=p?.openPath===void 0||!p.openPath.startsWith("/")||p.openSpan===void 0?null:[{...p.openSpan,url:hw(p.openPath)}],y=Yb("sbar",r,p,null,null,null)+`|${m}|${h===null?"":h.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(f,y,()=>{this.term(" ".repeat(Math.max(0,Yl-1))),m===" "?this.term(" "):Ls(this.term,m,"sidebar-rule",!1),p?this.writeFormattedLine(p,r,null,0,null,!1,!0,h):this.term(" ".repeat(r))},{region:"sidebar",column:s})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let t=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return t===this.sidebarScrollOffset||(this.sidebarScrollOffset=t,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,t){let r=this.sidebarColumnStart();return r===0?!1:e>=r&&e<=(this.term.width||0)&&t>=1&&t<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let o of this.sidebarRowActions.get(e.y)??[])if(!(e.x<o.start||e.x>o.end))return o.collapse===!0?this.toggleSidebarGadgetCollapsed(o.gadget):this.sidebarPages={...this.sidebarPages,[o.gadget]:o.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),r=this.lastSidebarClick;if(r!==null&&t-r.t<=Jl&&e.y===r.y){this.lastSidebarClick=null;let o=this.sidebarRowDoubleActions.get(e.y);if(o!==void 0)return this.dispatchBarAction(o.action,o.value),!0;let i=this.sidebarRowPaths.get(e.y);return i!==void 0&&!this.dispatchLinkUrl(i)&&this.notify(this.hasOpenFileCommand()?`can't open ${i}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Kb,this.queuedTexts.length)}chipRows(){return Math.min(Vb,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,r)=>t===e[r])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Gb,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-Tt-Bt-Nt,o=this.queuedRows(),i=this.chipRows(),d=s-1-o-i-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>Gb,m=this.completions.length-Gb+1,h=u?p?`comp|${t}|overflow|${m}`:`comp|${t}|${c}|${u.name}|${u.description??""}`:`comp|${t}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){N(this.term,"modal-hint",` + ${m} more match(es)`);return}let y=u.name.padEnd(c),w=u.description??"",k=t-y.length-4,b=k>0?Zt(w,k):"";this.term.noFormat(" "),N(this.term,"completion-name",y),b.length>0&&(this.term.noFormat(" "),N(this.term,"completion-desc",b))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),i=this.term.height-r-Tt-Bt-Nt-1-e+1;for(let a=0;a<e;a++){let d=i+a,c=a===e-1&&this.attachments.length>Vb,l=this.attachments.length-Vb,f=this.attachments[a],u=f?`${f.name??"image"} \xB7 ${Ir(f.sizeBytes)}`:"",p=c?`chip|${t}|overflow|${l}`:f?`chip|${t}|${u}`:`chip|${t}|empty`;this.paintRow(d,p,()=>{if(c){N(this.term,"modal-hint",` \u{1F4CE} + ${l+1} more attached`);return}f&&(this.term.noFormat(" "),N(this.term,"attachment",`\u{1F4CE} ${u}`))})}}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-Tt-Bt-Nt,o=this.chipRows(),a=s-1-o-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>Kb,p=this.queuedTexts.length-Kb,m=f===void 0?"":u?`+ ${p+1} more queued`:Zt(m2(f),t-4),h=!u&&c===d,y=f===void 0?`queued|${t}|empty`:`queued|${t}|${h?"edit":u?"ovf":"row"}|${m}`;this.paintRow(l,y,()=>{if(f===void 0)return;let w=`\u23F3 ${m}`,k=w+" ".repeat(Math.max(0,t-1-w.length));h?N(this.term,"queue-cursor","\u25B8"):N(this.term,"queue-blank"," "),N(this.term,"queue-row",k)})}}drawPrompt(){if((this.permissionPrompt||this.formPrompt||this.confirmPrompt)&&(this.compactionRegion=null),(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt)&&(this.helpRegion=null),this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Ns(r.buffer,t),o=ao(s,r,qb),i=this.term.height-o.rendered-Nt-Bt-Tt+1,a=!1;for(let d=0;d<o.rendered;d++){let c=s[o.windowStart+d],l=i+d,f="wrap",u="";c&&(c.bufferIdx===0&&c.startCol===0?f="first":c.startCol===0&&(f="newline"),u=(r.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(f==="first"?a?N(this.term,"composer-inactive","> "):N(this.term,"composer-gutter","> "):f==="newline"?N(this.term,"composer-continuation","\xB7 "):this.term(" "),a?N(this.term,"composer-inactive",u):N(this.term,"content",u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,r=this.term.height-Jb-Nt-Bt-Tt+1;this.paintRow(r,`confirm|q|${t}|${e.question}`,()=>{N(this.term,"prompt-text",` ? ${Zt(e.question,t-4)}`)}),this.paintRow(r+1,`confirm|h|${t}|${e.hint}`,()=>{N(this.term,"modal-hint",` ${Zt(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,r=this.compactionRows(),s=this.term.height-r-Nt-Bt-Tt+1,o=s;this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion={top:s,bottom:s+r-1};let i=(c,l)=>{o>=s+r||(this.paintRow(o,c,l),o+=1)};i(`cpct|msg|${t}|${e.message}`,()=>{N(this.term,"prompt-text",` ${Zt(e.message,t-2)}`)}),i(`cpct|q|${t}`,()=>{N(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let c=0;c<e.options.length&&!(o>=s+r-1);c++){let l=e.options[c];if(!l)continue;let f=c===e.selectedIndex,p=` ${f?"\u276F":" "} ${c+1}. ${Zt(l.label,t-8)}`;this.compactionRowHits.set(o,c),i(`cpct|o|${t}|${c}|${f?"1":"0"}|${l.label}`,()=>{f?N(this.term,"modal-option-selected",p):N(this.term,"modal-option",p)})}let a=Zb(Uj,t),d=o;for(let c of a.spans)(c.action==="commit"||c.action==="cancel")&&this.compactionHintHits.push({row:d,start:c.start,end:c.end,action:c.action});i(`cpct|hint|${t}|${a.text}`,()=>{N(this.term,"modal-hint",` ${a.text}`)})}isCompactionCell(e){let t=this.compactionRegion;return this.compactionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}compactionHitAt(e,t){if(!this.isCompactionCell(t))return null;for(let s of this.compactionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.compactionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}stepCompactionCursor(e){let t=this.compactionPrompt;if(t===null||t.options.length===0)return;let r=Math.max(0,Math.min(t.options.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onCompactionClick?.({kind:"option",index:r,select:!0})}handleCompactionPress(e){return this.isCompactionCell(e.y)?(this.compactionPressHit=this.compactionHitAt(e.x,e.y),!0):(this.compactionPressHit=null,!1)}handleCompactionRelease(e){let t=this.compactionPressHit;if(this.compactionPressHit=null,t===null||e===null||!this.isCompactionCell(e.y))return t!==null;let r=this.compactionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.compactionArmedAt<EE?(this.notify("compaction prompt just appeared, click again to confirm"),!0):(this.onCompactionClick?.(r),!0)}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let t=this.term.width,r=this.helpRows(),s=this.term.height-r-Nt-Bt-Tt+1,o=s;this.helpRegion={top:s,bottom:s+r-1};let i=(d,c)=>{o>=s+r||(this.paintRow(o,d,c),o+=1)};i(`help|t|${t}|${e.title}`,()=>{N(this.term,"prompt-text",` \u2753 ${Zt(e.title,t-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(o>=s+r-1)break;if(d===null){i(`help|sep|${t}|${o}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);i(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),N(this.term,"modal-key",f),N(this.term,"content",` ${Zt(l,t-2-a-1)}`)})}i(`help|hint|${t}|${e.hint}`,()=>{N(this.term,"modal-hint",` ${Zt(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(jj,2+this.helpPrompt.entries.length):0}isHelpCell(e){let t=this.helpRegion;return this.helpPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}handleHelpPress(e){return this.isHelpCell(e.y)?(this.helpPressed=!0,!0):(this.helpPressed=!1,!1)}handleHelpRelease(e){let t=this.helpPressed;return this.helpPressed=!1,t?(e!==null&&this.isHelpCell(e.y)&&this.onHelpClick?.(),!0):!1}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,r=this.permissionRows(),s=this.term.height-r-Nt-Bt-Tt+1,o=s;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:s,bottom:s+r-1};let i=(l,f)=>{o>=s+r||(this.paintRow(o,l,f),o+=1)};i(`perm|t|${t}|${e.title}`,()=>{N(this.term,"prompt-text",` \u{1F512} ${Zt(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${t}|${a}`,()=>{N(this.term,"modal-hint",` ${Zt(a,t-2)}`)}),i(`perm|q|${t}`,()=>{N(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(o>=s+r-1);l++){let f=e.options[l];if(!f)continue;let u=l===e.selectedIndex,m=` ${u?"\u276F":" "} ${l+1}. ${Zt(f.label,t-8)}`;this.permissionRowHits.set(o,l),i(`perm|o|${t}|${l}|${u?"1":"0"}|${f.label}`,()=>{u?N(this.term,"modal-option-selected",m):N(this.term,"modal-option",m)})}let d=Zb(Hj,t),c=o;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});i(`perm|hint|${t}|${d.text}`,()=>{N(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let t=this.permissionRegion;return this.permissionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}permissionHitAt(e,t){if(!this.isPermissionCell(t))return null;for(let s of this.permissionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.permissionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let t=this.permissionPressHit;if(this.permissionPressHit=null,t===null||e===null||!this.isPermissionCell(e.y))return t!==null;let r=this.permissionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.permissionArmedAt<EE?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(r),!0)}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}drawBanner(){let e=this.term.height,t=this.promptRows(),r=e-t-Nt-Bt-Tt;this.drawBar("composerTop",r),this.drawBar("composerBottom",e-Tt)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Nt-Bt-Tt+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Nt-Bt-Tt;this.term.moveTo(2,Math.min(u,p));return}if(this.formPrompt){let l=this.formPrompt,f=this.formWindowSize(),u=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-u),m=this.term.height-Nt-Bt-Tt,h=Math.min(p,m),w=_E(l,this.term.width,u,f).find(k=>k.selected);if(w?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(w.caretCol,this.term.width),h);return}if(this.confirmPrompt){let l=this.term.height-Jb-Nt-Bt-Tt+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-Nt-Bt-Tt+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Nt-Bt-Tt;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Nt-Bt-Tt+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Ns(r.buffer,t),o=ao(s,r,qb),a=this.term.height-o.rendered-Nt-Bt-Tt+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Nt-Bt-Tt;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return Jb;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Ns(r.buffer,t);return Math.min(qb,Math.max(1,s.length))}permissionRows(){return this.permissionPrompt?Math.min(Bj,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(Wj,this.formPrompt.maxRows??Dj),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Nt-Bt-Tt+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let t=this.term.width,r=this.formRows(),s=this.formTop(),o=this.formWindowSize(),i=`${e.title}|${e.rows.length}|${o}`;i!==this.formWindowKey?(this.formWindowKey=i,this.formWindowTop=l2(e.rows.length,e.selectedIndex,o)):this.formWindowTop=u2(this.formWindowTop,e.rows.length,e.selectedIndex,o);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:s,bottom:s+r-1};let d=s,c=(h,y)=>{d>=s+r||(this.paintRow(d,h,y),d+=1)},l=e.rows.length>o?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${t}|${e.title}|${l}`,()=>{N(this.term,"prompt-text",` \u2699 ${Zt(`${e.title}${l}`,t-5)}`)});let f=_E(e,t,a,o);for(let h of f){if(d>=s+r-1)break;this.formRowHits.set(d,{row:h.index,...h.kind==="text"?{field:{startCol:1+xt(h.prefix),slice:h.field,sliceStart:h.fieldStart}}:{}}),c(h.sig,()=>{if(h.kind==="text"){N(this.term,h.selected?"modal-option-selected":"modal-option",h.prefix),N(this.term,"content",h.field);return}N(this.term,h.selected?"modal-option-selected":"modal-option",h.body)})}let u=e.hints??f2,p=d,m=Zb(u,t);for(let h of m.spans)this.formHintHits.push({row:p,...h});c(`form|hint|${t}|${m.text}`,()=>{N(this.term,"modal-hint",` ${m.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,r=this.wrapBtwWindow(t,e,0).rows.length;return Math.min(this.btwOverlayMaxHeight,1+r)}wrapBtwWindow(e,t,r){let s=this.btwOverlayLines.length;if(t<=0||s===0)return{rows:[],offset:0,more:!1};if(e<=4){let u=Math.min(Math.max(0,r),Math.max(0,s-t)),p=s-u,m=Math.max(0,p-t);return{rows:this.btwOverlayLines.slice(m,p),offset:u,more:m>0}}let o=Math.max(0,r),i=[],a=0;for(let u=s-1;u>=0;u--){let p=this.btwOverlayLines[u],m=this.wrapOne(p,e);if(i.push(m),a+=m.length,a>t+o)break}let d=[];for(let u=i.length-1;u>=0;u--)d.push(...i[u]);let c=Math.min(o,Math.max(0,d.length-t)),l=d.length-c,f=Math.max(0,l-t);return{rows:d.slice(f,l),offset:c,more:f>0}}scrollBtwOverlayBy(e){let t=this.btwOverlayRegion;if(!this.btwOverlayOpen||t===null||t.contentRows<=0)return!1;let r=Math.max(0,this.btwOverlayScroll+e),s=this.wrapBtwWindow(this.term.width,t.contentRows,r);return!s.more&&s.offset===0?!1:(s.offset===this.btwOverlayScroll||(this.btwOverlayScroll=s.offset,this.repaintNow()),!0)}isBtwOverlayCell(e){let t=this.btwOverlayRegion;return t!==null&&e>=t.top&&e<=t.bottom}btwOverlayScrollState(){let t=this.btwOverlayRegion?.contentRows??0;return{offset:this.btwOverlayScroll,more:this.wrapBtwWindow(this.term.width,t,this.btwOverlayScroll).more}}drawBtwOverlay(){if(!this.btwOverlayOpen){this.btwOverlayRegion=null;return}let e=this.btwOverlayRows();if(e===0){this.btwOverlayRegion=null;return}let t=this.term.width,s=this.term.height-this.promptRows()-Nt-Bt-Tt,o=this.chipRows()+this.queuedRows()+this.completionRows(),i=s-1-o,a=i-e+1,d=e-1,c=a;this.btwOverlayRegion={top:c,bottom:i,contentRows:d},this.drawBar("btw",c);let l=this.wrapBtwWindow(t,d,this.btwOverlayScroll);this.btwOverlayScroll=l.offset;let f=l.rows;for(let u=0;u<d;u++){let p=c+1+u,m=f.length-d+u,h=m>=0?f[m]:void 0,y=Yb(`btw|c${u}`,t,h);this.paintRow(p,y,()=>{h?this.writeFormattedLine(h,t):this.term.noFormat(" ".repeat(t))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,t){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(t,d.length);return{rows:d.slice(d.length-c),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],s=0,o=0,i=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(i=!0);continue}let l=this.wrapOne(c,e);if(r.push(l),s+=l.length,o=d,s>=t)break}let a=[];for(let d=r.length-1;d>=0;d--)a.push(...r[d]);return{rows:a,exhausted:o===0||i}}wrapOne(e,t){let r=this.lineIds.get(e);if(r!==void 0){let y=this.wrapCache.get(r);if(y)return y}let s=e.prefix??"",o=xt(s),i=Math.max(1,t-o-1),a=Math.max(0,Math.min(e.hangingIndent??0,i-1)),d=Math.max(1,i-a),c=Ql(e.bodyStyle),l=e.ansi?t2(e.body,a>0?d:i):i2(e.body,a>0?d:i,{escapeAware:c}),f=e.ansi?0:e.maxWrapRows??0,u=f>0&&l.length>f;u&&(l.length=f);let p=[],m=0,h=0;for(let y=0;y<l.length;y++){let w=l[y]??"",k=y===0||a===0?w:" ".repeat(a)+w;u&&y===l.length-1&&(k=Zt(`${k}\u2026`,i,{escapeAware:c}));let b={prefix:y===0?e.prefix:" ".repeat(o),body:k};if(e.prefixStyle!==void 0&&(b.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(b.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(b.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(b.hoverSubKey=e.hoverSubKey),e.fillRow&&(b.fillRow=!0),e.ansi&&(b.ansi=!0),r!==void 0&&w.length>0)if(e.ansi){let S=m,C=0;for(let E=0;E<w.length;){let $=Cr(w,E);if($){E+=$.text.length,$.width>0&&(C+=1);continue}C+=1,E+=1}let I=C;for(;I>0&&m<e.body.length;){let E=Cr(e.body,m);if(E){m+=E.text.length,E.width>0&&(I-=1);continue}m+=1,I-=1}let T=m;if(y===l.length-1){for(;T<e.body.length;){let E=Cr(e.body,T);if(!E)break;T+=E.text.length}m=T}let O={sourceLineId:r,sourceColOffset:S,sourceColEnd:T};if(y>0&&a>0&&(O.bodyDisplayShift=a),this.wrapOrigin.set(b,O),e.links!==void 0){let E=this.linkSpansForWindow(e.body,e.links,S,T,y===0||a===0?0:a);E!==null&&(b.linkSpans=E)}}else{let S=e.body.indexOf(w,h),C=S===-1?h:S,I={sourceLineId:r,sourceColOffset:C};if(y>0&&a>0&&(I.bodyDisplayShift=a),this.wrapOrigin.set(b,I),e.links!==void 0){let T=this.linkSpansForWindow(e.body,e.links,C,C+w.length,y===0||a===0?0:a);T!==null&&(b.linkSpans=T)}h=C+w.length}p.push(b)}return r!==void 0&&this.wrapCache.set(r,p),p}writeFormattedLine(e,t,r=null,s=0,o=null,i=!1,a=!1,d=null){e.prefix&&Ls(this.term,e.prefix,e.prefixStyle??e.bodyStyle,i);let c=Math.max(0,t-xt(e.prefix??"")),l=Ql(e.bodyStyle),f=e.ansi?e.body:Zt(e.body,c,{escapeAware:l}),u=d===null||d.length===0?null:d.map(h=>({start:Math.max(0,Math.min(f.length,h.start)),end:Math.max(0,Math.min(f.length,h.end)),url:h.url})).filter(h=>h.end>h.start).sort((h,y)=>h.start-y.start),p=(h,y,w)=>{if(u===null){w(h,y);return}let k=y+h.length,b=y;for(let S of u){if(S.end<=b||S.start>=k)continue;let C=Math.max(S.start,b),I=Math.min(S.end,k);C>b&&w(h.slice(b-y,C-y),b),process.stdout.write(`\x1B]8;;${S.url}\x1B\\`),w(h.slice(C-y,I-y),C),process.stdout.write("\x1B]8;;\x1B\\"),b=I}b<k&&w(h.slice(b-y),b)},m=(h,y)=>{h.length!==0&&p(h,y,(w,k)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let b=r!==null&&r>=k?r-k:null;e2(this.term,w,e.bodyStyle,this.scrollbackHighlight,b,s,i)}else Ls(this.term,w,e.bodyStyle,i)})};if(o!==null){let h=Math.max(0,Math.min(f.length,o.start)),y=Math.max(h,Math.min(f.length,o.end)),w=Ql(e.bodyStyle)||e.ansi===!0;if(m(f.slice(0,h),0),y>h){let b=f.slice(h,y);w&&(b=_h(b)),w?Ls(this.term,b,"selection-highlight",i):p(b,h,S=>{Ls(this.term,S,"selection-highlight",i)})}let k=f.slice(y);if(w&&y>h){let b=o2(f.slice(0,y));b.length>0&&(k=b+k)}m(k,y)}else m(f,0);if(e.fillRow||i||a){let h=e.ansi?OE(f):xt(l?_h(f):f),y=c-h;if(y>0){let w=o!==null&&o.toEndOfLine?"selection-highlight":e.fillRow||i?e.bodyStyle:void 0;Ls(this.term," ".repeat(y),w,i)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset()}};LE=/[^\x20-\x7e]/,tk=new Intl.Segmenter(void 0,{granularity:"grapheme"}),NE=!1;f2=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}];g2=Je});function y2(n,e,t=co){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let r=t[n];return r?{kind:"resolve",action:r.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let r=e.ch.toLowerCase();if(r==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(r==="p")return{kind:"continue",selected:Math.max(0,n-1)};let s=t.findIndex(o=>o.hotkey.toLowerCase()===r);if(s>=0){let o=t[s];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:n}}async function WE(n,e){Vr();let t=Je(e.sessionId),r=e.importedFromMachine??"another machine",s=K(e.cwd),o=co.findIndex(p=>p.key==="view");o<0&&(o=0);let i=null,a=null,d=()=>{let m=7+co.length*2+2,h=or(n,{contentHeight:m,title:"Imported session"}),y=h.contentW,w=[{label:"session: ",value:t},{label:"from: ",value:r},{label:"cwd: ",value:s}],k=0;for(let S of w)n.moveTo(h.contentX,h.contentY+k),N(n,"modal-label",` ${S.label}`),N(n,"content",At(S.value,y-S.label.length-2)),k++;k++;let b=jE(n,h,k,{intro:"What do you want to do?",choices:co,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"});return i=h,a=b.firstChoiceRow,h},c=()=>{let p=i,m=a;if(!(p===null||m===null))for(let h=0;h<co.length;h++){let y=co[h];y&&sk(n,p,m+h*2,y.label,h===o)}},l=p=>{p<0||p>=co.length||p===o||(o=p,c())},f=null,u=qE({choiceCount:co.length,layout:()=>i,firstChoiceRow:()=>a,selected:()=>o,select:l,commit:p=>{let m=co[p];m&&f?.(m.key)},back:()=>f?.("back")});return _s({term:n,render:d,onKey:(p,m,h,y)=>{let w=w2(p,h);if(!w)return;let k=y2(o,w);if(k.kind==="cancel"){y("cancel");return}if(k.kind==="back"){y("back");return}if(k.kind==="resolve"){y(k.action);return}l(k.selected)},onMouse:(p,m,h)=>{f=h,u(p,m)}})}function jE(n,e,t,r){let s=t;n.moveTo(e.contentX,e.contentY+s),N(n,"content",` ${r.intro}`),s+=2;let o=e.contentY+s;for(let i=0;i<r.choices.length;i++){let a=r.choices[i];a&&(sk(n,e,e.contentY+s,a.label,i===r.selected),s++,n.moveTo(e.contentX,e.contentY+s),N(n,"list-description",` ${a.description}`),s++)}return s++,n.moveTo(e.contentX,e.contentY+s),N(n,"modal-hint",` ${r.footer}`),{firstChoiceRow:o}}function qE(n){let e=null,t=r=>{let s=n.firstChoiceRow();if(s===null)return null;let o=r-s;if(o<0)return null;let i=Math.floor(o/2);return i<n.choiceCount?i:null};return(r,s)=>{if(r==="MOUSE_WHEEL_UP"){n.select(n.selected()-1);return}if(r==="MOUSE_WHEEL_DOWN"){n.select(n.selected()+1);return}if(r==="MOUSE_LEFT_BUTTON_PRESSED"){e={x:s?.x??-1,y:s?.y??-1};return}let o=s?.y;if(typeof o!="number")return;if(r==="MOUSE_MOTION"){let l=t(o);l!==null&&n.select(l);return}if(r!=="MOUSE_LEFT_BUTTON_RELEASED")return;let i=s?.x,a=e!==null&&i===e.x&&o===e.y;if(e=null,!a)return;let d=n.layout();if(d!==null&&typeof i=="number"&&(i<d.x||i>=d.x+d.w||o<d.y||o>=d.y+d.h)){n.back();return}let c=t(o);c!==null&&n.commit(c)}}function sk(n,e,t,r,s){let i=Qi(` ${s?"\u276F":" "} ${r}`,e.contentW);n.moveTo(e.contentX,t),N(n,s?"list-selected":"content",i)}function w2(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function zE(n,e,t){let r=Je(e.sessionId),s=e.title??K(e.cwd),o=1,i=[{key:"launch",label:"Launch",hotkey:"l",description:"start a new agent session"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=null,d=null,c=()=>{let u=or(n,{contentHeight:11,title:"Open session",overlay:!0}),p=u.contentW,m=0;n.moveTo(u.contentX,u.contentY+m),N(n,"modal-label"," session: "),N(n,"content",At(r,p-10)),m++,n.moveTo(u.contentX,u.contentY+m),N(n,"content"," "+At(s,p-2)),m++,m++;let h=jE(n,u,m,{intro:"What do you want to do?",choices:i,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"});a=u,d=h.firstChoiceRow},l=()=>{let u=a,p=d;if(!(u===null||p===null))for(let m=0;m<i.length;m++){let h=i[m];h&&sk(n,u,p+m*2,h.label,m===o)}},f=u=>{u<0||u>=i.length||u===o||(o=u,l())};return c(),n.hideCursor(),await new Promise(u=>{let p=!1,m=()=>{p=!0},h=k=>{m(),t.pop(),u(k)},y=(k,b,S)=>{if(k==="CTRL_C"||k==="CTRL_D"){h("cancel");return}if(k==="ESCAPE"){h("back");return}if(k==="ENTER"||k==="KP_ENTER"){h(i[o]?.key??"view");return}if(k==="UP"||k==="SHIFT_TAB"){f(o-1);return}if(k==="DOWN"||k==="TAB"){f(o+1);return}if(S?.isCharacter){let C=k.toLowerCase();if(C==="l"){h("launch");return}if(C==="v"){h("view");return}if(C==="n"){f(o+1);return}if(C==="p"){f(o-1);return}}},w=qE({choiceCount:i.length,layout:()=>a,firstChoiceRow:()=>d,selected:()=>o,select:f,commit:k=>{let b=i[k];b&&h(b.key)},back:()=>h("back")});t.push({onKey:(k,b,S)=>{p||y(k,b,S)},onMouse:(k,b)=>{p||w(k,b)},onResize:()=>{p||c()}})})}var co,ok=j(()=>{"use strict";ve();yr();Xi();gn();co=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Zl(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let r=n[t]??"",s=0;for(;s<e.length&&s<r.length&&e[s]===r[s];)s+=1;if(e=e.slice(0,s),e.length===0)break}return e}function KE(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let r=t.indexOf(" "),s=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r);if(e.length===1){let a=e[0]??"",d=o.startsWith(" ")?"":" ";return a+d+o}let i=Zl(e);return i.length<=s.length?null:i+o}var Fh=j(()=>{"use strict"});import*as GE from"os";async function sa(n,e,t={}){let r=t.defaultCwd??(e?await V0(e.cwd):void 0)??GE.homedir();Vr();let s=t.title??"Fork locally \u2014 choose cwd",o=t.intro??"Pick a local cwd for this session:",i=e?[{label:"session: ",value:Je(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:K(e.cwd)}]:[],a=new Wo(r),d=null,c=!1,l=null,f=null,u=null,p=null,m=" Enter accept \xB7 Esc back",h="Enter accept",y="Esc back",w=m.indexOf(h),k=m.indexOf(y),b=()=>{let E=i.length+6;l=or(n,{contentHeight:E,title:s,overlay:t.overlay===!0});let $=l.contentW,F=0;for(let z of i)n.moveTo(l.contentX,l.contentY+F),N(n,"modal-label",` ${z.label}`),N(n,"content",At(z.value,$-z.label.length-2)),F++;F++,n.moveTo(l.contentX,l.contentY+F),N(n,"content",` ${o}`),F+=2,I(F),F+=2;let q=l.contentY+F;d!==null?(n.moveTo(l.contentX,q),N(n,"input-error",` ${At(d,$-2)}`),f=null,u=null,p=null):(n.moveTo(l.contentX,q),N(n,"modal-hint",m),f=q,u={start:l.contentX+w,end:l.contentX+w+h.length-1},p={start:l.contentX+k,end:l.contentX+k+y.length-1})},S=()=>i.length+3,C=0,I=E=>{if(!l)return;let $=E??S();n.moveTo(l.contentX,l.contentY+$).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+$),N(n,"box-border","\u2502"),n.moveTo(l.contentX,l.contentY+$),n.noFormat(" ");let q=Math.max(1,l.contentW-1-2),z=a.text,X=a.cursor;X<C&&(C=X),X-C>=q&&(C=X-q+1),C<0&&(C=0);let oe=z.slice(C,C+q);C>0&&oe.length>0&&(oe="\u2026"+oe.slice(1));let ae=X-C;if(c){N(n,"content",oe);return}ae>=oe.length?(N(n,"content",oe),N(n,"input-cursor"," ")):(N(n,"content",oe.slice(0,ae)),N(n,"input-cursor",oe[ae]??" "),N(n,"content",oe.slice(ae+1)))},T=()=>{if(I(),!l)return;let E=S()+2;n.moveTo(l.contentX,l.contentY+E).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+E),N(n,"box-border","\u2502");let $=l.contentY+E;n.moveTo(l.contentX,$),d!==null?(N(n,"input-error",` ${At(d,l.contentW-2)}`),f=null,u=null,p=null):(N(n,"modal-hint",m),f=$,u={start:l.contentX+w,end:l.contentX+w+h.length-1},p={start:l.contentX+k,end:l.contentX+k+y.length-1})},O=E=>{if(c)return;let $=a.text;c=!0,d=null,T(),Bl($).then(F=>{if(c=!1,F.ok){E({kind:"ok",path:F.path});return}d=F.reason,T()})};return _s({term:n,render:b,overlay:t.overlay===!0,onKey:(E,$,F,q)=>{if(!c){if(E==="ENTER"||E==="KP_ENTER"){O(q);return}if(E==="ESCAPE"){q({kind:"back"});return}if(E==="CTRL_C"||E==="CTRL_D"){q({kind:"cancel"});return}if(E==="TAB"){c=!0,J0(a.text).then(z=>{if(c=!1,z.matches.length===0)return;let X;if(z.matches.length===1)X=z.prefix+z.matches[0];else{let oe=Zl(z.matches);if(oe.length<=z.basePrefix.length)return;X=z.prefix+oe}X!==a.text&&(a.setText(X,{recordUndo:!0}),d=null,T())});return}if(a.handleKey(E,F?.isCharacter===!0)){d=null,T();return}}},onMouse:(E,$,F)=>{if(c||E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let q=$?.x,z=$?.y;if(!(typeof q!="number"||typeof z!="number")){if(l!==null&&(q<l.x||q>=l.x+l.w||z<l.y||z>=l.y+l.h)){F({kind:"back"});return}if(f!==null&&z===f){if(u!==null&&q>=u.start&&q<=u.end){O(F);return}if(p!==null&&q>=p.start&&q<=p.end){F({kind:"back"});return}}}}})}var ik=j(()=>{"use strict";ve();yr();ob();Fh();Xi();lh();gn()});import*as JE from"fs";import*as YE from"os";import*as Lh from"path";function Nh(n,e){let t=e;for(;t>0;){let r=n[t-1]??"";if(/\s/.test(r)){if(r===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function b2(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function k2(n){return n.replace(/\\ /g," ")}function VE(n){return n.replace(/ /g,"\\ ")}function v2(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function S2(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=YE.homedir()+t.slice(1)),Lh.isAbsolute(t)?t:Lh.resolve(e,t)}function I2(n){let e;try{e=JE.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function Bh(n,e,t=I2){let r=k2(n),{dirPrefix:s,base:o}=v2(r);if(s.length===0&&!b2(n)&&o.length===0)return null;let i=S2(s,e),a=t(i);if(a===null)return null;let d=o.startsWith("."),c=a.filter(u=>u.name.startsWith(o)&&(d||!u.name.startsWith(".")));if(c.length===0)return null;let l=c.map(u=>u.isDir?u.name+"/":u.name);if(c.length===1){let u=c[0],p=u.isDir?u.name+"/":u.name;return{replacement:VE(s+p),candidates:l}}let f=Zl(c.map(u=>u.name));return{replacement:VE(s+f),candidates:l}}var ak=j(()=>{"use strict";Fh()});function x2(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function C2(n,e,t){let r=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${r} via npm\u2026`:t.phase==="installed"?`${n} ${r} installed`:`${n} installing ${r} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let s=t.receivedBytes??0,o=t.totalBytes??0,i=(s/1e6).toFixed(1);if(o>0){let a=(o/1e6).toFixed(1),d=Math.min(100,Math.floor(s/o*100));return`${n} downloading ${r} ${i}/${a} MB (${d}%)`}return`${n} downloading ${r} ${i} MB`}return t.phase==="download_done"?`${n} downloaded ${r}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${r}\u2026`:t.phase==="installed"?`${n} ${r} installed`:e||n}function Dh(n,e){let t=!1,r="",s=!1,o=n,i=a=>{t||a===3&&s||a===0&&!s||(s=a===3,x2(a))};return{write(a){t||(o=a,r=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?i(3):a.phase==="installed"&&i(0);let c=C2(o,r,a);r=c,e.write(c)},finalize(){t||(t=!0,i(0),e.finalize())}}}function QE(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),N(n,"status-active",t))},finalize(){e||(e=!0,process.stdout.write(`
|
|
245
245
|
`))}}}var dk=j(()=>{"use strict";gn()});function ck(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}function oa(){return Xt()?.id??"terminal"}function T2(){if(!Ol())return ZE;let n=[];for(let e of ZE)n.push(e),e?.[0]==="*"&&n.push(["^t",dh()?"go to selected session's tab (opening one if needed), or send the composer to a new one":"new tab: selected session, or send the composer to a new one"]);return n}async function lk(n,e){let t=()=>{ge(Ur),ge(Gi),ge(so),ge(Vi),ge(Ji),ge(Hd),ge(Ud),ge(Wd),ge(Ki),ge("\x1B>")};t();let r=e.prefs??ck();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(B=>B.sessionId===e.currentSessionId)?.importedFromMachine&&(r.filters.hostFilter="__all");let s=e.cwd,o=Uh(e.sessions,s),i=P=>{let B=P;return r.filters.cwdOnly&&(B=B.filter(V=>V.cwd===s)),r.filters.includeNonInteractive||(B=B.filter(V=>V.interactive===!0)),B=M2(B,r.filters.hostFilter),B},a=i(o),d={columns:e.config.tui.sessionColumns??Bo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},c=a.map(P=>Kr(P,Date.now())),l=Ps(c,d),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let P=a.findIndex(B=>B.sessionId===e.currentSessionId);P>=0&&(u=P+1)}let m=!1,h="",y=120,w=!1,k=0,b="normal",S=null,C=!1,I="input",T=new oo({history:[],collapsePastes:!1}),O=[],E=!1,$=0,F=0,q=null,z=!1,X=new Map,oe=Ps([],d),ae="",Ce=P=>X.get(P)??null,jt=()=>{let P=Date.now(),B=new Map(a.map(ue=>[ue.sessionId,ue])),V=[];X=new Map;for(let ue of O){let ye=B.get(ue.sessionId);if(!ye)continue;let je=Kr(ye,P);X.set(ue.sessionId,je),V.push(je)}oe=Ps(V,d);let te=Math.max(20,on(n)-Hh);ae=rr(Zs,oe,te,d).padEnd(te)},Pt=null,Xe=null,tt=null,pe=null,Ve=()=>{if(pe!==null){let P=pe;return{plain:P,render:()=>{N(n,"status-active",` ${P}`)}}}if(m){let P=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${h}\u2589 ${P} \xB7 ^c clears`,render:()=>{N(n,"prompt-text",` /${h}`),N(n,"prompt-cursor"," "),N(n,"modal-hint",` ${P} \xB7 ^c clears`)}}}return tt!==null?{plain:tt,render:()=>{N(n,"modal-hint",` ${tt}`)}}:null},Ee=!1,Pe=new oo({history:[]});if(e.initialPrompt&&Pe.setBuffer(e.initialPrompt),e.initialAttachments)for(let P of e.initialAttachments)Pe.addAttachment(P);let In=e.config.tui.promptHistoryMaxEntries;el(D.globalTuiHistoryFile()).then(P=>{let B=P.length>In?P.slice(P.length-In):P;Pe.setHistory(B)}).catch(()=>{});let Me=new Qd(n),ce=Ms(n),Oe=on(n),fe=0,an="",Tr=0,xn=[],Kn=1,Bs=0,ar=0,Xd=0,Go="",Er=[],Pr=1,Zd=0,Vo=[],dn=1,Jo=0,du=0,cu=0,lo=()=>{ce=Ms(n),Oe=on(n);let P=Math.max(10,Oe-Hh-1);Tr=Math.max(10,Oe-XE);let B=Math.max(10,Oe-8),V=Pe.state().attachments.length,te=V>0?` \xB7 \u{1F4CE}\xD7${V}`:"",ue=Math.max(10,B-te.length);an=E2(s,ue)+te;let ye=Pe.state();xn=Ns(ye.buffer,Tr);let je=ao(xn,ye,eu);Kn=je.rendered,Bs=je.windowStart,ar=je.cursorVisualRow,Xd=je.cursorVisualCol;let ft=6+Kn,_t=Math.max(3,ce-ft);fe=Math.min(a.length,_t),Go=rr(Zs,l,P,d).padEnd(P),Er=c.map(Ut=>rr(Ut,l,P,d).padEnd(P))},Yh=()=>{c=a.map(P=>Kr(P,Date.now())),l=Ps(c,d),f=1+a.length,lo()},On=()=>{let P=i(o);m&&h.length>0?a=P.filter(B=>_2(B,h)):a=P,Yh(),m?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+fe>a.length&&(p=Math.max(0,a.length-fe)),Mr()},We=P=>{if(P!==void 0){let B=a.findIndex(V=>V.sessionId===P);if(B>=0){u=B+1,Mr();return}}u=a.length>0?1:0,p=0,Mr()},Mr=()=>{if(u===0)return;let P=u-1;P<p?p=P:P>=p+fe?p=P-fe+1:p+fe>a.length&&(p=Math.max(0,a.length-fe))},uo=()=>Math.max(2,Oe-3),$t=!1,qt=!0,Dt=!1,Yo=[],dr=e.composerAgentId,Zr=e.composerModel,ec=!1,ke=()=>{let P=dr;if(!P)return"";let B=Zr;return B?`${P}\u2022${B}`:P},Cn=null,St=null,Gn=null,tc=()=>{let P=uo(),B=`\u2500 ${an} `,V=ke(),te="";if(V.length>0){let Ot=`\u2500 ${V} `;Ot.length+B.length+1<=P&&(te=Ot)}let ue=Math.max(1,P-B.length-te.length),ye="\u2500".repeat(ue),je=(u===0||$t)&&qt;if(Cn=B.length>0?{start:2,end:1+B.length}:null,te.length>0){let Ot=1+B.length+ue+1;St={start:Ot,end:Ot+te.length-1}}else St=null;let ft=je?"box-border-focused":"box-border",_t=je?"box-border-focused-hover":"box-border-hover",Ut=(Ot,ss)=>{N(n,ss?_t:ft,Ot)};N(n,ft,"\u256D"),Ut(B,Gn==="cwd"),N(n,ft,ye),te&&Ut(te,Gn==="agent"),N(n,ft,"\u256E")},fo=()=>{let P=uo(),B="\u2500".repeat(P);(u===0||$t)&&qt?N(n,"box-border-focused",`\u2570${B}\u256F`):N(n,"box-border",`\u2570${B}\u256F`)},cr=()=>{let P=Ve();if(P===null)return;let B=Math.max(0,on(n)-2);if(P.plain.length>B){let V=P.plain.slice(0,Math.max(0,B-1))+"\u2026";N(n,"modal-hint",` ${V}`);return}P.render()},Qo=P=>{let B=xn[P];return B?(Pe.state().buffer[B.bufferIdx]??"").slice(B.startCol,B.endCol):""},Ds=P=>{let B=uo(),V=Qo(P),te=Math.max(0,B-1-V.length),ue=" ".repeat(te);(u===0||$t)&&qt?(N(n,"box-border-focused","\u2502"),N(n,"content",` ${V}${ue}`),N(n,"box-border-focused","\u2502")):(N(n,"box-border","\u2502"),N(n,"content",` ${V}${ue}`),N(n,"box-border","\u2502"))},po=P=>{let B=Er[P]??"",V=a[P],te=V&&V.priority&&V.priority>0?"* ":" ";u===P+1&&!$t&&qt?N(n,"list-selected",`${te}${B}`):N(n,"content",`${te}${B}`)},da=()=>{let P=p,B=Math.max(0,a.length-p-fe),V=[];if(r.filters.cwdOnly&&V.push({kind:"plain",text:"cwd-only"}),r.filters.hostFilter!=="__all"){let te=r.filters.hostFilter==="__local"?"host: local":`host: ${r.filters.hostFilter}`;V.push({kind:"host",text:te})}return r.filters.includeNonInteractive&&V.push({kind:"plain",text:"+non-interactive"}),P>0&&V.push({kind:"plain",text:`\u2191 ${P} above`}),B>0&&V.push({kind:"plain",text:`\u2193 ${B} below`}),V},ca=()=>{let P=da();return P.length===0?"":` ${P.map(B=>B.text).join(" \xB7 ")}`},es=P=>Je(P),nc=()=>{let P=S?`${S.sessionId}|${S.status}`:"";return["ind",b,P,Pt?`${Pt.text}${Pt.cursor}`:"",Xe??"",m?`1|${h}|${a.length}`:"0",ca(),fn?"h1":"h0",bo?"ho1":"ho0"].join("")},Ke=()=>{at(()=>{Me.paintRow(ns(),nc(),()=>{let P=()=>{Jt=null,ur=null};if(b==="confirm-kill"&&S)P(),N(n,"prompt-text",` kill ${es(S.sessionId)}? [y/N]`);else if(b==="confirm-delete"&&S)P(),S.status==="warm"?N(n,"prompt-destructive",` kill + delete ${es(S.sessionId)}? [y/N]`):N(n,"prompt-destructive",` delete ${es(S.sessionId)}? [y/N]`);else if(b==="busy"&&S)P(),N(n,"modal-status",` working on ${es(S.sessionId)}\u2026`);else if(b==="rename"&&S&&Pt){P();let B=Pt.text,V=Pt.cursor;N(n,"prompt-text"," title: "),N(n,"prompt-text",B.slice(0,V)),V<B.length?(N(n,"prompt-cursor",B[V]??" "),N(n,"prompt-text",B.slice(V+1))):N(n,"prompt-cursor"," "),N(n,"modal-hint"," Enter saves \xB7 Esc cancels")}else if(Xe!==null)P(),N(n,"modal-status",` ${Xe}`);else{let B=da(),V=ca(),te="Esc \xB7 Go Back",ue=te.length,ye=5,je=V.length,ft=Math.max(1,Oe-je-ue-ye);if(ur=null,B.length>0){N(n,"modal-hint"," ");let _t=3;for(let Ut=0;Ut<B.length;Ut++){let Ot=B[Ut];Ut>0&&(N(n,"modal-hint"," \xB7 "),_t+=3),Ot.kind==="host"?(ur={start:_t,end:_t+Ot.text.length-1},bo?N(n,"content",Ot.text):N(n,"modal-hint",Ot.text)):N(n,"modal-hint",Ot.text),_t+=Ot.text.length}}N(n,"modal-hint"," ".repeat(ft)),fn?N(n,"content",te):N(n,"modal-hint",te),Jt={start:Oe-ye-ue+1,end:Oe-ye}}})})},ho=P=>Pr+1+P,ts=()=>Pr+Kn+1,_r=()=>Pr+Kn+3,Xo=P=>_r()+1+(P-p),ns=()=>_r()+1+fe,Mt=()=>{let P=ar-Bs;if(P<0||P>=Kn)return;let B=3+Xd;n.moveTo(B,ho(P))},Fn=()=>qt?u===0?"f":$t?"h":"u":"x",rs=()=>`ct|${Fn()}|${uo()}|${an}|${ke()}|${Gn??""}`,nt=()=>`cb|${Fn()}|${uo()}`,rc=()=>pe!==null?`cs|i|${pe}`:m?`cs|s|${h}|${a.length}`:tt!==null?`cs|h|${tt}`:"blank",Zo=P=>`cbb|${Fn()}|${uo()}|${Qo(P)}`,Hs=()=>`h|${Go}`,cn=P=>{let B=a[P],V=B&&B.priority&&B.priority>0?"* ":" ",te=Er[P]??"";return`sr|${u===P+1&&!$t&&qt?"1":"0"}|${V}${te}`},bt=()=>{at(()=>{n.hideCursor(),lo(),Mr(),Pr=1,Me.ensureSize(Oe,ce),Me.paintRow(Pr,rs(),()=>{tc()});for(let P=0;P<Kn;P++){let B=Bs+P;Me.paintRow(ho(P),Zo(B),()=>{Ds(B)})}Me.paintRow(ts(),nt(),()=>{fo()}),Me.paintRow(ts()+1,rc(),()=>cr()),Me.paintRow(_r(),Hs(),()=>{N(n,"list-header",` ${Go}`)});for(let P=0;P<fe;P++){let B=p+P,V=_r()+1+P;B<a.length?Me.paintRow(V,cn(B),()=>{po(B)}):Me.paintRow(V,"blank",()=>{})}Ke();for(let P=ns()+1;P<=ce;P++)Me.paintRow(P,"blank",()=>{});u===0&&(Mt(),n.hideCursor(!1))})},ei=()=>{Me.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),bt()},A=()=>{at(()=>{n.hideCursor(),Me.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),N(n,"modal-title"," Picker hotkeys"),n.noFormat(`
|
|
246
246
|
|
|
@@ -303,7 +303,7 @@ Couldn't reach the daemon (${r.message}) \u2014 it'll pick up the new token next
|
|
|
303
303
|
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${s} signal=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${s} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${s} signal=${o}`)}for(let i of this.exitHandlers)i(s,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
|
|
304
304
|
stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...Za(),...e.plan.env,...e.extraEnv??{}},r=Q$(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return r.unref(),new n(e,r)}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()} ---
|
|
305
305
|
`),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()} ---
|
|
306
|
-
`),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(XS),this.exited||this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} still has not exited ${XS}ms after SIGKILL; giving up on the reap`)))}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 r=setTimeout(()=>{this.child.off("exit",s),t()},e),s=()=>{clearTimeout(r),t()};this.child.once("exit",s)})}},Z$=2e3,XS=5e3;function eO(n){try{let e=D.agentLogFile(n);of.mkdirSync(ZS.dirname(e),{recursive:!0});let t=of.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}Hc();import*as Li from"fs/promises";import*as Lx from"os";import*as al from"path";import{customAlphabet as
|
|
306
|
+
`),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(XS),this.exited||this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} still has not exited ${XS}ms after SIGKILL; giving up on the reap`)))}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 r=setTimeout(()=>{this.child.off("exit",s),t()},e),s=()=>{clearTimeout(r),t()};this.child.once("exit",s)})}},Z$=2e3,XS=5e3;function eO(n){try{let e=D.agentLogFile(n);of.mkdirSync(ZS.dirname(e),{recursive:!0});let t=of.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}Hc();import*as Li from"fs/promises";import*as Lx from"os";import*as al from"path";import{customAlphabet as aL}from"nanoid";Hg();ws();ed();yr();my();us();ve();import*as bn from"fs/promises";import*as kn from"path";ve();import*as wf from"path";import{createHash as bF}from"crypto";var Wr=class extends Error{constructor(e,t){super(`provider "${e}" does not support ${t}; check capabilities().supports before calling`),this.name="WorkspaceUnsupportedError"}};function yd(n){let e=bF("sha256").update(wf.resolve(n)).digest("hex").slice(0,12);return wf.join(Re(),"workspaces",e)}async function bf(n,e,t=100){if(await e(n))return n;for(let r=2;r<=t;r+=1){let s=`${n}-${r}`;if(await e(s))return s}}function Mi(n,e=10){if(n.length<=e)return[...n];let t=n.slice(0,e),r=n.length-e;return[...t,`... and ${r} more`]}function gy(n){return n.changedPaths.length>0||n.recorded!==void 0&&n.recorded!==n.actual}function kF(n){let e=[];for(let t of n){if(t.changedPaths.length===0){e.push(`${t.relPath} (nested tree advanced to ${t.actual.slice(0,8)})`);continue}for(let r of t.changedPaths)e.push(`${t.relPath}/${r}`)}return e}function yy(n,e){let t=new Set(e.map(s=>s.relPath));return[...n.filter(s=>!t.has(s.replace(/\/$/,""))),...kF(e.filter(gy))]}function kf(n){let e=n.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e.slice(0,64):"workspace"}var wy="copy",QI=new Set([".git"]);function Jc(n){return`${n}.manifest.json`}async function YI(n){let e=new Map,t=[n];for(;t.length>0;){let r=t.pop();if(r===void 0)break;let s;try{s=await bn.readdir(r,{withFileTypes:!0})}catch{continue}for(let o of s){let i=kn.join(r,o.name);if(!(r===n&&QI.has(o.name))){if(o.isDirectory()){t.push(i);continue}if(o.isFile())try{let a=await bn.stat(i);e.set(kn.relative(n,i),{size:a.size,mtimeMs:a.mtimeMs})}catch{continue}}}}return e}var vf=class{kind=wy;capabilities(){return{cheapWorkspaces:!1,sharedHistory:!1,nonMutatingCapture:!0,conflictReporting:!1,locking:!1,requiresServer:!1,supports:{record:!1,integrate:!1,captureWorkingState:!1,changedPaths:!1,environmentNotes:!0,rematerialize:!1,nestedTrees:!1}}}async materializeNested(){return{ok:!0,count:0}}async retainSnapshot(){}async dropSnapshotRef(){}async rematerialize(e){return{ok:!1,reason:`copy provider retains nothing outside ${e.path}; it cannot be rebuilt`}}async createWorkspace(e){if(e.from!==void 0)return{ok:!1,reason:"copy provider cannot create from a snapshot; it records none"};let t=kn.resolve(e.sourceCwd),r=e.contentFrom!==void 0?kn.resolve(e.contentFrom):t;try{if(!(await bn.stat(r)).isDirectory())return{ok:!1,reason:`${r} is not a directory`}}catch{return{ok:!1,reason:`${r} does not exist`}}let s=yd(t);try{await bn.mkdir(s,{recursive:!0})}catch(c){return{ok:!1,reason:`could not create workspace root: ${String(c)}`}}let o=await bf(kf(e.label),async c=>bn.access(kn.join(s,c)).then(()=>!1).catch(()=>!0));if(o===void 0)return{ok:!1,reason:`no free name available for "${e.label}"`};let i=kn.join(s,o);try{await bn.cp(r,i,{recursive:!0,errorOnExist:!1,force:!0,filter:c=>{let l=kn.relative(r,c);if(l.length===0)return!0;let f=l.split(kn.sep)[0];return f===void 0||!QI.has(f)}})}catch(c){return await bn.rm(i,{recursive:!0,force:!0}).catch(()=>{}),{ok:!1,reason:`copy failed: ${String(c)}`}}let a=await YI(i),d={sourceCwd:t,label:o,createdAt:new Date().toISOString(),entries:Object.fromEntries(a)};return await mn(Jc(i),d,{pretty:!1}),{ok:!0,workspace:{path:i,sourceCwd:t,label:o,provider:this.kind}}}async removeWorkspace(e,t){if(!t.force){let r=await this.status(e);if(!r.clean)throw new Error(`workspace ${e.path} has ${r.changedPaths.length} changed path(s); pass force to remove`)}await bn.rm(e.path,{recursive:!0,force:!0}),await bn.rm(Jc(e.path),{force:!0})}async listWorkspaces(e){let t=yd(kn.resolve(e)),r;try{r=await bn.readdir(t)}catch{return[]}let s=[];for(let o of r){if(o.endsWith(".manifest.json"))continue;let i=kn.join(t,o),a=await Wt(Jc(i));a!==void 0&&s.push({path:i,sourceCwd:a.sourceCwd,label:a.label,provider:this.kind})}return s}async status(e){let t=await Wt(Jc(e.path)),r=await YI(e.path);if(t===void 0)return{clean:!1,changedPaths:[...r.keys()].sort(),hasRecordedWork:!1};let s=[];for(let[o,i]of r){let a=t.entries[o];(a===void 0||a.size!==i.size||a.mtimeMs!==i.mtimeMs)&&s.push(o)}for(let o of Object.keys(t.entries))r.has(o)||s.push(o);return s.sort(),{clean:s.length===0,changedPaths:s,hasRecordedWork:!1}}async statusReport(e){let{changedPaths:t}=await this.status(e),r=t.length===0?["no changes since this copy was made"]:[`${t.length} changed file(s) since this copy was made:`,...Mi(t.map(s=>` ${s}`))];return r.push(`Not tracking ${K(e.sourceCwd)}: a copied directory has no shared history, so there is nothing to be in or out of sync with.`),r}async environmentNotes(e){return[`This directory is an isolated copy of ${e.sourceCwd}. It is not under version control: there is no history, no branches, and version-control commands will not behave as they would in the original.`,"Changes here are not automatically returned to the original directory."]}async captureWorkingState(){throw new Wr(this.kind,"captureWorkingState")}async record(){throw new Wr(this.kind,"record")}async attributeOrphan(e){let t=await Wt(Jc(e));if(t?.sourceCwd!==void 0)return{path:e,sourceCwd:t.sourceCwd,label:t.label??kn.basename(e),provider:this.kind}}async discardLine(){return{ok:!0,dropped:0}}ownsLine(){return!1}async pruneStale(){}async changedPaths(){throw new Wr(this.kind,"changedPaths")}async integrate(){return{ok:!1,conflicts:[],declined:!0,reason:`the "${this.kind}" provider keeps no history, so there is nothing to integrate from`}}async currentState(){}async contentId(){}async currentLineName(){}async resolveRoot(e){return e}async resolveRetained(){}async contains(){return!1}async divergence(){}async changedPathsBetween(){return[]}async captureDelta(){throw new Wr(this.kind,"captureDelta")}async applyDelta(){return{ok:!1,reason:`the "${this.kind}" provider cannot reproduce a captured change`}}async resetTo(){return{ok:!1,reason:`the "${this.kind}" provider records no state to return to`}}async integrationInProgress(){return!1}async abortIntegration(){}async conflictedPaths(){return[]}async listNested(){return[]}async captureNested(){return[]}async reproduceNested(){return{applied:[],failed:[]}}async integrateNested(){return{applied:[],failed:[]}}async lock(){throw new Wr(this.kind,"lock")}async unlock(){throw new Wr(this.kind,"unlock")}};ve();import{execFile as rx}from"child_process";import{randomBytes as IF}from"crypto";import*as jr from"fs/promises";import*as sx from"os";import*as wt from"path";function vF(n){let e=n.indexOf(" ");return e===-1?{key:n,value:""}:{key:n.slice(0,e),value:n.slice(e+1)}}function XI(n){let e=[],t,r=()=>{t!==void 0&&(e.push(t),t=void 0)};for(let s of n.split(`
|
|
307
307
|
`)){let o=s.replace(/\r$/,"");if(o.length===0){r();continue}let{key:i,value:a}=vF(o);if(i==="worktree"){r(),t={path:a,bare:!1,detached:!1};continue}if(t!==void 0)switch(i){case"HEAD":t.head=a;break;case"branch":t.branch=a;break;case"bare":t.bare=!0;break;case"detached":t.detached=!0;break;case"locked":t.lockedReason=a;break;case"prunable":t.prunableReason=a;break;default:break}}return r(),e}function ZI(n){if(n===void 0)return;let e="refs/heads/";return n.startsWith(e)?n.slice(e.length):n}var xf="git",ex="hydra-acp:",by="hydra",ze=5e3,sn=12e4,Sf=9e5;function tx(n){return jr.access(n).then(()=>!0).catch(()=>!1)}function xF(n){return jr.realpath(n).catch(()=>n)}function we(n,e,t,r){return new Promise(s=>{rx("git",n,{cwd:e,timeout:t,maxBuffer:8*1024*1024,...r?{env:{...process.env,...r}}:{}},(o,i,a)=>{s({ok:!o,stdout:i??"",stderr:a??""})})})}function ky(n,e,t,r=sn){return new Promise(s=>{let o=rx("git",n,{cwd:e,timeout:r,maxBuffer:67108864},(i,a,d)=>{s({ok:!i,stdout:a??"",stderr:d??""})});o.stdin?.on("error",()=>{}),o.stdin?.end(t)})}function vy(n){let e=[];for(let t of n.split(`
|
|
308
308
|
`)){let r=t.replace(/\r$/,"");if(r.length<4)continue;let s=r.slice(3),o=s.indexOf(" -> ");e.push({code:r.slice(0,2),path:o===-1?s:s.slice(o+4)})}return e}var If=class{kind=xf;refRoot(e){return e.vcs?.repoRoot??e.sourceCwd}ownsLine(e){return e.startsWith(`${by}/`)}capabilities(){return{cheapWorkspaces:!0,sharedHistory:!0,nonMutatingCapture:!0,conflictReporting:!0,locking:!0,requiresServer:!1,supports:{record:!0,integrate:!0,captureWorkingState:!0,changedPaths:!1,environmentNotes:!0,rematerialize:!0,nestedTrees:!0}}}async materializeNested(e,t){if(!await tx(wt.join(e.path,".gitmodules")))return{ok:!0,count:0};let s=await we(["submodule","update","--init","--recursive",...t?.discardLocal===!0?["--force"]:[]],e.path,Sf);if(!s.ok)return{ok:!1,count:0,reason:s.stderr.trim()||"git submodule update --init failed"};if(t?.discardLocal===!0){let a=await we(["submodule","foreach","--recursive","git","reset","--hard"],e.path,Sf);if(!a.ok)return{ok:!1,count:0,reason:a.stderr.trim()||"could not reset submodules"};let d=t.purgeIgnored===!0?"-ffdx":"-fd",c=await we(["submodule","foreach","--recursive","git","clean",d],e.path,Sf);if(!c.ok)return{ok:!1,count:0,reason:c.stderr.trim()||"could not clean submodules"}}let o=await we(["submodule","status","--recursive"],e.path,ze);return{ok:!0,count:o.ok?o.stdout.split(`
|
|
309
309
|
`).filter(a=>a.trim().length>0).length:0}}async rematerialize(e){let t=e.vcs?.branch;if(t===void 0)return{ok:!1,reason:"workspace has no recorded branch to restore from"};let r=this.refRoot(e);if(!await tx(r))return{ok:!1,reason:`source repository ${r} no longer exists`};let s=await we(["rev-parse","--verify","--quiet",`refs/heads/${t}`],r,ze);if(!s.ok||s.stdout.trim().length===0)return{ok:!1,reason:`branch ${t} no longer exists in ${r}`};await we(["worktree","unlock",e.path],r,ze),await we(["worktree","prune"],r,ze);let o=await we(["worktree","add",e.path,t],r,sn);return o.ok?{ok:!0,workspace:{...e,line:t,vcs:{...e.vcs??{},kind:"git",branch:t,repoRoot:r}}}:{ok:!1,reason:`could not restore worktree: ${o.stderr.trim()||"unknown error"}`}}async createWorkspace(e){let t=wt.resolve(e.sourceCwd),r=await we(["rev-parse","--show-toplevel"],t,ze);if(!r.ok)return{ok:!1,reason:`${t} is not a git repository (or git is unavailable)`};let s=r.stdout.trim();if(s.length===0)return{ok:!1,reason:`could not resolve the repository root for ${t}`};let o=await we(["rev-parse","HEAD"],s,ze);if(!o.ok)return{ok:!1,reason:`${s} has no commits yet, so there is nothing to branch from`};let i=e.from??o.stdout.trim(),a=kf(e.label),d=yd(t);try{await jr.mkdir(d,{recursive:!0})}catch(p){return{ok:!1,reason:`could not create workspace root: ${String(p)}`}}let c=await bf(a,async p=>await jr.access(wt.join(d,p)).then(()=>!0).catch(()=>!1)?!1:!(await we(["rev-parse","--verify","--quiet",`refs/heads/${by}/${p}`],s,ze)).ok);if(c===void 0)return{ok:!1,reason:`no free name available for "${a}"`};let l=wt.join(d,c),f=`${by}/${c}`,u=await we(["worktree","add","--no-track","-b",f,l,i],s,sn);return u.ok?{ok:!0,workspace:{path:l,sourceCwd:t,label:c,provider:this.kind,snapshot:i,line:f,vcs:{kind:"git",branch:f,base:i,repoRoot:s}}}:{ok:!1,reason:`git worktree add failed: ${u.stderr.trim()||"unknown error"}`}}async removeWorkspace(e,t){if(!t.force){let o=await this.status(e);if(!o.clean)throw new Error(`workspace ${e.path} has ${o.changedPaths.length} changed path(s)${o.hasRecordedWork?" and unintegrated recorded work":""}; pass force to remove`)}let r=this.refRoot(e);await this.unlock(e).catch(()=>{});let s=await we(["worktree","remove","--force",e.path],r,sn);t.discardLine===!0&&e.vcs?.branch!==void 0&&await we(["branch","-D",e.vcs.branch],r,ze),s.ok||(await jr.rm(e.path,{recursive:!0,force:!0}),await we(["worktree","prune"],r,ze))}async listWorkspaces(e){let t=wt.resolve(e),r=await we(["rev-parse","--show-toplevel"],t,ze);if(!r.ok)return[];let s=r.stdout.trim(),o=await we(["worktree","list","--porcelain"],s,ze);if(!o.ok)return[];let i=yd(t),a=await xF(i),d=[];for(let c of XI(o.stdout)){let l=wt.dirname(c.path);if(l!==i&&l!==a)continue;let f=wt.join(i,wt.basename(c.path)),u={kind:"git",repoRoot:s},p=ZI(c.branch);p!==void 0&&(u.branch=p),c.head!==void 0&&(u.head=c.head),c.lockedReason!==void 0&&(u.locked=c.lockedReason);let m=c.lockedReason?.startsWith(ex)===!0;d.push({path:f,sourceCwd:t,label:wt.basename(f),...m?{heldByUs:!0}:{},provider:this.kind,...p!==void 0?{line:p}:{},vcs:u})}return d}async status(e){let t=await we(["status","--porcelain","--untracked-files=all"],e.path,ze);if(!t.ok)return{clean:!1,changedPaths:[],hasRecordedWork:!1};let r=vy(t.stdout),s=r.map(a=>a.path),o=r.some(({code:a})=>a!=="??"&&a[0]!==" "&&a[0]!=="?"),i=!1;if(e.snapshot!==void 0){let a=await we(["rev-list","--count",`${e.snapshot}..HEAD`],e.path,ze);a.ok&&(i=Number.parseInt(a.stdout.trim(),10)>0)}return{clean:s.length===0&&!i,changedPaths:s,hasRecordedWork:i,hasStagedWork:o}}async lock(e,t){let r=this.refRoot(e);await we(["worktree","lock","--reason",`${ex}${t}`,e.path],r,ze)}async unlock(e){let t=this.refRoot(e);await we(["worktree","unlock",e.path],t,ze)}async environmentNotes(e){let t=[],r=e.vcs?.branch;return t.push(`This directory is a git worktree of ${e.sourceCwd}${r!==void 0?`, on branch ${r}`:""}. Do not read or write ${e.sourceCwd} directly; paths under it refer to the corresponding file here. Prefer repo-relative paths, which are identical in both.`),t.push("`.git` here is a file, not a directory. That is normal for a worktree and does not need repairing."),await jr.access(wt.join(e.path,".gitmodules")).then(()=>!0).catch(()=>!1)&&t.push("Submodules here are initialized and checked out at the commits this tree records, which means each sits on a detached HEAD. That is normal and does not need repairing. Never re-add a submodule's contents as ordinary tracked files in the superproject: that silently corrupts the integration back to the source branch."),t}async statusReport(e){let t=[],r=await we(["status","--porcelain","--untracked-files=all"],e.path,ze);if(r.ok){let s=vy(r.stdout);if(s.length===0)t.push("no uncommitted changes");else{let o=0,i=0,a=0;for(let{code:c}of s){if(c==="??"){a+=1;continue}c[0]!==" "&&c[0]!=="?"&&(o+=1),c[1]!==" "&&c[1]!=="?"&&(i+=1)}let d=[];o>0&&d.push(`${o} staged`),i>0&&d.push(`${i} unstaged`),a>0&&d.push(`${a} untracked`),t.push(`${d.join(", ")}:`),t.push(...Mi(s.map(c=>` ${c.code} ${c.path}`)))}}return t.push(...await this.syncLines(e)),t}async syncLines(e){if(e.vcs?.branch===void 0)return[];let[t,r]=await Promise.all([we(["rev-parse","HEAD"],e.sourceCwd,ze),we(["rev-parse","HEAD"],e.path,ze)]),s=t.stdout.trim(),o=r.stdout.trim();if(!t.ok||!r.ok||s.length===0||o.length===0)return[];let i=K(e.sourceCwd);if(s===o)return[`in sync with ${i}`];let a=await we(["rev-list","--left-right","--count",`${s}...${o}`],e.path,ze),d=a.stdout.trim().split(/\s+/).map(u=>Number.parseInt(u,10)),c=d[0],l=d[1];if(!a.ok||c===void 0||l===void 0||!Number.isFinite(c)||!Number.isFinite(l))return[];let f=[];return c>0&&f.push(`${c} commit(s) behind ${i}. \`/hydra workspace sync\` brings them in; landing is fast-forward-only, so this also unblocks \`stop\`.`),l>0&&f.push(`${l} commit(s) recorded here and not landed yet.`),f}async captureWorkingState(e,t){let r=wt.join(sx.tmpdir(),`hydra-index-${process.pid}-${IF(6).toString("hex")}`),s={GIT_INDEX_FILE:r};try{let o=await we(["rev-parse","--verify","HEAD"],e,ze),i=o.ok&&o.stdout.trim().length>0;if(i){let f=await we(["read-tree","HEAD"],e,sn,s);if(!f.ok)throw new Error(`could not seed the snapshot index: ${f.stderr.trim()}`)}let a=await we(["add","-A"],e,sn,s);if(!a.ok)throw new Error(`could not stage working state: ${a.stderr.trim()}`);let d=await we(["write-tree"],e,sn,s);if(!d.ok||d.stdout.trim().length===0)throw new Error(`could not write tree: ${d.stderr.trim()}`);let c=["commit-tree",d.stdout.trim(),"-m",t];i&&c.push("-p",o.stdout.trim());let l=await we(c,e,sn,s);if(!l.ok||l.stdout.trim().length===0)throw new Error(`could not create snapshot commit: ${l.stderr.trim()}`);return l.stdout.trim()}finally{await jr.rm(r,{force:!0}).catch(()=>{})}}async retainSnapshot(e,t,r){let s=this.refRoot(e);await we(["update-ref","--create-reflog",t,r],s,ze)}async dropSnapshotRef(e,t){let r=this.refRoot(e);await we(["update-ref","-d",t],r,ze)}async currentState(e){let t=await we(["rev-parse","HEAD"],e,ze),r=t.stdout.trim();return t.ok&&r.length>0?r:void 0}async contentId(e,t){let r=await we(["rev-parse",`${t}^{tree}`],e,ze),s=r.stdout.trim();return r.ok&&s.length>0?s:void 0}async currentLineName(e){let t=await we(["rev-parse","--abbrev-ref","HEAD"],e,ze),r=t.stdout.trim();return t.ok&&r.length>0?r:void 0}async resolveRoot(e){let t=await we(["rev-parse","--show-toplevel"],e,ze),r=t.stdout.trim();return t.ok&&r.length>0?r:void 0}async resolveRetained(e,t){let r=await we(["rev-parse","--verify","--quiet",`${t}^{commit}`],this.refRoot(e),ze),s=r.stdout.trim();return r.ok&&s.length>0?s:void 0}async contains(e,t){return(await we(["merge-base","--is-ancestor",t.state,t.within],e,ze)).ok}async divergence(e,t,r){let s=await we(["rev-list","--left-right","--count",`${t}...${r}`],e,ze);if(!s.ok)return;let o=s.stdout.trim().split(/\s+/).map(d=>Number.parseInt(d,10)),i=o[0],a=o[1];if(!(i===void 0||a===void 0||!Number.isFinite(i)||!Number.isFinite(a)))return{ahead:i,behind:a}}async changedPathsBetween(e,t,r){let s=await we(["diff","--name-only",t,r],e,ze);return s.ok?s.stdout.split(`
|
|
@@ -322,7 +322,7 @@ ${e}
|
|
|
322
322
|
|
|
323
323
|
${dy}`:`${t}
|
|
324
324
|
|
|
325
|
-
${dy}`;return lx(n,r,VI)}function FF(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let r=t.content;return r&&typeof r.text=="string"?r.text:""}function LF(n){let e=new Set;cx(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&cx(e,t.availableModels),e}function cx(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let r=t.modelId??t.value??t.id;typeof r=="string"&&r.length>0&&n.add(r)}}}ws();Cy();ve();var BF=NF("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",12),DF=2,$f=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??DF}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let r=t?.targetAgentId;if(this.inflight.has(e))return;let s=this.queued[e];if(s&&s.kind==="title"){this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}};return}this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let r=t-Date.now();if(r<=0)return;let s=[...this.inflight.values()];if(s.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(s),new Promise(o=>{setTimeout(o,r).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let r=this.queued[t];delete this.queued[t];let s=this.runOne(t,r).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,s)}}async runOne(e,t){let r=t.kind,s=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let d=r==="compaction"?s??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let l=await gr(c,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&s===void 0,u=r==="compaction"?this.opts.compactionModel??(f?o.currentModel:void 0):this.opts.synopsisModel,p=D.sessionDir(e);if(await vx.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${i.length} model=${JSON.stringify(u??"(default)")} cwd=${p}`),r==="compaction"){let m=this.opts.compactionMaxIterations??3,h=0,y=a??0,w,k=0,b,S=Date.now(),C=BF(),I={targetAgentId:s},T=E=>this.opts.onCompactionStateChange?.(e,{runId:C,...E},I)??Promise.resolve(),O=E=>{this.opts.broadcastHydraCompaction?.(e,E,I)};await T({status:"requested",requestedAt:S}),O({sessionUpdate:"_hydra_compaction",phase:"started",requestedAt:S});try{do{h++,this.opts.logger?.info(`synopsis: compaction iteration ${h} sessionId=${e} historyLen=${i.length} watermark=${y}`);let E=await this.opts.histories.load(e,{maxEntries:1/0});if(E.length===y)break;let $=await ux({agentId:d,cwd:p,plan:l,history:E,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(q,z)=>{T({status:"running",requestedAt:S,iter:h,worker:{upstreamSessionId:q,pid:z??0}})},onFailure:q=>{b=q}});if($){let q=wx($.synopsis,E);q&&bx(q)&&(await this.opts.persistSynopsis(e,q,E.length),w=q,k=E.length,b=void 0,await T({status:"running",requestedAt:S,iter:h}),O({sessionUpdate:"_hydra_compaction",phase:"iteration",iter:h,historyLen:E.length}),await this.opts.onSynthesisArtifact?.(e,q,k,s,C),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${h} fields=${kx(q)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${h} returned no result`);if(y=E.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(h<m);if(w)this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} runId=${C} watermark=${k} iterations=${h}`+(h>=m?` (hit maxIterations=${m})`:"")),O({sessionUpdate:"_hydra_compaction",phase:"converged",iter:h,summarizedThroughEntry:k});else{h>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${b??"no reason captured"}`);let E=b??(h===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${h} iteration(s)`);await T({status:"failed",requestedAt:S,iter:h,lastError:E}),O({sessionUpdate:"_hydra_compaction",phase:"failed",error:E}),s&&await this.opts.onSynthesisUnavailable?.(e,s,E)}}catch(E){let $=E instanceof Error?E.message:String(E);if(this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${$}`),await T({status:"failed",requestedAt:S,iter:h,lastError:$}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"_hydra_compaction",phase:"failed",error:$},{targetAgentId:s}),s)try{await this.opts.onSynthesisUnavailable?.(e,s,$)}catch{}}}else{let m=await _f({agentId:d,cwd:p,plan:l,history:i,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let h=wx(m.synopsis,i);h&&bx(h)?(await this.opts.persistSynopsis(e,h,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${kx(h)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function wx(n,e){let t=mx(e),r=hx(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:r.length>0?r:n.tools_used}:t.length===0&&r.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:r.length>0?r:void 0}}function bx(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function kx(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}ve();import*as ut from"fs/promises";import{createReadStream as KF}from"fs";import{createGunzip as GF,gzip as VF,gunzip as JF}from"zlib";import{createInterface as YF}from"readline";import{promisify as Rx}from"util";function Sx(n){return n==="summary"?"summary":"inline"}var Ay=256,HF=["totalMatches","totalFiles","referenceCount","truncated","exitCode"],UF=["content","stdout","stderr"];function Ix(n,e){return e!=="summary"?n:n.map(WF)}function WF(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,r=t.update;if(!r||typeof r!="object"||Array.isArray(r))return n;let s=r;if(s.sessionUpdate!=="tool_call"&&s.sessionUpdate!=="tool_call_update")return n;let o={...s};Array.isArray(s.content)&&(o.content=s.content.map(xx));let i=s.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=Of(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata);for(let c of HF)a[c]!==void 0&&(d[c]=a[c]);for(let c of UF)typeof a[c]=="string"&&(d[c]=Of(a[c]));o.rawOutput=d}return{...n,params:{...t,update:o}}}function jF(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function xx(n){if(jF(n)){let r=n,s={type:"diff",oldText:"",newText:""};return typeof r.path=="string"&&(s.path=r.path),s}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Of(e.text)),typeof e.content=="string"?t.content=Of(e.content):e.content&&typeof e.content=="object"&&(t.content=xx(e.content)),t}function Of(n){if(typeof n=="string"&&n.length>Ay){let e=n.length-Ay;return`${n.slice(0,Ay)}\u2026[+${e} chars omitted from summary export]`}return n}var qF=2048;function Cx(n){let e=new Set,t=r=>{if(Ax(r)){e.add(r.__hydraBlob);return}if(Array.isArray(r)){for(let s of r)t(s);return}if(r&&typeof r=="object")for(let s of Object.values(r))t(s)};for(let r of n)t(r.params);return e}function Ax(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function zF(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t.sessionUpdate;return r==="tool_call"||r==="tool_call_update"}async function Ey(n,e){if(!zF(n))return n;let t=n.params,r=t.update,s=await Ry(r,e);return{...n,params:{...t,update:s}}}async function Ry(n,e){if(typeof n=="string"){if(n.length<=qF)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let r of n)t.push(await Ry(r,e));return t}if(n&&typeof n=="object"){let t={};for(let[r,s]of Object.entries(n))t[r]=await Ry(s,e);return t}return n}async function Py(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let r=await Ty(t,e);return r===t?n:{...n,params:r}}async function Ty(n,e){if(Ax(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,r=[];for(let s of n){let o=await Ty(s,e);o!==s&&(t=!0),r.push(o)}return t?r:n}if(n&&typeof n=="object"){let t=!1,r={};for(let[s,o]of Object.entries(n)){let i=await Ty(o,e);i!==o&&(t=!0),r[s]=i}return t?r:n}return n}var QF=Rx(VF),XF=Rx(JF),ZF=/^history\.jsonl\.(\d+)(\.gz)?$/,qr=/^[A-Za-z0-9_-]+$/,e1=1e3,t1=1e7,n1=10,Ff=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??e1,this.archiveMaxBytes=e.archiveMaxBytes??t1,this.archiveTiers=e.archiveTiers??n1}async append(e,t){if(qr.test(e))return this.enqueue(e,async()=>{await ut.mkdir(D.sessionDir(e),{recursive:!0});let r=await Ey(t,o=>kg(e,o)),s=JSON.stringify(r)+`
|
|
325
|
+
${dy}`;return lx(n,r,VI)}function FF(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let r=t.content;return r&&typeof r.text=="string"?r.text:""}function LF(n){let e=new Set;cx(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&cx(e,t.availableModels),e}function cx(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let r=t.modelId??t.value??t.id;typeof r=="string"&&r.length>0&&n.add(r)}}}ws();Cy();ve();var BF=NF("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",12),DF=2,$f=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??DF}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let r=t?.targetAgentId;if(this.inflight.has(e))return;let s=this.queued[e];if(s&&s.kind==="title"){this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}};return}this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let r=t-Date.now();if(r<=0)return;let s=[...this.inflight.values()];if(s.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(s),new Promise(o=>{setTimeout(o,r).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let r=this.queued[t];delete this.queued[t];let s=this.runOne(t,r).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,s)}}async runOne(e,t){let r=t.kind,s=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let d=r==="compaction"?s??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let l=await gr(c,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&s===void 0,u=r==="compaction"?this.opts.compactionModel??(f?o.currentModel:void 0):this.opts.synopsisModel,p=D.sessionDir(e);if(await vx.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${i.length} model=${JSON.stringify(u??"(default)")} cwd=${p}`),r==="compaction"){let m=this.opts.compactionMaxIterations??3,h=0,y=a??0,w,k=0,b,S=Date.now(),C=BF(),I={targetAgentId:s},T=E=>this.opts.onCompactionStateChange?.(e,{runId:C,...E},I)??Promise.resolve(),O=E=>{this.opts.broadcastHydraCompaction?.(e,E,I)};await T({status:"requested",requestedAt:S}),O({sessionUpdate:"_hydra_compaction",phase:"started",requestedAt:S});try{do{h++,this.opts.logger?.info(`synopsis: compaction iteration ${h} sessionId=${e} historyLen=${i.length} watermark=${y}`);let E=await this.opts.histories.load(e,{maxEntries:1/0});if(E.length===y)break;let $=await ux({agentId:d,cwd:p,plan:l,history:E,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(q,z)=>{T({status:"running",requestedAt:S,iter:h,worker:{upstreamSessionId:q,pid:z??0}})},onFailure:q=>{b=q}});if($){let q=wx($.synopsis,E);q&&bx(q)&&(await this.opts.persistSynopsis(e,q,E.length),w=q,k=E.length,b=void 0,await T({status:"running",requestedAt:S,iter:h}),O({sessionUpdate:"_hydra_compaction",phase:"iteration",iter:h,historyLen:E.length}),await this.opts.onSynthesisArtifact?.(e,q,k,s,C),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${h} fields=${kx(q)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${h} returned no result`);if(y=E.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(h<m);if(w)this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} runId=${C} watermark=${k} iterations=${h}`+(h>=m?` (hit maxIterations=${m})`:"")),O({sessionUpdate:"_hydra_compaction",phase:"converged",iter:h,summarizedThroughEntry:k});else{h>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${b??"no reason captured"}`);let E=b??(h===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${h} iteration(s)`);await T({status:"failed",requestedAt:S,iter:h,lastError:E}),O({sessionUpdate:"_hydra_compaction",phase:"failed",error:E}),s&&await this.opts.onSynthesisUnavailable?.(e,s,E)}}catch(E){let $=E instanceof Error?E.message:String(E);if(this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${$}`),await T({status:"failed",requestedAt:S,iter:h,lastError:$}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"_hydra_compaction",phase:"failed",error:$},{targetAgentId:s}),s)try{await this.opts.onSynthesisUnavailable?.(e,s,$)}catch{}}}else{let m=await _f({agentId:d,cwd:p,plan:l,history:i,modelId:u,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let h=wx(m.synopsis,i);h&&bx(h)?(await this.opts.persistSynopsis(e,h,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${kx(h)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function wx(n,e){let t=mx(e),r=hx(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:r.length>0?r:n.tools_used}:t.length===0&&r.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:r.length>0?r:void 0}}function bx(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function kx(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}ve();import*as ut from"fs/promises";import{createReadStream as KF}from"fs";import{createGunzip as GF,gzip as VF,gunzip as JF}from"zlib";import{createInterface as YF}from"readline";import{promisify as Rx}from"util";function Sx(n){return n==="summary"?"summary":"inline"}var Ay=256,HF=["totalMatches","totalFiles","referenceCount","truncated","exitCode"],UF=["content","stdout","stderr"];function Ix(n,e){return e!=="summary"?n:n.map(WF)}function WF(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,r=t.update;if(!r||typeof r!="object"||Array.isArray(r))return n;let s=r;if(s.sessionUpdate!=="tool_call"&&s.sessionUpdate!=="tool_call_update")return n;let o={...s};Array.isArray(s.content)&&(o.content=s.content.map(xx));let i=s.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=Of(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata);for(let c of HF)a[c]!==void 0&&(d[c]=a[c]);for(let c of UF)typeof a[c]=="string"&&(d[c]=Of(a[c]));o.rawOutput=d}return{...n,params:{...t,update:o}}}function jF(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function xx(n){if(jF(n)){let r=n,s={type:"diff",oldText:"",newText:""};return typeof r.path=="string"&&(s.path=r.path),s}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Of(e.text)),typeof e.content=="string"?t.content=Of(e.content):e.content&&typeof e.content=="object"&&(t.content=xx(e.content)),t}function Of(n){if(typeof n=="string"&&n.length>Ay){let e=n.length-Ay;return`${n.slice(0,Ay)}\u2026[+${e} chars omitted from summary export]`}return n}var qF=2048;function Cx(n){let e=new Set,t=r=>{if(Ax(r)){e.add(r.__hydraBlob);return}if(Array.isArray(r)){for(let s of r)t(s);return}if(r&&typeof r=="object")for(let s of Object.values(r))t(s)};for(let r of n)t(r.params);return e}function Ax(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function zF(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t.sessionUpdate;return r==="tool_call"||r==="tool_call_update"}async function Ey(n,e){if(!zF(n))return n;let t=n.params,r=t.update,s=await Ry(r,e);return{...n,params:{...t,update:s}}}async function Ry(n,e){if(typeof n=="string"){if(n.length<=qF)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let r of n)t.push(await Ry(r,e));return t}if(n&&typeof n=="object"){let t={};for(let[r,s]of Object.entries(n))t[r]=await Ry(s,e);return t}return n}async function Py(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let r=await Ty(t,e);return r===t?n:{...n,params:r}}async function Ty(n,e){if(Ax(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,r=[];for(let s of n){let o=await Ty(s,e);o!==s&&(t=!0),r.push(o)}return t?r:n}if(n&&typeof n=="object"){let t=!1,r={};for(let[s,o]of Object.entries(n)){let i=await Ty(o,e);i!==o&&(t=!0),r[s]=i}return t?r:n}return n}var QF=Rx(VF),XF=Rx(JF),ZF=/^history\.jsonl\.(\d+)(\.gz)?$/,qr=/^[A-Za-z0-9_-]+$/,eL=1e3,tL=1e7,nL=10,Ff=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??eL,this.archiveMaxBytes=e.archiveMaxBytes??tL,this.archiveTiers=e.archiveTiers??nL}async append(e,t){if(qr.test(e))return this.enqueue(e,async()=>{await ut.mkdir(D.sessionDir(e),{recursive:!0});let r=await Ey(t,o=>kg(e,o)),s=JSON.stringify(r)+`
|
|
326
326
|
`;await ut.appendFile(D.historyFile(e),s,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(qr.test(e))return this.enqueue(e,async()=>{await ut.mkdir(D.sessionDir(e),{recursive:!0});let r=[];for(let o of t)r.push(await Ey(o,i=>kg(e,i)));let s=r.length===0?"":r.map(o=>JSON.stringify(o)).join(`
|
|
327
327
|
`)+`
|
|
328
328
|
`;await ut.writeFile(D.historyFile(e),s,{encoding:"utf8",mode:384})})}async compact(e,t){if(qr.test(e))return this.enqueue(e,async()=>{let r;try{r=await ut.readFile(D.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let s=r.split(`
|
|
@@ -332,7 +332,7 @@ ${dy}`;return lx(n,r,VI)}function FF(n){if(!n||typeof n!="object")return"";let e
|
|
|
332
332
|
`)+`
|
|
333
333
|
`,s=await this.resolveNextArchiveIndex(e);await this.enforceArchiveTierCap(e,s);let o=D.historyArchiveFile(e,s);await ut.mkdir(D.sessionDir(e),{recursive:!0}),await ut.appendFile(o,r,{encoding:"utf8",mode:384});let i=0;try{i=(await ut.stat(o)).size}catch{i=0}i>=this.archiveMaxBytes?(await this.sealArchive(e,s),this.nextArchiveIndex.set(e,s+1)):this.nextArchiveIndex.set(e,s),this.archiveLineCounts.delete(e)}async sealArchive(e,t){let r=D.historyArchiveFile(e,t),s;try{s=await ut.readFile(r)}catch(i){if(i.code==="ENOENT")return;throw i}let o=await QF(s);await ut.writeFile(r+".gz",o,{mode:384});try{await ut.unlink(r)}catch(i){if(i.code!=="ENOENT")throw i}}async resolveNextArchiveIndex(e){let t=this.nextArchiveIndex.get(e);if(t!==void 0)return t;let r=await this.listArchiveIndices(e),s=r.length===0?0:r[r.length-1],o=s===0?1:s;if(s>0){let i=D.historyArchiveFile(e,s),a=i+".gz",d=!1;try{await ut.access(a),d=!0}catch{d=!1}if(d)o=s+1;else try{(await ut.stat(i)).size>=this.archiveMaxBytes&&(o=s+1)}catch{o=s}}return this.nextArchiveIndex.set(e,o),o}async enforceArchiveTierCap(e,t){if(this.archiveTiers<=0)return;let r=await this.listArchiveIndices(e),o=(r.includes(t)?r.length:r.length+1)-this.archiveTiers,i=0;for(;o>0&&i<r.length;){let a=r[i];a!==t&&(await this.unlinkArchive(e,a),o-=1),i+=1}}async unlinkArchive(e,t){let r=D.historyArchiveFile(e,t);for(let s of[r,r+".gz"])try{await ut.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}this.archiveLineCounts.delete(e)}async listArchiveIndices(e){let t;try{t=await ut.readdir(D.sessionDir(e))}catch(s){if(s.code==="ENOENT")return[];throw s}let r=new Set;for(let s of t){let o=ZF.exec(s);if(!o)continue;let i=Number.parseInt(o[1],10);Number.isFinite(i)&&i>0&&r.add(i)}return[...r].sort((s,o)=>s-o)}async listArchives(e){if(!qr.test(e))return[];let t=await this.listArchiveIndices(e),r=[];for(let s of t){let o=D.historyArchiveFile(e,s),i=o+".gz",a=o;try{await ut.access(i),a=i}catch{a=o}r.push({index:s,path:a})}return r}async loadArchives(e){if(!qr.test(e))return[];let t=this.writeQueues.get(e);t&&await t;let r=await this.listArchives(e),s=[];for(let{path:o}of r){let i;try{if(o.endsWith(".gz")){let a=await ut.readFile(o);i=(await XF(a)).toString("utf8")}else i=await ut.readFile(o,"utf8")}catch(a){if(a.code==="ENOENT")continue;throw a}for(let a of i.split(`
|
|
334
334
|
`)){if(a.length===0)continue;let d;try{d=JSON.parse(a)}catch{continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let c=d;typeof c.method=="string"&&typeof c.recordedAt=="number"&&s.push({method:c.method,params:c.params,recordedAt:c.recordedAt})}}return s}async*streamFile(e){let t;try{t=KF(e)}catch(i){if(i.code==="ENOENT")return;throw i}if(await new Promise(i=>{let a=!1,d=c=>{a||(a=!0,i(c))};t.once("error",c=>{c.code==="ENOENT"?d(!0):(t.destroy(),d(!1))}),t.once("readable",()=>d(!1)),t.once("end",()=>d(!1))}))return;let s=e.endsWith(".gz")?t.pipe(GF()):t,o=YF({input:s,crlfDelay:1/0});try{for await(let i of o){if(i.length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}if(!a||typeof a!="object"||Array.isArray(a))continue;let d=a;typeof d.method=="string"&&typeof d.recordedAt=="number"&&(yield{method:d.method,params:d.params,recordedAt:d.recordedAt})}}finally{o.close(),t.destroy()}}async getArchiveLineCounts(e){if(!qr.test(e))return[];let t=this.archiveLineCounts.get(e),r=await this.listArchives(e);if(t&&t.length===r.length&&t.every((o,i)=>o.index===r[i].index&&o.path===r[i].path))return t;let s=[];for(let{index:o,path:i}of r){let a=t?.find(c=>c.index===o&&c.path===i);if(a){s.push(a);continue}let d=0;for await(let c of this.streamFile(i))d+=1;s.push({index:o,path:i,lineCount:d})}return this.archiveLineCounts.set(e,s),s}async hydrateEntry(e,t,r){return Py(t,async s=>{let o=r.get(s);if(o!==void 0)return o;let i=await Nc(e,s);return r.set(s,i),i})}async*iterRecallNewestFirst(e){if(!qr.test(e))return;let t=this.writeQueues.get(e);t&&await t;let r=await this.getArchiveLineCounts(e),s=0;for(let c of r)s+=c.lineCount;let o=new Map,i=[];for await(let c of this.streamFile(D.historyFile(e)))i.push(c);for(let c=i.length-1;c>=0;c--){let l=await this.hydrateEntry(e,i[c],o);yield{entryId:s+c,entry:l}}let a=new Array(r.length),d=0;for(let c=0;c<r.length;c++)a[c]=d,d+=r[c].lineCount;for(let c=r.length-1;c>=0;c--){let l=r[c],f=[];for await(let p of this.streamFile(l.path))f.push(p);let u=a[c];for(let p=f.length-1;p>=0;p--){let m=await this.hydrateEntry(e,f[p],o);yield{entryId:u+p,entry:m}}}}async rangeSlice(e,t,r){if(!qr.test(e))return[];if(r<t)return[];let s=this.writeQueues.get(e);s&&await s;let o=await this.getArchiveLineCounts(e),i=0;for(let l of o)i+=l.lineCount;let a=[],d=new Map,c=0;for(let l of o){let f=c,u=c+l.lineCount;if(c=u,u<=t)continue;if(f>r)break;let p=0;for await(let m of this.streamFile(l.path)){let h=f+p;if(p+=1,h<t)continue;if(h>r)break;let y=await this.hydrateEntry(e,m,d);a.push({entryId:h,entry:y})}}if(r>=i){let l=Math.max(t-i,0),f=r-i,u=0;for await(let p of this.streamFile(D.historyFile(e))){if(u>f)break;if(u>=l){let m=await this.hydrateEntry(e,p,d);a.push({entryId:i+u,entry:m})}u+=1}}return a}async getRecallTotalCount(e){if(!qr.test(e))return 0;let t=await this.getArchiveLineCounts(e),r=0;for(let o of t)r+=o.lineCount;let s=0;for await(let o of this.streamFile(D.historyFile(e)))s+=1;return r+s}async load(e,t={}){if(!qr.test(e))return[];let r=(t.tools??"inline")==="inline",s=this.writeQueues.get(e);s&&await s;let o;try{o=await ut.readFile(D.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let i=[];for(let u of o.split(`
|
|
335
|
-
`)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=t.maxEntries??this.maxEntries,d=i.length>a?i.slice(-a):i;if(!r)return d;let c=new Map,l=async u=>{let p=c.get(u);if(p!==void 0)return p;let m=await Nc(e,u);return c.set(u,m),m},f=[];for(let u of d)f.push(await Py(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(qr.test(e))return this.enqueue(e,async()=>{try{await ut.unlink(D.historyFile(e))}catch(r){if(r.code!=="ENOENT")throw r}let t=await this.listArchiveIndices(e);for(let r of t)await this.unlinkArchive(e,r);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await vS(e);try{await ut.rmdir(D.sessionDir(e))}catch(r){let s=r;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw r}})}enqueue(e,t){let s=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=s.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),s}};ve();ot();Nf();Oi();lf();Uc();rn();wd();rn();er();ey();var Mx=900*1e3,d1=12,c1="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bd=a1(c1,16),Df=class n{constructor(e,t,r,s={}){this.registry=e;this.spawner=t??(a=>Ro.spawn(a)),this.store=r??new yf,this.tombstones=s.tombstones??new Pf,this.sessionHistoryMaxEntries=s.sessionHistoryMaxEntries??1e3,this.histories=new Ff({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:s.sessionHistoryArchiveMaxBytes,archiveTiers:s.sessionHistoryArchiveTiers}),this.workspaceSnapshotsDisabled=s.disableWorkspaceSnapshots===!0,this.idleTimeoutMs=s.idleTimeoutMs??0,this.orphanTimeoutMs=s.orphanTimeoutMs??0,this.idleEventTimeoutMs=s.idleEventTimeoutMs??3e4,this.defaultModels=s.defaultModels??{},this.synopsisAgent=s.synopsisAgent,this.synopsisModel=s.synopsisModel,this.compactionAgent=s.compactionAgent,this.compactionModel=s.compactionModel,this.defaultTransformers=s.defaultTransformers??[],this.logger=s.logger,this.npmRegistry=s.npmRegistry,this.extensionCommands=s.extensionCommands,this.defaultCwd=s.defaultCwd??"~";let o=s.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new $f({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,d)=>{let c=this.get(a);if(c){await c.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,c)=>this.persistSynopsis(a,d,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,c)=>{if(c.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,c)=>{this.emitSwapPhase(a,c.targetAgentId,d)},onSynthesisArtifact:async(a,d,c,l,f)=>{await this.dispatchSynthesisSwap(a,d,c,l,f)},onSynthesisUnavailable:async(a,d,c)=>{let l=await this.store.read(a).catch(()=>{});if(l?.synopsis&&l.summarizedThroughEntry!==void 0){this.logger?.info(`agent switch: synthesis produced no new artifact for sessionId=${a} (${c}); swapping to ${d} on the persisted synopsis`),await this.dispatchSynthesisSwap(a,l.synopsis,l.summarizedThroughEntry,d);return}let f=(await this.histories.load(a).catch(()=>[])).length;this.logger?.warn(`agent switch: synthesis unavailable for sessionId=${a} (${c}); swapping to ${d} on verbatim tail`),await this.dispatchSynthesisSwap(a,void 0,f,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;snapshotInFlight=new Set;snapshotPending=new Set;workspaceSnapshotsDisabled=!1;driftNoticed=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;orphanTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;workspaceQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,r,s,o){let i=this.get(e);if(t===void 0&&s===void 0)return;if(!i){if(this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),t===void 0)return;await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r});return}let a=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,a,r,s,o);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,s,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(d){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${d instanceof Error?d.message:String(d)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let r=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let d=await this.store.read(e).catch(()=>{});d?.synopsis&&d.summarizedThroughEntry!==void 0?this.dispatchSynthesisSwap(e,d.synopsis,d.summarizedThroughEntry,d.pendingAgentSwap):d?.pendingAgentSwap&&this.dispatchSynthesisSwap(e,void 0,(await this.histories.load(e).catch(()=>[])).length,d.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){if(o?.pendingAgentSwap){let d=(await this.histories.load(e).catch(()=>[])).length;this.logger?.info(`compaction: no artifact for sessionId=${e}, swapping to ${o.pendingAgentSwap} on verbatim tail`),await this.performSynthesisSwap(t,void 0,r,d,o.pendingAgentSwap);return}this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,r,o.summarizedThroughEntry,i,o.compactionState?.runId)}catch(s){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${s instanceof Error?s.message:String(s)}`)}}async recordSynopsisFor(e){let t=await this.store.read(e).catch(()=>{});return t?.synopsis?{synopsis:t.synopsis}:{}}async performSynthesisSwap(e,t,r,s,o,i){try{let a=o?Math.min(t===void 0?d1:5,r):0;await e.swapUpstream({...t!==void 0?{artifact:t}:{},tailK:r,tailFloor:a,summarizedThroughEntry:s,...o?{newAgentId:o}:{},...i!==void 0?{runId:i}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(a){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await od(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async resolveWorkspace(e){let t=e.workspace;if(t===void 0)return{cwd:e.cwd};let r=Ne(t.provider);if(r===void 0){let l=`unknown workspace provider "${t.provider}"`;if(t.required===!0)throw new Error(`isolation required but unavailable: ${l}`);return this.logger?.warn?.(`session workspace: ${l}; running in ${e.cwd}`),{cwd:e.cwd,isolationError:l}}let s=t.label??`s-${bd().slice(0,8)}`,o=await r.createWorkspace({sourceCwd:e.cwd,label:s,...t.from!==void 0?{from:t.from}:{}}).catch(l=>({ok:!1,reason:String(l)}));if(!o.ok){if(t.required===!0)throw new Error(`isolation required but unavailable: ${o.reason}`);return this.logger?.warn?.(`session workspace: ${o.reason}; falling back to ${e.cwd} (unisolated)`),{cwd:e.cwd,isolationError:o.reason}}let i=o.workspace;r.capabilities().locking&&await r.lock(i,`session ${e.title??"live"}`).catch(()=>{});let a=await Tf(i.sourceCwd).catch(()=>({})),d,c=await this.materializeNestedTrees(i);if(c!==void 0&&this.logger?.info?.(`session workspace: ${c} in ${i.path}`),a.carry!==void 0&&a.carry.length>0){let l=await Sy(i.sourceCwd,i.path,a.carry).catch(()=>{});l!==void 0&&l.copied.length>0&&this.logger?.info?.(`session workspace: carried ${l.copied.length} file(s) into ${i.path}`)}if(a.postCreate!==void 0){let l=await Ef(a.postCreate,{workspacePath:i.path,sourceCwd:i.sourceCwd,label:i.label,...a.hookTimeoutSeconds!==void 0?{timeoutSeconds:a.hookTimeoutSeconds}:{}});l.ok||(d=`postCreate failed: ${l.reason??"unknown"}`,this.logger?.warn?.(`session workspace: ${d} (${i.path})`))}return i.snapshot!==void 0&&await r.retainSnapshot(i,this.startRefFor(i.label),i.snapshot).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},clean:!0},...d!==void 0?{isolationError:d}:{}}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let r=`${wn}${bd()}`,s=await this.resolveWorkspace(e),o=s.cwd,i=await this.bootstrapAgent({agentId:e.agentId,cwd:o,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,selfSessionId:r});if(e.transformChain&&e.transformChain.length>0){let d={...i.agentCapabilities??{}};for(let c of e.transformChain)if(c.intercepts.has("agent:initialize"))try{let l=await c.connection.request("hydra-acp/transformer/message",{token:`t_${bd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:d});l.action==="stop"&&l.payload&&(d=l.payload)}catch{}i.agentCapabilities=d}let a=new pd({sessionId:r,cwd:o,...s.workspace!==void 0?{workspace:s.workspace}:{},...s.isolationError!==void 0?{workspaceError:s.isolationError}:{},agentId:e.agentId,agent:i.agent,upstreamSessionId:i.upstreamSessionId,agentMeta:i.agentMeta,agentCapabilities:i.agentCapabilities,...i.modelVerb?{modelVerb:i.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??[],selfSessionId:r}),loadExistingAgentSession:(d,c)=>this.bootstrapAgentLoad(d,{...c,mcpServers:c.mcpServers??[],selfSessionId:r}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:i.initialModel,currentMode:i.initialMode,agentModes:i.initialModes,agentModels:i.initialModels,agentConfigOptions:i.initialConfigOptions,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(a.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(a),scheduleCompaction:d=>this.scheduleCompaction(a.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(a.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(a.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(a.sessionId),uncompactHook:()=>this.performUncompact(a.sessionId),forkHook:d=>this.forkSession(a.sessionId,d??{}),workspaceHook:(d,c,l)=>this.runWorkspaceAction(a.sessionId,d,c,l),onCompactionSwapHook:d=>{this.persistRollbackBreadcrumb(a.sessionId,d).catch(()=>{})},persistWatermarkHook:d=>{this.mutateRecord(a.sessionId,{summarizedThroughEntry:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(a.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});if(s.workspace!==void 0){let d=Ne(s.workspace.provider);d!==void 0&&d.capabilities().supports.environmentNotes&&(a.workspaceNotes=await d.environmentNotes({path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:s.workspace.vcs}:{}}).catch(()=>[]))}return await this.attachManagerHooks(a),a}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=G.AlreadyAttached,o}return t}let r=this.resurrectionInflight.get(e.hydraSessionId);if(r)return r;let s=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,s);try{return await s}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let r=await this.registry.getAgent(e.agentId);if(!r){let b=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw b.code=G.AgentNotInstalled,b}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let s=await gr(r,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=Yu(e.hydraSessionId,e.forwardedEnv),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...o?{extraEnv:o}:{}}),a;try{let b=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}});a=b.agentCapabilities,i.authMethods=ol(b.authMethods),i.steeringSupported=sl(b)}catch(b){throw await i.kill().catch(()=>{}),Mo(b,i)}let d;try{let b=Oy(r,{model:e.currentModel});d=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...b&&{_meta:b}})}catch(b){if(b&&typeof b=="object"&&b.code===G.AuthRequired)throw await i.kill().catch(()=>{}),Mo(b,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${b.message}); recovering via import-reseed
|
|
335
|
+
`)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=t.maxEntries??this.maxEntries,d=i.length>a?i.slice(-a):i;if(!r)return d;let c=new Map,l=async u=>{let p=c.get(u);if(p!==void 0)return p;let m=await Nc(e,u);return c.set(u,m),m},f=[];for(let u of d)f.push(await Py(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(qr.test(e))return this.enqueue(e,async()=>{try{await ut.unlink(D.historyFile(e))}catch(r){if(r.code!=="ENOENT")throw r}let t=await this.listArchiveIndices(e);for(let r of t)await this.unlinkArchive(e,r);this.nextArchiveIndex.delete(e),this.archiveLineCounts.delete(e),await vS(e);try{await ut.rmdir(D.sessionDir(e))}catch(r){let s=r;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw r}})}enqueue(e,t){let s=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=s.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),s}};ve();ot();Nf();Oi();lf();Uc();rn();wd();rn();er();ey();var Mx=900*1e3,dL=12,cL="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bd=aL(cL,16),Df=class n{constructor(e,t,r,s={}){this.registry=e;this.spawner=t??(a=>Ro.spawn(a)),this.store=r??new yf,this.tombstones=s.tombstones??new Pf,this.sessionHistoryMaxEntries=s.sessionHistoryMaxEntries??1e3,this.histories=new Ff({maxEntries:this.sessionHistoryMaxEntries,archiveMaxBytes:s.sessionHistoryArchiveMaxBytes,archiveTiers:s.sessionHistoryArchiveTiers}),this.workspaceSnapshotsDisabled=s.disableWorkspaceSnapshots===!0,this.idleTimeoutMs=s.idleTimeoutMs??0,this.orphanTimeoutMs=s.orphanTimeoutMs??0,this.idleEventTimeoutMs=s.idleEventTimeoutMs??3e4,this.defaultModels=s.defaultModels??{},this.synopsisAgent=s.synopsisAgent,this.synopsisModel=s.synopsisModel,this.compactionAgent=s.compactionAgent,this.compactionModel=s.compactionModel,this.defaultTransformers=s.defaultTransformers??[],this.logger=s.logger,this.npmRegistry=s.npmRegistry,this.extensionCommands=s.extensionCommands,this.defaultCwd=s.defaultCwd??"~";let o=s.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new $f({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,d)=>{let c=this.get(a);if(c){await c.retitle(d);return}await this.persistTitle(a,d)},persistSynopsis:(a,d,c)=>this.persistSynopsis(a,d,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,d,c)=>{if(c.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=d),await this.mutateRecord(a,{compactionState:d})},broadcastHydraCompaction:(a,d,c)=>{this.emitSwapPhase(a,c.targetAgentId,d)},onSynthesisArtifact:async(a,d,c,l,f)=>{await this.dispatchSynthesisSwap(a,d,c,l,f)},onSynthesisUnavailable:async(a,d,c)=>{let l=await this.store.read(a).catch(()=>{});if(l?.synopsis&&l.summarizedThroughEntry!==void 0){this.logger?.info(`agent switch: synthesis produced no new artifact for sessionId=${a} (${c}); swapping to ${d} on the persisted synopsis`),await this.dispatchSynthesisSwap(a,l.synopsis,l.summarizedThroughEntry,d);return}let f=(await this.histories.load(a).catch(()=>[])).length;this.logger?.warn(`agent switch: synthesis unavailable for sessionId=${a} (${c}); swapping to ${d} on verbatim tail`),await this.dispatchSynthesisSwap(a,void 0,f,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;snapshotInFlight=new Set;snapshotPending=new Set;workspaceSnapshotsDisabled=!1;driftNoticed=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;orphanTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;workspaceQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,r,s,o){let i=this.get(e);if(t===void 0&&s===void 0)return;if(!i){if(this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),t===void 0)return;await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r});return}let a=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,a,r,s,o);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,s,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(d){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${d instanceof Error?d.message:String(d)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let r=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let d=await this.store.read(e).catch(()=>{});d?.synopsis&&d.summarizedThroughEntry!==void 0?this.dispatchSynthesisSwap(e,d.synopsis,d.summarizedThroughEntry,d.pendingAgentSwap):d?.pendingAgentSwap&&this.dispatchSynthesisSwap(e,void 0,(await this.histories.load(e).catch(()=>[])).length,d.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){if(o?.pendingAgentSwap){let d=(await this.histories.load(e).catch(()=>[])).length;this.logger?.info(`compaction: no artifact for sessionId=${e}, swapping to ${o.pendingAgentSwap} on verbatim tail`),await this.performSynthesisSwap(t,void 0,r,d,o.pendingAgentSwap);return}this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,r,o.summarizedThroughEntry,i,o.compactionState?.runId)}catch(s){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${s instanceof Error?s.message:String(s)}`)}}async recordSynopsisFor(e){let t=await this.store.read(e).catch(()=>{});return t?.synopsis?{synopsis:t.synopsis}:{}}async performSynthesisSwap(e,t,r,s,o,i){try{let a=o?Math.min(t===void 0?dL:5,r):0;await e.swapUpstream({...t!==void 0?{artifact:t}:{},tailK:r,tailFloor:a,summarizedThroughEntry:s,...o?{newAgentId:o}:{},...i!==void 0?{runId:i}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(a){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await od(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async resolveWorkspace(e){let t=e.workspace;if(t===void 0)return{cwd:e.cwd};let r=Ne(t.provider);if(r===void 0){let l=`unknown workspace provider "${t.provider}"`;if(t.required===!0)throw new Error(`isolation required but unavailable: ${l}`);return this.logger?.warn?.(`session workspace: ${l}; running in ${e.cwd}`),{cwd:e.cwd,isolationError:l}}let s=t.label??`s-${bd().slice(0,8)}`,o=await r.createWorkspace({sourceCwd:e.cwd,label:s,...t.from!==void 0?{from:t.from}:{}}).catch(l=>({ok:!1,reason:String(l)}));if(!o.ok){if(t.required===!0)throw new Error(`isolation required but unavailable: ${o.reason}`);return this.logger?.warn?.(`session workspace: ${o.reason}; falling back to ${e.cwd} (unisolated)`),{cwd:e.cwd,isolationError:o.reason}}let i=o.workspace;r.capabilities().locking&&await r.lock(i,`session ${e.title??"live"}`).catch(()=>{});let a=await Tf(i.sourceCwd).catch(()=>({})),d,c=await this.materializeNestedTrees(i);if(c!==void 0&&this.logger?.info?.(`session workspace: ${c} in ${i.path}`),a.carry!==void 0&&a.carry.length>0){let l=await Sy(i.sourceCwd,i.path,a.carry).catch(()=>{});l!==void 0&&l.copied.length>0&&this.logger?.info?.(`session workspace: carried ${l.copied.length} file(s) into ${i.path}`)}if(a.postCreate!==void 0){let l=await Ef(a.postCreate,{workspacePath:i.path,sourceCwd:i.sourceCwd,label:i.label,...a.hookTimeoutSeconds!==void 0?{timeoutSeconds:a.hookTimeoutSeconds}:{}});l.ok||(d=`postCreate failed: ${l.reason??"unknown"}`,this.logger?.warn?.(`session workspace: ${d} (${i.path})`))}return i.snapshot!==void 0&&await r.retainSnapshot(i,this.startRefFor(i.label),i.snapshot).catch(()=>{}),{cwd:i.path,workspace:{path:i.path,sourceCwd:i.sourceCwd,label:i.label,provider:i.provider,...i.snapshot!==void 0?{snapshot:i.snapshot}:{},...i.line!==void 0?{line:i.line}:{},...i.vcs!==void 0?{vcs:{...i.vcs}}:{},clean:!0},...d!==void 0?{isolationError:d}:{}}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let r=`${wn}${bd()}`,s=await this.resolveWorkspace(e),o=s.cwd,i=await this.bootstrapAgent({agentId:e.agentId,cwd:o,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,selfSessionId:r});if(e.transformChain&&e.transformChain.length>0){let d={...i.agentCapabilities??{}};for(let c of e.transformChain)if(c.intercepts.has("agent:initialize"))try{let l=await c.connection.request("hydra-acp/transformer/message",{token:`t_${bd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:d});l.action==="stop"&&l.payload&&(d=l.payload)}catch{}i.agentCapabilities=d}let a=new pd({sessionId:r,cwd:o,...s.workspace!==void 0?{workspace:s.workspace}:{},...s.isolationError!==void 0?{workspaceError:s.isolationError}:{},agentId:e.agentId,agent:i.agent,upstreamSessionId:i.upstreamSessionId,agentMeta:i.agentMeta,agentCapabilities:i.agentCapabilities,...i.modelVerb?{modelVerb:i.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??[],selfSessionId:r}),loadExistingAgentSession:(d,c)=>this.bootstrapAgentLoad(d,{...c,mcpServers:c.mcpServers??[],selfSessionId:r}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:i.initialModel,currentMode:i.initialMode,agentModes:i.initialModes,agentModels:i.initialModels,agentConfigOptions:i.initialConfigOptions,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(a.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(a),scheduleCompaction:d=>this.scheduleCompaction(a.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(a.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(a.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(a.sessionId),uncompactHook:()=>this.performUncompact(a.sessionId),forkHook:d=>this.forkSession(a.sessionId,d??{}),workspaceHook:(d,c,l)=>this.runWorkspaceAction(a.sessionId,d,c,l),onCompactionSwapHook:d=>{this.persistRollbackBreadcrumb(a.sessionId,d).catch(()=>{})},persistWatermarkHook:d=>{this.mutateRecord(a.sessionId,{summarizedThroughEntry:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(a.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});if(s.workspace!==void 0){let d=Ne(s.workspace.provider);d!==void 0&&d.capabilities().supports.environmentNotes&&(a.workspaceNotes=await d.environmentNotes({path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:s.workspace.vcs}:{}}).catch(()=>[]))}return await this.attachManagerHooks(a),a}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=G.AlreadyAttached,o}return t}let r=this.resurrectionInflight.get(e.hydraSessionId);if(r)return r;let s=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,s);try{return await s}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let r=await this.registry.getAgent(e.agentId);if(!r){let b=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw b.code=G.AgentNotInstalled,b}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let s=await gr(r,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=Yu(e.hydraSessionId,e.forwardedEnv),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...o?{extraEnv:o}:{}}),a;try{let b=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}});a=b.agentCapabilities,i.authMethods=ol(b.authMethods),i.steeringSupported=sl(b)}catch(b){throw await i.kill().catch(()=>{}),Mo(b,i)}let d;try{let b=Oy(r,{model:e.currentModel});d=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...b&&{_meta:b}})}catch(b){if(b&&typeof b=="object"&&b.code===G.AuthRequired)throw await i.kill().catch(()=>{}),Mo(b,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${b.message}); recovering via import-reseed
|
|
336
336
|
`),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let b=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${b} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Dy(d??{}),l=e.agentModes??kd(By(d??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(l?.map(b=>b.id))}`);let f=await Ti({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:l,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=Fy(d??{}),p=kd(Ny(d??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(p?.map(b=>b.modelId))}`),e.pendingHistorySync!==!0){let b=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${b} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=dd(d),h=await Ei({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,...m?{modelVerb:m}:{},logger:this.logger}),y=h.modelId,w=kd(Bf(Ly(h.result)?h.result:d??{}));if(e.pendingHistorySync!==!0){let b=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${b} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let k=new pd({sessionId:e.hydraSessionId,cwd:e.cwd,...e.workspace!==void 0?{workspace:e.workspace}:{},agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:d?._meta,agentCapabilities:a,...m?{modelVerb:m}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,logger:this.logger,spawnReplacementAgent:b=>this.bootstrapAgent({...b,mcpServers:b.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(b,S)=>this.bootstrapAgentLoad(b,{...S,mcpServers:S.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:y,currentMode:f,currentUsage:e.currentUsage,reloadsUpstreamLedger:!0,agentCommands:e.agentCommands,agentModes:l,agentModels:p,agentConfigOptions:w,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(k.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(k),scheduleCompaction:b=>this.scheduleCompaction(k.sessionId,b),resolveAgentId:async b=>(await this.registry.getAgent(b))?.id,getCompactionState:()=>this.getCompactionState(k.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(k.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(k.sessionId),uncompactHook:()=>this.performUncompact(k.sessionId),forkHook:b=>this.forkSession(k.sessionId,b??{}),workspaceHook:(b,S,C)=>this.runWorkspaceAction(k.sessionId,b,S,C),onCompactionSwapHook:b=>{this.persistRollbackBreadcrumb(k.sessionId,b).catch(()=>{})},persistWatermarkHook:b=>{this.mutateRecord(k.sessionId,{summarizedThroughEntry:b}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(k.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(k),k}async doResurrectFromImport(e){let t=await this.resolveResurrectTarget(e.cwd,e.workspace),r=t.cwd,s=await this.bootstrapAgent({agentId:e.agentId,cwd:r,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),o=e.agentModes??s.initialModes,i=await Ti({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:o,logger:this.logger}),a=e.agentModels??s.initialModels,d=await Ei({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,...s.modelVerb?{modelVerb:s.modelVerb}:{},logger:this.logger}),c=d.modelId,l=Ly(d.result)?kd(Bf(d.result)):void 0;s.agent.connection.drainBuffered("session/update");let f=new pd({sessionId:e.hydraSessionId,cwd:r,...t.workspace!==void 0?{workspace:t.workspace}:{},agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,...s.modelVerb?{modelVerb:s.modelVerb}:{},title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,orphanTimeoutMs:this.orphanTimeoutMs,logger:this.logger,spawnReplacementAgent:u=>this.bootstrapAgent({...u,mcpServers:u.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),loadExistingAgentSession:(u,p)=>this.bootstrapAgentLoad(u,{...p,mcpServers:p.mcpServers??e.mcpServers??[],selfSessionId:e.hydraSessionId}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:c,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:o,agentModels:a,agentConfigOptions:l??s.initialConfigOptions,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(f.sessionId),scheduleWorkspaceSnapshot:()=>this.scheduleWorkspaceSnapshot(f),scheduleCompaction:u=>this.scheduleCompaction(f.sessionId,u),resolveAgentId:async u=>(await this.registry.getAgent(u))?.id,getCompactionState:()=>this.getCompactionState(f.sessionId),getUpstreamGenerations:()=>this.getUpstreamGenerations(f.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(f.sessionId),uncompactHook:()=>this.performUncompact(f.sessionId),forkHook:u=>this.forkSession(f.sessionId,u??{}),workspaceHook:(u,p,m)=>this.runWorkspaceAction(f.sessionId,u,p,m),onCompactionSwapHook:u=>{this.persistRollbackBreadcrumb(f.sessionId,u).catch(()=>{})},persistWatermarkHook:u=>{this.mutateRecord(f.sessionId,{summarizedThroughEntry:u}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(f.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(f),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${f.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?f.seedFromFork(e.synopsis).catch(()=>{}):f.seedFromImport().catch(()=>{}),f}async dirExists(e){try{return(await Li.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);if(!(!t||t.attachedCount>0)&&t.interactive!==!0){if(t.hasWorkInFlight){this.logger?.info(`deferring reap of ${e}: work still in flight after detach`),t.onceIdle(r=>{this.reapIfOrphanedNonInteractive(r.sessionId).catch(()=>{})});return}this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1,by:"reap-orphaned"}).catch(()=>{})}}async resolveResurrectTarget(e,t){if(await this.dirExists(e))return t!==void 0?{cwd:e,workspace:t}:{cwd:e};if(t!==void 0){let r=await this.recoverWorkspace(t);if(r!==void 0)return{cwd:r.path,workspace:r}}return{cwd:mt(this.defaultCwd)}}async releaseWorkspace(e,t){let r=Ne(e.provider);if(r===void 0){this.logger?.warn?.(`session workspace: no provider "${e.provider}" to release ${e.path}; leaving it in place`);return}return this.enqueueKeyed(this.workspaceQueues,e.path,async()=>{let s=this.liveSessionsIn(e.path,t);if(s.length>0){this.logger?.info?.(`session workspace: keeping ${e.path} \u2014 ${s.length} live session(s) still in it`);return}await this.tearDownWorkspace(r,e,t)})}async syncWorkspaceFromSource(e,t,r){let s=this.liveSessionsIn(t.path,e.sessionId);if(s.length>0)throw new Error(`${K(t.path)} is shared with ${s.map(p=>Je(p.sessionId)).join(", ")}, and a sync would move files under them. Sync it from a session that has it to itself.`);let o=await e.quiesceBlocker();if(o!==void 0)throw new Error(o);let i=Ne(t.provider);if(t.line===void 0||i?.capabilities().sharedHistory!==!0)throw new Error(`workspace ${t.label} uses the "${t.provider}" provider, which has no history to merge from \u2014 a sync needs a common base, and a copied directory has none. Land its work with \`/hydra workspace merge\` instead, or start a git-backed workspace if you need to track the source.`);let[a,d]=await Promise.all([i.currentState(t.sourceCwd),i.currentState(t.path)]);if(a===void 0||d===void 0)throw new Error("could not read the state of the source or the workspace");if(await i.contains(t.path,{state:a,within:d}))return{ok:!0,message:`Already up to date with ${K(t.sourceCwd)} (${a.slice(0,8)}).`};let c=await i.divergence(t.path,d,a),l=String(c?.behind??0),f=await i.integrate({into:t.path,from:a,message:`hydra: sync ${t.label} with the source`});if(!f.ok){let p=f.conflicts,m=await i.integrationInProgress(t.path);if(p.length===0&&!m){let y=await this.syncOverDirtyTree(t,{provider:i,before:d,sourceHead:a,incoming:l});if(y!==void 0)return y}let h=p.length>0?`
|
|
337
337
|
${p.map(y=>` ${y}`).join(`
|
|
338
338
|
`)}`:` (${f.reason??"the integration failed"})`;return p.length===0?{ok:!1,message:`the source could not be merged into ${K(t.path)}; nothing changed.${h}
|
|
@@ -360,31 +360,31 @@ A sync was attempted first but was refused: ${O instanceof Error?O.message:Strin
|
|
|
360
360
|
Nothing was committed: review it with \`git -C ${r} diff --cached\` and commit it however you like. The workspace and its history are untouched.`,warnings:k}}async leaveWorkspace(e,t,r){let s=r.exit!=="detached",o=Ne(t.provider),i={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}},a=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:t.sourceCwd,workspace:void 0,historyLength:a.length,note:`Returned to the source tree at ${t.sourceCwd}`+(r.exit==="landed"?" after merging the workspace.":r.exit==="discarded"?" after discarding the workspace and its work.":" without merging."),...await this.recordSynopsisFor(e.sessionId),left:{path:t.path,removed:s}}),await this.mutateRecord(e.sessionId,{cwd:e.cwd},["workspace"]),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"left",cwd:e.cwd,sourceCwd:t.sourceCwd,integrated:r.exit==="landed"}),o!==void 0&&await this.enqueueKeyed(this.workspaceQueues,t.path,async()=>{let d=this.liveSessionsIn(t.path,e.sessionId);if(d.length>0){this.logger?.info?.(`session workspace: ${e.sessionId} left ${t.path}; ${d.length} live session(s) remain, so it stays`);return}await this.reclaimAfterLastLeaver(o,i,t,e.sessionId,r)})}async reclaimAfterLastLeaver(e,t,r,s,o){await e.unlock(t).catch(()=>{});for(let i of[this.startRefFor(r.label),this.baselineRefFor(r.label)])await e.dropSnapshotRef(t,i).catch(()=>{});o.exit!=="detached"&&(o.exit==="landed"&&await e.dropSnapshotRef(t,this.snapshotRefFor(r.label)).catch(()=>{}),await e.removeWorkspace(t,{force:!0,discardLine:!0}).catch(()=>{}))}async joinDivergence(e,t,r){let[s,o]=await Promise.all([e.captureWorkingState(t,"hydra: source state at join").catch(()=>{}),e.captureWorkingState(r.path,"hydra: workspace state at join").catch(()=>{})]);if(s===void 0||o===void 0)return`could not compare ${K(t)} with ${K(r.path)}, so refusing to join a workspace that may not match your tree`;let i=await Promise.all([s,o].map(a=>e.contentId(t,a).catch(()=>{})));if(!(i[0]!==void 0&&i[0]===i[1]))return`${K(t)} and ${K(r.path)} have diverged, and joining does not carry work across \u2014 whichever side you are not in would be left behind. Land or stash one of them first: \`git -C ${t} stash\` if the difference is yours, or \`/hydra workspace merge\` from the session already in there if it is theirs.`}liveSessionsWithLabel(e,t){let r=[];for(let s of this.sessions.values()){let o=s.workspace;o===void 0||o.sourceCwd!==e||(o.label===t||o.requestedLabel===t)&&r.push(s)}return r}async joinWorkspace(e,t,r,s){let o=Ne(r.provider);if(o===void 0)throw new Error(`no provider "${r.provider}" to join that workspace with`);if(o.capabilities().supports.captureWorkingState){let i=await this.joinDivergence(o,s,r);if(i!==void 0)throw new Error(i)}return await this.enqueueKeyed(this.workspaceQueues,r.path,async()=>{if(this.sessions.get(t.sessionId)?.workspace?.path!==r.path)throw new Error(`${K(r.path)} was released while joining it; run the command again`);e.broadcastWorkspacePhase({phase:"swapping"});let i=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:r.path,workspace:{path:r.path,sourceCwd:r.sourceCwd,label:r.label,...r.requestedLabel!==void 0?{requestedLabel:r.requestedLabel}:{},provider:r.provider,...r.snapshot!==void 0?{snapshot:r.snapshot}:{},...r.line!==void 0?{line:r.line}:{},...r.vcs!==void 0?{vcs:{...r.vcs}}:{}},historyLength:i.length,note:`Continuing in an isolated workspace at ${r.path}, derived from ${s}, shared with another session.`,...await this.recordSynopsisFor(e.sessionId)}),await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache();let a=r.line;e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:r.sourceCwd,label:r.label,...a!==void 0?{branch:a}:{}});let d=this.liveSessionsIn(r.path,e.sessionId).map(l=>Je(l.sessionId)),c=[`Joined workspace ${K(r.path)}`,` source: ${K(r.sourceCwd)}`];return a!==void 0&&c.push(` branch: ${a}`),c.push(` shared with: ${d.join(", ")}`),c.push(" your edits will interleave with that session's"),c.push("Use `/hydra workspace stop` to leave; the work lands when the last session leaves."),c.join(`
|
|
361
361
|
`)})}async startWorkspace(e,t,r){if(e.workspace!==void 0)throw new Error(`already isolated in ${K(e.workspace.path)}. Use \`/hydra workspace stop\` to merge and return first, or \`detach\` to leave it behind.`);let s=e.cwd,o=Ne();if(o===void 0)throw new Error("no workspace provider available");let i=await e.quiesceBlocker();if(i!==void 0)throw new Error(i);let a=o.capabilities();if(t!==void 0){let I=this.liveSessionsWithLabel(s,t)[0];if(I!==void 0&&I.workspace!==void 0)return await this.joinWorkspace(e,I,I.workspace,s)}let d,c=[],l=!1,f=!1,u=[],p=[],m=r?.clean===!0;if(a.supports.captureWorkingState){let I=await o.status({path:s,sourceCwd:s,label:"source",provider:o.kind}).catch(()=>{});f=I!==void 0;let T=a.supports.nestedTrees&&I!==void 0&&I.changedPaths.length>0?await o.listNested(s).catch(()=>[]):[];if(I!==void 0&&I.changedPaths.length>0&&m)u=yy(I.changedPaths,T);else if(I!==void 0&&I.changedPaths.length>0&&(c=yy(I.changedPaths,T),p=await o.captureNested(s,T).catch(()=>[]),l=I.hasStagedWork===!0,d=await o.captureWorkingState(s,"hydra: work carried into workspace").catch(()=>{}),d===void 0))throw new Error("could not snapshot your uncommitted work, so refusing to move it. Commit or stash first.")}e.broadcastWorkspacePhase({phase:"provisioning"});let h=await o.createWorkspace({sourceCwd:s,label:t??`s-${e.sessionId.slice(-8)}`});if(!h.ok)throw e.broadcastWorkspacePhase({phase:"failed",error:h.reason}),new Error(h.reason);let y=h.workspace,w=this.startRefFor(y.label),k,b=!1,S=[];try{a.locking&&await o.lock(y,`session ${e.sessionId}`).catch(()=>{});let I=d??y.snapshot;if(I===void 0)throw new Error(`provider "${y.provider}" gave the workspace no base to anchor landing against`);await o.retainSnapshot(y,w,I),e.broadcastWorkspacePhase({phase:"setup"}),b=d!==void 0?await this.copyCarriedWork(y,d,s):!0;let T=await this.materializeNestedTrees(y);if(p.length>0){let E=await o.reproduceNested(y.path,s,p).catch($=>({applied:[],failed:p.map(F=>({path:F.relPath,reason:$ instanceof Error?$.message:String($)}))}));E.failed.length>0&&(b=!1,S=E.failed)}k=await this.applyWorkspaceSetup(y,e.sessionId),T!==void 0&&(k=k===void 0?T:`${T}; ${k}`),e.broadcastWorkspacePhase({phase:"swapping"});let O=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:y.path,workspace:{path:y.path,sourceCwd:y.sourceCwd,label:y.label,...t!==void 0&&t!==y.label?{requestedLabel:t}:{},provider:y.provider,...y.snapshot!==void 0?{snapshot:y.snapshot}:{},...y.line!==void 0?{line:y.line}:{},...y.vcs!==void 0?{vcs:{...y.vcs}}:{},...d===void 0?{clean:!0}:{}},historyLength:O.length,note:`Continuing in an isolated workspace at ${y.path}, derived from ${s}.`,...await this.recordSynopsisFor(e.sessionId)})}catch(I){let T=await this.unwindStartWorkspace({provider:o,ws:y,startRef:w,carried:d}),O=I instanceof Error?I.message:String(I);throw e.broadcastWorkspacePhase({phase:"failed",error:O}),new Error(T===void 0?O:`${O}
|
|
362
362
|
${T}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:y.sourceCwd,label:y.label,...y.line!==void 0?{branch:y.line}:{}});let C=[`Moved into workspace ${K(y.path)}`,` source: ${K(s)}`];if(y.line!==void 0&&C.push(` branch: ${y.line}`),t!==void 0&&t!==y.label&&C.push(` note: "${t}" was already taken by a surviving branch, so this is "${y.label}"`),d!==void 0){C.push(b?` carried ${c.length} uncommitted file(s) in; the source tree is untouched:`:` WARNING: could not copy ${c.length} uncommitted file(s); the workspace starts from HEAD. They are untouched in the source tree:`);for(let I of Mi(c))C.push(` ${I}`);b&&l&&C.push(" staging did not come along; everything above is unstaged here");for(let I of S)C.push(` nested tree ${I.path}: ${I.reason}`)}else if(u.length>0){C.push(` started clean: ${u.length} uncommitted file(s) stayed in the source and did NOT come along:`);for(let I of Mi(u))C.push(` ${I}`)}else f&&C.push(" source tree was clean; nothing carried in");return k!==void 0&&C.push(` ${k}`),C.push("Use `/hydra workspace stop` to merge back and return."),C.join(`
|
|
363
|
-
`)}async copyCarriedWork(e,t,r){let s=await this.patchFromSnapshot(r,t,e.provider);if(s===void 0)return!1;if(s.length===0)return!0;let o=Ne(e.provider);return o===void 0?!1:(await o.applyDelta(e.path,s)).ok}async patchFromSnapshot(e,t,r){let s=Ne(r);if(s===void 0)return;let o=await s.currentState(e);if(o!==void 0)return await s.captureDelta(e,o,t).catch(()=>{})}async unwindStartWorkspace(e){let{provider:t,ws:r,startRef:s,carried:o}=e;await t.unlock(r).catch(()=>{}),o!==void 0&&await t.dropSnapshotRef(r,s).catch(()=>{}),await t.removeWorkspace(r,{force:!0}).catch(()=>{})}async materializeNestedTrees(e,t){let r=Ne(e.provider);if(r?.capabilities().supports.nestedTrees!==!0)return;let s=await r.materializeNested({path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:r.kind},t).catch(o=>({ok:!1,count:0,reason:o instanceof Error?o.message:String(o)}));return s.ok?s.count>0?`populated ${s.count} nested tree(s)`:void 0:`nested trees FAILED: ${s.reason??"unknown"}`}async applyWorkspaceSetup(e,t){let r=await Tf(e.sourceCwd).catch(()=>({})),s=[];if(r.carry!==void 0&&r.carry.length>0){let o=await Sy(e.sourceCwd,e.path,r.carry).catch(()=>{});o!==void 0&&o.copied.length>0&&s.push(`carried ${o.copied.length} config file(s)`)}if(r.postCreate!==void 0){let o=await Ef(r.postCreate,{workspacePath:e.path,sourceCwd:e.sourceCwd,label:e.label,sessionId:t,...r.hookTimeoutSeconds!==void 0?{timeoutSeconds:r.hookTimeoutSeconds}:{}});s.push(o.ok?"ran postCreate":`postCreate FAILED: ${o.reason??"unknown"}`)}return s.length>0?s.join("; "):void 0}async deriveForkWorkspace(e,t){let r=Ne(e.provider);if(r===void 0)return;let s=r.capabilities(),o=s.sharedHistory?await r.currentState(e.path)??"":"",i=await r.createWorkspace({sourceCwd:e.sourceCwd,label:t,...o.length>0?{from:o}:{contentFrom:e.path}}).catch(d=>({ok:!1,reason:String(d)}));if(!i.ok){this.logger?.warn?.(`fork workspace: could not derive from ${e.path}: ${i.reason}`);return}let a=i.workspace;if(o.length>0&&s.supports.captureWorkingState){let d=await r.captureWorkingState(e.path,`hydra: fork carry from ${e.label}`).catch(()=>{});d!==void 0&&d!==o&&await this.copyUncommittedInto(e.path,a.path,o,d,a.provider).catch(()=>{})}return{path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.line!==void 0?{line:a.line}:{},...a.vcs!==void 0?{vcs:{...a.vcs}}:{}}}async copyUncommittedInto(e,t,r,s,o){let i=Ne(o);if(i===void 0)return!1;let a=await i.captureDelta(e,r,s).catch(()=>{});return a===void 0||a.trim().length===0?!1:(await i.applyDelta(t,a,{stage:!0})).ok}async recoverWorkspace(e){let t=Ne(e.provider);if(t===void 0)return;let r={path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}};if(t.capabilities().supports.rematerialize){let o=await t.rematerialize(r).catch(i=>({ok:!1,reason:String(i)}));if(o.ok)return this.logger?.info?.(`session workspace: restored ${o.workspace.path} from retained state`),{...e,path:o.workspace.path};this.logger?.warn?.(`session workspace: could not restore: ${o.reason}`)}if(!await this.dirExists(e.sourceCwd))return;let s=await t.createWorkspace({sourceCwd:e.sourceCwd,label:`${e.label}-r`}).catch(o=>({ok:!1,reason:String(o)}));if(s.ok)return this.logger?.warn?.(`session workspace: ${e.path} is gone and could not be restored; resurrecting in a fresh workspace ${s.workspace.path} from ${e.sourceCwd}. Uncommitted work from the old workspace is not recoverable.`),{path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:{...s.workspace.vcs}}:{}}}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let h=new Error(`agent ${e} not found in registry`);throw h.code=G.AgentNotInstalled,h}let r=await gr(t,[],{npmRegistry:this.npmRegistry}),s=this.spawner({agentId:e,cwd:Lx.homedir(),plan:r}),o;try{o=await s.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}})}catch(h){throw await s.kill().catch(()=>{}),Mo(h,s)}if(s.authMethods=ol(o.authMethods),s.steeringSupported=sl(o),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await s.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(s)}catch(h){throw await s.kill().catch(()=>{}),h}await s.kill().catch(()=>{});let d=new Map,c=Pg(t);d.set(e,c);let l=new Set;for(let h of this.sessions.values()){let y=await this.agentStoreKey(h.agentId,d);l.add(`${y}::${h.upstreamSessionId}`)}let f=await this.store.list().catch(()=>[]);for(let h of f){l.add(`${await this.agentStoreKey(h.agentId,d)}::${h.upstreamSessionId}`);for(let y of h.upstreamGenerations??[])l.add(`${await this.agentStoreKey(y.agentId,d)}::${y.upstreamSessionId}`)}let u=D.sessionsDir(),p=[],m=0;for(let h of a){let y=`${c}::${h.sessionId}`;if(l.has(y)){m+=1;continue}if(l1(h.cwd,u)){m+=1;continue}let w=c,k=await this.tombstones.read(w,h.sessionId).catch(()=>{});if(!k&&c!==e&&(w=e,k=await this.tombstones.read(w,h.sessionId).catch(()=>{})),k){if(!dx(k,h.updatedAt)){m+=1;continue}await this.tombstones.remove(w,h.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${h.sessionId} (upstream updatedAt advanced past ${k.upstreamUpdatedAt??"<unset>"})`)}l.add(y);let b=`${wn}${bd()}`,S=new Date().toISOString(),C=h.updatedAt??S,I={sessionId:b,lineageId:Vc(),upstreamSessionId:h.sessionId,agentId:e,cwd:h.cwd,pendingHistorySync:!0,interactive:!0,createdAt:C,updatedAt:C};h.title!==void 0&&(I.title=h.title);let T=hy(I);await this.store.write(T),p.push({version:1,...T})}return{synced:p,skipped:m}}async collectAgentSessions(e){let t=[],r,s=new Set;for(let o=0;o<100;o+=1){let i={};r!==void 0&&(i.cursor=r);let a=await e.connection.request("session/list",i),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.updatedAt),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||s.has(a.nextCursor))break;s.add(a.nextCursor),r=a.nextCursor}return t}async applySeedModel(e,t,r,s,o){try{let{verb:i,result:a}=await Eo({request:(d,c)=>e.connection.request(d,c),sessionId:t,modelId:r,...o?{verb:o}:{},logger:this.logger});return this.logger?.info(`${s}: ${i} accepted`),{accepted:!0,result:a}}catch(i){return this.logger?.warn(`${s} rejected by agent (${i.message}); session will use the agent's own default`),{accepted:!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=G.AgentNotInstalled,i}let r=await gr(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),s=Yu(e.selfSessionId,e.forwardedEnv),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...s?{extraEnv:s}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}}),a=i.agentCapabilities;o.authMethods=ol(i.authMethods),o.steeringSupported=sl(i);let d=Oy(t),c=await o.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[],...d&&{_meta:d}}),l=c.sessionId;if(typeof l!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let f=Fy(c),u=Ny(c),p=dd(c),m=mr(this.defaultModels,t),h=e.model??m?.value,y;if(h&&h!==f){let S=ud(h,u),C=e.model!==void 0?`model=${JSON.stringify(h)}`:`defaultModels[${m?.from??e.agentId}]=${JSON.stringify(h)}`;if(S.kind==="exact"||S.kind==="none"){let I=await this.applySeedModel(o,l,h,C,p);I.accepted&&(f=h,y=I.result)}else if(S.kind==="resolved")if(S.modelId===f)f=S.modelId;else{let I=await this.applySeedModel(o,l,S.modelId,`${C} resolved to ${JSON.stringify(S.modelId)}`,p);I.accepted&&(f=S.modelId,y=I.result)}else if(S.kind==="ambiguous")this.logger?.warn(`${C} is ambiguous (trailing-segment matches [${S.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(f)}`);else{let I=u.map(T=>T.modelId).join(", ");this.logger?.warn(`${C} not in agent's availableModels ([${I}]); skipping session/set_model, session will use ${JSON.stringify(f)}`)}}let w=By(c),k=Dy(c),b=Bf(Ly(y)?y:c);return{agent:o,upstreamSessionId:l,agentMeta:c._meta,agentCapabilities:a,initialModel:f,initialModels:u.length>0?u:void 0,initialModes:w.length>0?w:void 0,initialMode:k,initialConfigOptions:b.length>0?b:void 0,modelVerb:p}}catch(i){throw await o.kill().catch(()=>{}),Mo(Ox(i,o,e.agentId,{command:r.command,args:r.args,cwd:e.cwd}),o)}}async bootstrapAgentLoad(e,t){let r=await this.registry.getAgent(t.agentId);if(!r){let a=new Error(`agent ${t.agentId} not found in registry`);throw a.code=G.AgentNotInstalled,a}let s=await gr(r,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=Yu(t.selfSessionId,t.forwardedEnv),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:s,...o?{extraEnv:o}:{}});try{let a=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}}),d=a.agentCapabilities;i.authMethods=ol(a.authMethods),i.steeringSupported=sl(a);let c=Oy(r),l=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),f=Fy(l),u=kd(Ny(l)),p=By(l),m=Dy(l),h=kd(Bf(l));return{agent:i,upstreamSessionId:e,agentMeta:l._meta,agentCapabilities:d,initialModel:f,initialModels:u,initialModes:p.length>0?p:void 0,initialMode:m,initialConfigOptions:h,modelVerb:dd(l)}}catch(a){throw await i.kill().catch(()=>{}),Mo(Ox(a,i,t.agentId,{command:s.command,args:s.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let r=await this.store.read(e);if(!r)throw new Error("session record not found");let s=r.rollbackBreadcrumb;if(!s)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=r.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:s.previousUpstreamSessionId,previousSummarizedThroughEntry:s.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:s.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let r=this.pendingAuthAgents.get(e);if(r&&r.isAlive())return r;let s=await this.registry.getAgent(e);if(!s){let d=new Error(`agent ${e} not found in registry`);throw d.code=G.AgentNotInstalled,d}let o=await gr(s,[],{npmRegistry:this.npmRegistry}),i=t??mt(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}});a.authMethods=ol(d.authMethods),a.steeringSupported=sl(d)}catch(d){throw await a.kill().catch(()=>{}),Mo(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 r=new Error(`agent ${e} not found in registry`);throw r.code=G.AgentNotInstalled,r}return gr(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.driftNoticed.delete(e.sessionId),this.invalidateListCache(),t&&e.workspace!==void 0&&this.releaseWorkspace(e.workspace,e.sessionId).catch(()=>{}),t){if(e.upstreamSessionId){let s=vd({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstoneAllGenerations(e.sessionId,{agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,...e.title!==void 0?{title:e.title}:{},...s!==void 0?{interactive:s}:{}},"user").catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let r=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===r&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,r);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:r,...s})=>{this.persistAgentChange(e.sessionId,t,r,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:Nx(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(r=>({name:r.name,...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(r=>({id:r.id,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(r=>({modelId:r.modelId,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),r=u1(e,t);await this.store.write(r)}).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,t={}){return this.histories.load(e,t)}async loadToolBlob(e,t){return Nc(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let r=t.title;return r||(r=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:r,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:f1(t.currentUsage),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,workspace:t.workspace,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(s=>!(s.source==="daemon"&&s.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let r=this.sessions.get(e);r&&(r.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s)return;let o={...s,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let r={...t};delete r.pendingHistorySync,await this.store.write(r)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let r of t){let s=r.params;if(s?.update?.sessionUpdate!=="prompt_received")continue;let o=s.update.sentBy;if(typeof o?.fromSession=="string"||typeof o?.clientId=="string"&&o.clientId.startsWith("transformer:"))continue;let i=Pi(s.update.prompt),a=iy(i,200);if(a&&!a.startsWith("/"))return a}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}setLiveConfig(e){e.defaultModels&&(this.defaultModels=e.defaultModels)}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let r=t.agent.installId,s=t.agent.version,o=e.get(r);o||(o=new Set,e.set(r,o)),o.add(s)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(wn))return;let t=wn+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let r=new Error(`session ${e} not found`);throw r.code=G.SessionNotFound,r}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,workspace:e.workspace,workspaceError:e.workspaceError,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,armedTasks:e.armedBackgroundTasks.length,...e.armedSince!==void 0?{armedSince:e.armedSince}:{},awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await il(t.sessionId),d=vd({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,armedTasks:t.armedBackgroundTasks.length,...t.armedSince!==void 0?{armedSince:t.armedSince}:{},awaitingInput:t.awaitingInput}}let r=await this.store.read(e).catch(()=>{});if(!r)return;let s=await il(r.sessionId),o=vd(r,s.hasContent),i=s.mtime??r.updatedAt;return{sessionId:r.sessionId,upstreamSessionId:r.upstreamSessionId,cwd:r.cwd,title:r.title,agentId:r.agentId,currentModel:r.currentModel,currentUsage:Fi(r.currentUsage),importedFromMachine:r.importedFromMachine,importedFromUpstreamSessionId:r.importedFromUpstreamSessionId,parentSessionId:r.parentSessionId,forkedFromSessionId:r.forkedFromSessionId,forkedFromMessageId:r.forkedFromMessageId,forkSynthesisState:r.forkSynthesisState,originatingClient:r.originatingClient,interactive:o,priority:r.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}|${e.status??""}`,r=Date.now(),s=this.listCache.get(t);if(s&&s.expiresAt>r)return s.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:r+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],r=new Set,s=l=>e.includeNonInteractive?!0:l===!0,o=[...this.sessions.values()].filter(l=>_x(e.cwd,l));if(e.status==="cold")for(let l of o)r.add(l.sessionId);let i=e.status==="cold"?[]:await Promise.all(o.map(l=>il(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=o[l],u=i[l];r.add(f.sessionId);let p=vd({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!s(p))continue;let m=u.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,workspace:f.workspace,workspaceError:f.workspaceError,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"warm",agentPid:f.agentPid,busy:f.turnStartedAt!==void 0,armedTasks:f.armedBackgroundTasks.length,...f.armedSince!==void 0?{armedSince:f.armedSince}:{},awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}if(e.status==="warm")return t;let d=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!r.has(l.sessionId)&&_x(e.cwd,l)),c=await Promise.all(d.map(l=>il(l.sessionId)));for(let l=0;l<d.length;l+=1){let f=d[l],u=c[l],p=vd(f,u.hasContent);if(!s(p))continue;let m=u.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,workspace:f.workspace,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:Fi(f.currentUsage),importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((l,f)=>l.updatedAt<f.updatedAt?1:-1),t}async exportBundle(e,t={}){let r=await this.store.read(e);if(!r)return;let s;if(r.lineageId)s=r;else{let c=Vc(),l={...r,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),s=l}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Fx(e);if(o!=="references")return{record:s,history:i,promptHistory:a};let d={};for(let c of Cx(i)){let l=await bS(e,c);l&&(d[c]=l.toString("base64"))}return{record:s,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let r=await this.store.findByLineageId(e.session.lineageId);if(r){if(!t.replace){let i=new Error(`bundle already imported as ${r.sessionId}`);throw i.code=G.BundleAlreadyImported,i.existingSessionId=r.sessionId,i}let o=this.sessions.get(r.sessionId);return o&&await o.close({deleteRecord:!1,by:"bundle-import-overwrite"}).catch(()=>{}),await this.writeImportedRecord({sessionId:r.sessionId,bundle:e,preservedCreatedAt:r.createdAt,cwd:t.cwd}),{sessionId:r.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let s=`${wn}${bd()}`;return await this.writeImportedRecord({sessionId:s,bundle:e,cwd:t.cwd}),{sessionId:s,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let r=await this.store.read(e);if(!r){let C=new Error(`source session not found: ${e}`);throw C.code=G.SessionNotFound,C}let s=t.agentId??r.agentId,o=s!==r.agentId;if(o&&!await this.registry.getAgent(s)){let I=new Error(`agent ${s} not found in registry`);throw I.code=G.AgentNotInstalled,I}let i=await this.histories.load(e).catch(()=>[]),a=i,d,c=t.mode??"synthesis",l,f,u,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let C=mf(i,t.forkAt);if(C<0){let I=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw I.code=G.InvalidParams,I}d=t.forkAt,a=i.slice(0,C+1)}else{let C=g1(i);C?(d=C.messageId,a=i.slice(0,C.index+1)):(d="",a=i.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let I=mf(i,t.forkAt);if(I<0){let T=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw T.code=G.InvalidParams,T}d=t.forkAt,a=i.slice(0,I+1)}else d="",a=i;let C=await this.registry.getAgent(s);if(!C){let I=new Error(`agent ${s} not found in registry`);throw I.code=G.AgentNotInstalled,I}u=C,f=r.currentModel,l="running"}let m=await Fx(e),h=c==="synthesis",y={...r,lineageId:Vc(),agentId:s,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},w=nl({record:y,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:He,machine:To()}),k=`${wn}${bd()}`,b=t.cwd,S;if(t.cwd===void 0&&r.workspace!==void 0){let C=await this.deriveForkWorkspace(r.workspace,`${r.workspace.label}-fork-${k.slice(-6)}`);C!==void 0?(S=C,b=C.path):(b=r.workspace.sourceCwd,this.logger?.warn?.(`fork ${k}: could not derive an isolated workspace from ${r.workspace.path}; running unisolated in ${b}`))}return await this.writeImportedRecord({sessionId:k,bundle:w,cwd:b,...S!==void 0?{workspace:S}:{},forkedFromSessionId:e,forkedFromMessageId:d,...l!==void 0?{forkSynthesisState:l}:{}}),h&&(async()=>{try{let C=await gr(u,[],{npmRegistry:this.npmRegistry}),I=await _f({agentId:s,cwd:t.cwd??D.sessionDir(e),plan:C,history:a,modelId:f,sessionId:e,logger:this.logger,timeoutMs:p});I&&I.synopsis?await this.mutateRecord(k,{synopsis:I.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(k,{},["forkSynthesisState"]))}catch(C){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${C.message}`);try{await this.mutateRecord(k,{},["forkSynthesisState"])}catch(I){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${I.message}`)}}})(),{sessionId:k,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await kS(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Li.utimes(D.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await $i(D.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let r=new Date().toISOString(),s=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...s?{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,workspace:e.workspace,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??r,updatedAt:e.bundle.session.updatedAt})})}async agentStoreKey(e,t){let r=t.get(e);if(r!==void 0)return r;let s=e;try{let o=await this.registry.getAgent(e);o&&(s=Pg(o))}catch{}return t.set(e,s),s}async tombstoneAllGenerations(e,t,r){let s=await this.store.read(e).catch(()=>{}),o=new Map;for(let d of s?.upstreamGenerations??[])d.upstreamSessionId&&o.set(`${d.agentId}::${d.upstreamSessionId}`,{agentId:d.agentId,upstreamSessionId:d.upstreamSessionId});o.set(`${t.agentId}::${t.upstreamSessionId}`,{agentId:t.agentId,upstreamSessionId:t.upstreamSessionId});let i=new Date().toISOString(),a=new Map;for(let d of o.values())await this.tombstones.add({agentId:await this.agentStoreKey(d.agentId,a),upstreamSessionId:d.upstreamSessionId,deletedAt:i,upstreamUpdatedAt:t.upstreamUpdatedAt,cwd:t.cwd,...t.title!==void 0?{title:t.title}:{},reason:r,...t.interactive!==void 0?{interactive:t.interactive}:{}}).catch(()=>{})}async deleteRecord(e,t="user"){let r=await this.store.read(e);if(!r)return!1;if(r.upstreamSessionId){let s=await il(e),o=vd(r,s.hasContent);await this.tombstoneAllGenerations(e,{agentId:r.agentId,upstreamSessionId:r.upstreamSessionId,upstreamUpdatedAt:r.updatedAt,cwd:r.cwd,...r.title!==void 0?{title:r.title}:{},...o!==void 0?{interactive:o}:{}},t)}return r.workspace!==void 0&&await this.releaseWorkspace(r.workspace,e).catch(()=>{}),await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){let r=await this.agentStoreKey(e,new Map);return(await this.tombstones.read(r,t).catch(()=>{})??(r!==e?await this.tombstones.read(e,t).catch(()=>{}):void 0))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async isRetiredGeneration(e,t){let r=await this.store.read(e).catch(()=>{});return!r||r.upstreamSessionId===t?!1:(r.upstreamGenerations??[]).some(s=>s.upstreamSessionId===t)}async clearWorkspaceBinding(e){if(this.get(e)!==void 0)return"live";let t=await this.store.read(e).catch(()=>{});if(!t)return"missing";let r=t.workspace?.sourceCwd;return await this.mutateRecord(e,r!==void 0?{cwd:r}:{},["workspace"]),"cleared"}async setCwd(e,t){if(this.get(e)!==void 0)return"live";let r=await this.store.read(e).catch(()=>{});return r?r.workspace!==void 0?"bound":await this.dirExists(t)?(await this.mutateRecord(e,{cwd:t}),this.invalidateListCache(),"set"):"not-a-directory":"missing"}async setPriority(e,t){let r=this.get(e);if(r)return r.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let s=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,s),!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 r=this.get(e);return r?(await r.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,r){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r})}async persistAgentChange(e,t,r,s={}){await this.mutateRecord(e,{agentId:t,upstreamSessionId:r},void 0,o=>({upstreamGenerations:Bx(o,t,r,void 0,s)}))}async persistSnapshot(e,t){let r={};t.currentModel!==void 0&&(r.currentModel=t.currentModel),t.currentMode!==void 0&&(r.currentMode=t.currentMode),t.currentUsage!==void 0&&(r.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(r.agentCommands=t.agentCommands),t.agentModes!==void 0&&(r.agentModes=t.agentModes),t.agentModels!==void 0&&(r.agentModels=t.agentModels),t.interactive!==void 0&&(r.interactive=t.interactive),t.cwd!==void 0&&(r.cwd=t.cwd),await this.mutateRecord(e,r)}async mutateRecord(e,t,r=[],s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o,...t,...s?s(o):{},updatedAt:new Date().toISOString()};for(let a of r)delete i[a];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,r){return(await this.getExtensionState(e,t))[r]}async setExtensionStateKey(e,t,r,s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[r]:s},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let c={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(c)})}async deleteExtensionStateKey(e,t,r){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s?.extensionState?.[t])return;let o={...s.extensionState},i={...o[t]};if(!(r in i))return;delete i[r],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...s,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){return this.enqueueKeyed(this.metaWriteQueues,e,t)}enqueueKeyed(e,t,r){let o=(e.get(t)??Promise.resolve()).catch(()=>{}).then(r),i=o.catch(()=>{});return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)}),o}liveSessionsIn(e,t){let r=[];for(let s of this.sessions.values())s.sessionId!==t&&s.workspace?.path===e&&r.push(s);return r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1,by:"daemon-shutdown"}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(s=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${s instanceof Error?s.message:String(s)}`)});let r=t.targetAgentId;(async()=>{try{let s=await this.store.read(e);if(!s?.synopsis||s.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==s.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${r} (reusing artifact @${s.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,s.synopsis,s.summarizedThroughEntry,r)}catch(s){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${s instanceof Error?s.message:String(s)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async persistRollbackBreadcrumb(e,t){await this.mutateRecord(e,{},void 0,r=>{let s=r.rollbackBreadcrumb;return s!==void 0&&t.runId!==void 0&&s.runId===t.runId?(this.logger?.info(`compaction: keeping rollback breadcrumb pinned at ${s.previousUpstreamSessionId} for runId=${t.runId} sessionId=${e} (later swap of the same run)`),{}):{rollbackBreadcrumb:t}})}async getUpstreamGenerations(e){return(await this.store.read(e).catch(()=>{}))?.upstreamGenerations??[]}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,r){let s=this.get(e);if(s){if(t){let o=r.phase==="failed";s.broadcastPendingAgentSwap(o?null:t);return}s.broadcastCompactionPhase(r)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let r of e){let s=r.attentionFlags??[],o=s.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==s.length){let i=s.length-o.length;t+=i,await this.mutateRecord(r.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let r of t){let s=r.compactionState;if(s!=null){if(!e.has(s.status)){this.logger?.info(`compaction: not resuming sessionId=${r.sessionId} status=${s.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${r.sessionId} status=${s.status} from prior daemon`);try{this.scheduleCompaction(r.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${r.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=t.pendingAgentSwap;if(r)try{let s=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=s.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} with persisted synopsis (history=${s.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??s.length,r)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} via fresh synthesis (history=${s.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:r}))}catch(s){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${s instanceof Error?s.message:String(s)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=await MI(t.sessionId).catch(()=>[]);if(r.length===0)continue;let s=Date.now(),o=r.filter(d=>s-d.enqueuedAt<Mx),i=r.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${Mx/1e3}s)`),await zc(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await zc(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function l1(n,e){if(typeof n!="string"||n.length===0)return!1;let t=al.resolve(n),r=al.resolve(e);return t===r||t.startsWith(r+al.sep)}function _x(n,e){if(n===void 0||n.length===0)return!0;let t=$y(n);if($y(e.cwd)===t)return!0;let r=e.workspace?.sourceCwd;return r!==void 0&&$y(r)===t}function $y(n){return n.length>1&&n.endsWith("/")?n.replace(/\/+$/,""):n}function u1(n,e){let r=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,s=n.availableModes(),i=(s.length>0?s.map(l=>{let f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return hy({sessionId:n.sessionId,lineageId:e?.lineageId??Vc(),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:Nx(n.persistableUsage)??e?.currentUsage,agentCommands:r,agentModes:i,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,workspace:n.workspace,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,upstreamGenerations:e?Bx(e,n.agentId,n.upstreamSessionId):void 0,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Nx(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 f1(n){return n?{...n}:void 0}function p1(n){return(n.extendsChain??[n.id]).some(t=>t==="claude-acp"||t.startsWith("claude-acp-"))}var h1=[{type:"system",subtype:"background_tasks_changed"}];function Oy(n,e={}){if(!p1(n))return;let t={extraArgs:{"thinking-display":"summarized"}};return e.model&&(t.model=e.model),{claudeCode:{options:t,emitRawSDKMessages:h1}}}function Hf(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let r=n[e.nestedKey];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=e.fromObject(r);if(i!==void 0)return i}let s=n._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let o=m1(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Fy(n){return Hf(n,{nestedKey:"models",configId:"model",fromObject:e=>$n(e.currentModelId)??$n(e.currentModel)??$n(e.modelId)??$n(e.model),fromConfig:e=>$n(e.currentValue)})}function Mo(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==G.AuthRequired)return n;let r=c=>!!c&&typeof c=="object"&&!Array.isArray(c),s=r(t.data)?t.data:{},o=r(s._meta)?s._meta:{},i=r(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=G.AuthRequired,d.data={...s,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function $x(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function Ox(n,e,t,r){if(n&&typeof n=="object"&&n.code===G.AuthRequired)return n;let s=n instanceof Error?n.message:String(n),o=s.includes("stderr:"),i=o?"":e.stderrTailText(),a=r?`to reproduce: (cd ${$x(r.cwd)} && ${[r.command,...r.args].map($x).join(" ")})`:"";if(!i&&!a)return n;let d=[o?s:`agent ${t} failed to start: ${s}`];i&&d.push(`stderr: ${i}`),a&&d.push(a);let c=new Error(d.join(`
|
|
364
|
-
`));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(c.code=l.code),l.data!==void 0&&(c.data=l.data)}return c}function sl(n){return n._meta?.steering?.supported===!0}function ol(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.id!="string")continue;let s=typeof r.description=="string"?r.description:"",o=r.type==="agent"||r.type==="terminal"?r.type:void 0,i=typeof r.name=="string"?r.name:void 0,a=r._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:r.id,description:s,...o&&{type:o},...i!==void 0&&{name:i},...d&&{_meta:d}})}return e.length>0?e:void 0}function $n(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function
|
|
365
|
-
`))if(r.length!==0)try{let s=JSON.parse(r);typeof s=="string"&&t.push(s)}catch{}return t}catch{return[]}}function Bx(n,e,t,r=new Date().toISOString(),s={}){let{retiredCost:o,retiredUsed:i,startedUsed:a,lifetimeCost:d,reason:c,runId:l}=s,f=m=>d!==void 0&&m.lifetimeCostAtStart!==void 0?Math.max(0,d-m.lifetimeCostAtStart):o,u=n.upstreamGenerations&&n.upstreamGenerations.length>0?[...n.upstreamGenerations]:n.upstreamSessionId?[{upstreamSessionId:n.upstreamSessionId,agentId:n.agentId}]:[],p=u[u.length-1];if(p&&p.upstreamSessionId===t){if(u.length>=2){let m=u[u.length-2];if(m){let h=f(m);u[u.length-2]={...m,...h!==void 0&&m.cost===void 0?{cost:h}:{},...i!==void 0&&m.usedAtEnd===void 0?{usedAtEnd:i}:{}}}}return(c!==void 0&&p.reason===void 0||a!==void 0&&p.usedAtStart===void 0||d!==void 0&&p.lifetimeCostAtStart===void 0)&&(u[u.length-1]={...p,...c!==void 0&&p.reason===void 0?{reason:c,...l!==void 0?{runId:l}:{}}:{},...a!==void 0&&p.usedAtStart===void 0?{usedAtStart:a}:{},...d!==void 0&&p.lifetimeCostAtStart===void 0?{lifetimeCostAtStart:d}:{}}),u}return p&&p.endedAt===void 0&&(u[u.length-1]={...p,endedAt:r,...(()=>{let m=f(p);return m!==void 0?{cost:m}:{}})(),...i!==void 0?{usedAtEnd:i}:{}}),u.push({upstreamSessionId:t,agentId:e,startedAt:r,...c!==void 0?{reason:c}:{},...l!==void 0?{runId:l}:{},...a!==void 0?{usedAtStart:a}:{},...d!==void 0?{lifetimeCostAtStart:d}:{}}),u}async function il(n){try{let e=await Li.stat(D.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function vd(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===_i?!1:e?!0:void 0}import{spawn as
|
|
363
|
+
`)}async copyCarriedWork(e,t,r){let s=await this.patchFromSnapshot(r,t,e.provider);if(s===void 0)return!1;if(s.length===0)return!0;let o=Ne(e.provider);return o===void 0?!1:(await o.applyDelta(e.path,s)).ok}async patchFromSnapshot(e,t,r){let s=Ne(r);if(s===void 0)return;let o=await s.currentState(e);if(o!==void 0)return await s.captureDelta(e,o,t).catch(()=>{})}async unwindStartWorkspace(e){let{provider:t,ws:r,startRef:s,carried:o}=e;await t.unlock(r).catch(()=>{}),o!==void 0&&await t.dropSnapshotRef(r,s).catch(()=>{}),await t.removeWorkspace(r,{force:!0}).catch(()=>{})}async materializeNestedTrees(e,t){let r=Ne(e.provider);if(r?.capabilities().supports.nestedTrees!==!0)return;let s=await r.materializeNested({path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:r.kind},t).catch(o=>({ok:!1,count:0,reason:o instanceof Error?o.message:String(o)}));return s.ok?s.count>0?`populated ${s.count} nested tree(s)`:void 0:`nested trees FAILED: ${s.reason??"unknown"}`}async applyWorkspaceSetup(e,t){let r=await Tf(e.sourceCwd).catch(()=>({})),s=[];if(r.carry!==void 0&&r.carry.length>0){let o=await Sy(e.sourceCwd,e.path,r.carry).catch(()=>{});o!==void 0&&o.copied.length>0&&s.push(`carried ${o.copied.length} config file(s)`)}if(r.postCreate!==void 0){let o=await Ef(r.postCreate,{workspacePath:e.path,sourceCwd:e.sourceCwd,label:e.label,sessionId:t,...r.hookTimeoutSeconds!==void 0?{timeoutSeconds:r.hookTimeoutSeconds}:{}});s.push(o.ok?"ran postCreate":`postCreate FAILED: ${o.reason??"unknown"}`)}return s.length>0?s.join("; "):void 0}async deriveForkWorkspace(e,t){let r=Ne(e.provider);if(r===void 0)return;let s=r.capabilities(),o=s.sharedHistory?await r.currentState(e.path)??"":"",i=await r.createWorkspace({sourceCwd:e.sourceCwd,label:t,...o.length>0?{from:o}:{contentFrom:e.path}}).catch(d=>({ok:!1,reason:String(d)}));if(!i.ok){this.logger?.warn?.(`fork workspace: could not derive from ${e.path}: ${i.reason}`);return}let a=i.workspace;if(o.length>0&&s.supports.captureWorkingState){let d=await r.captureWorkingState(e.path,`hydra: fork carry from ${e.label}`).catch(()=>{});d!==void 0&&d!==o&&await this.copyUncommittedInto(e.path,a.path,o,d,a.provider).catch(()=>{})}return{path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.line!==void 0?{line:a.line}:{},...a.vcs!==void 0?{vcs:{...a.vcs}}:{}}}async copyUncommittedInto(e,t,r,s,o){let i=Ne(o);if(i===void 0)return!1;let a=await i.captureDelta(e,r,s).catch(()=>{});return a===void 0||a.trim().length===0?!1:(await i.applyDelta(t,a,{stage:!0})).ok}async recoverWorkspace(e){let t=Ne(e.provider);if(t===void 0)return;let r={path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}};if(t.capabilities().supports.rematerialize){let o=await t.rematerialize(r).catch(i=>({ok:!1,reason:String(i)}));if(o.ok)return this.logger?.info?.(`session workspace: restored ${o.workspace.path} from retained state`),{...e,path:o.workspace.path};this.logger?.warn?.(`session workspace: could not restore: ${o.reason}`)}if(!await this.dirExists(e.sourceCwd))return;let s=await t.createWorkspace({sourceCwd:e.sourceCwd,label:`${e.label}-r`}).catch(o=>({ok:!1,reason:String(o)}));if(s.ok)return this.logger?.warn?.(`session workspace: ${e.path} is gone and could not be restored; resurrecting in a fresh workspace ${s.workspace.path} from ${e.sourceCwd}. Uncommitted work from the old workspace is not recoverable.`),{path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:{...s.workspace.vcs}}:{}}}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let h=new Error(`agent ${e} not found in registry`);throw h.code=G.AgentNotInstalled,h}let r=await gr(t,[],{npmRegistry:this.npmRegistry}),s=this.spawner({agentId:e,cwd:Lx.homedir(),plan:r}),o;try{o=await s.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}})}catch(h){throw await s.kill().catch(()=>{}),Mo(h,s)}if(s.authMethods=ol(o.authMethods),s.steeringSupported=sl(o),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await s.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(s)}catch(h){throw await s.kill().catch(()=>{}),h}await s.kill().catch(()=>{});let d=new Map,c=Pg(t);d.set(e,c);let l=new Set;for(let h of this.sessions.values()){let y=await this.agentStoreKey(h.agentId,d);l.add(`${y}::${h.upstreamSessionId}`)}let f=await this.store.list().catch(()=>[]);for(let h of f){l.add(`${await this.agentStoreKey(h.agentId,d)}::${h.upstreamSessionId}`);for(let y of h.upstreamGenerations??[])l.add(`${await this.agentStoreKey(y.agentId,d)}::${y.upstreamSessionId}`)}let u=D.sessionsDir(),p=[],m=0;for(let h of a){let y=`${c}::${h.sessionId}`;if(l.has(y)){m+=1;continue}if(lL(h.cwd,u)){m+=1;continue}let w=c,k=await this.tombstones.read(w,h.sessionId).catch(()=>{});if(!k&&c!==e&&(w=e,k=await this.tombstones.read(w,h.sessionId).catch(()=>{})),k){if(!dx(k,h.updatedAt)){m+=1;continue}await this.tombstones.remove(w,h.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${h.sessionId} (upstream updatedAt advanced past ${k.upstreamUpdatedAt??"<unset>"})`)}l.add(y);let b=`${wn}${bd()}`,S=new Date().toISOString(),C=h.updatedAt??S,I={sessionId:b,lineageId:Vc(),upstreamSessionId:h.sessionId,agentId:e,cwd:h.cwd,pendingHistorySync:!0,interactive:!0,createdAt:C,updatedAt:C};h.title!==void 0&&(I.title=h.title);let T=hy(I);await this.store.write(T),p.push({version:1,...T})}return{synced:p,skipped:m}}async collectAgentSessions(e){let t=[],r,s=new Set;for(let o=0;o<100;o+=1){let i={};r!==void 0&&(i.cursor=r);let a=await e.connection.request("session/list",i),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.updatedAt),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||s.has(a.nextCursor))break;s.add(a.nextCursor),r=a.nextCursor}return t}async applySeedModel(e,t,r,s,o){try{let{verb:i,result:a}=await Eo({request:(d,c)=>e.connection.request(d,c),sessionId:t,modelId:r,...o?{verb:o}:{},logger:this.logger});return this.logger?.info(`${s}: ${i} accepted`),{accepted:!0,result:a}}catch(i){return this.logger?.warn(`${s} rejected by agent (${i.message}); session will use the agent's own default`),{accepted:!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=G.AgentNotInstalled,i}let r=await gr(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),s=Yu(e.selfSessionId,e.forwardedEnv),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...s?{extraEnv:s}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}}),a=i.agentCapabilities;o.authMethods=ol(i.authMethods),o.steeringSupported=sl(i);let d=Oy(t),c=await o.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[],...d&&{_meta:d}}),l=c.sessionId;if(typeof l!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let f=Fy(c),u=Ny(c),p=dd(c),m=mr(this.defaultModels,t),h=e.model??m?.value,y;if(h&&h!==f){let S=ud(h,u),C=e.model!==void 0?`model=${JSON.stringify(h)}`:`defaultModels[${m?.from??e.agentId}]=${JSON.stringify(h)}`;if(S.kind==="exact"||S.kind==="none"){let I=await this.applySeedModel(o,l,h,C,p);I.accepted&&(f=h,y=I.result)}else if(S.kind==="resolved")if(S.modelId===f)f=S.modelId;else{let I=await this.applySeedModel(o,l,S.modelId,`${C} resolved to ${JSON.stringify(S.modelId)}`,p);I.accepted&&(f=S.modelId,y=I.result)}else if(S.kind==="ambiguous")this.logger?.warn(`${C} is ambiguous (trailing-segment matches [${S.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(f)}`);else{let I=u.map(T=>T.modelId).join(", ");this.logger?.warn(`${C} not in agent's availableModels ([${I}]); skipping session/set_model, session will use ${JSON.stringify(f)}`)}}let w=By(c),k=Dy(c),b=Bf(Ly(y)?y:c);return{agent:o,upstreamSessionId:l,agentMeta:c._meta,agentCapabilities:a,initialModel:f,initialModels:u.length>0?u:void 0,initialModes:w.length>0?w:void 0,initialMode:k,initialConfigOptions:b.length>0?b:void 0,modelVerb:p}}catch(i){throw await o.kill().catch(()=>{}),Mo(Ox(i,o,e.agentId,{command:r.command,args:r.args,cwd:e.cwd}),o)}}async bootstrapAgentLoad(e,t){let r=await this.registry.getAgent(t.agentId);if(!r){let a=new Error(`agent ${t.agentId} not found in registry`);throw a.code=G.AgentNotInstalled,a}let s=await gr(r,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=Yu(t.selfSessionId,t.forwardedEnv),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:s,...o?{extraEnv:o}:{}});try{let a=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}}),d=a.agentCapabilities;i.authMethods=ol(a.authMethods),i.steeringSupported=sl(a);let c=Oy(r),l=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),f=Fy(l),u=kd(Ny(l)),p=By(l),m=Dy(l),h=kd(Bf(l));return{agent:i,upstreamSessionId:e,agentMeta:l._meta,agentCapabilities:d,initialModel:f,initialModels:u,initialModes:p.length>0?p:void 0,initialMode:m,initialConfigOptions:h,modelVerb:dd(l)}}catch(a){throw await i.kill().catch(()=>{}),Mo(Ox(a,i,t.agentId,{command:s.command,args:s.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let r=await this.store.read(e);if(!r)throw new Error("session record not found");let s=r.rollbackBreadcrumb;if(!s)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=r.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:s.previousUpstreamSessionId,previousSummarizedThroughEntry:s.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:s.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let r=this.pendingAuthAgents.get(e);if(r&&r.isAlive())return r;let s=await this.registry.getAgent(e);if(!s){let d=new Error(`agent ${e} not found in registry`);throw d.code=G.AgentNotInstalled,d}let o=await gr(s,[],{npmRegistry:this.npmRegistry}),i=t??mt(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:ad,clientInfo:{name:"hydra",version:He}});a.authMethods=ol(d.authMethods),a.steeringSupported=sl(d)}catch(d){throw await a.kill().catch(()=>{}),Mo(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 r=new Error(`agent ${e} not found in registry`);throw r.code=G.AgentNotInstalled,r}return gr(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.driftNoticed.delete(e.sessionId),this.invalidateListCache(),t&&e.workspace!==void 0&&this.releaseWorkspace(e.workspace,e.sessionId).catch(()=>{}),t){if(e.upstreamSessionId){let s=vd({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstoneAllGenerations(e.sessionId,{agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,...e.title!==void 0?{title:e.title}:{},...s!==void 0?{interactive:s}:{}},"user").catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let r=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===r&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,r);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:r,...s})=>{this.persistAgentChange(e.sessionId,t,r,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:Nx(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(r=>({name:r.name,...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(r=>({id:r.id,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(r=>({modelId:r.modelId,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),r=uL(e,t);await this.store.write(r)}).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,t={}){return this.histories.load(e,t)}async loadToolBlob(e,t){return Nc(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let r=t.title;return r||(r=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:r,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:fL(t.currentUsage),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,workspace:t.workspace,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(s=>!(s.source==="daemon"&&s.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let r=this.sessions.get(e);r&&(r.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s)return;let o={...s,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let r={...t};delete r.pendingHistorySync,await this.store.write(r)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let r of t){let s=r.params;if(s?.update?.sessionUpdate!=="prompt_received")continue;let o=s.update.sentBy;if(typeof o?.fromSession=="string"||typeof o?.clientId=="string"&&o.clientId.startsWith("transformer:"))continue;let i=Pi(s.update.prompt),a=iy(i,200);if(a&&!a.startsWith("/"))return a}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}setLiveConfig(e){e.defaultModels&&(this.defaultModels=e.defaultModels)}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let r=t.agent.installId,s=t.agent.version,o=e.get(r);o||(o=new Set,e.set(r,o)),o.add(s)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(wn))return;let t=wn+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let r=new Error(`session ${e} not found`);throw r.code=G.SessionNotFound,r}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,workspace:e.workspace,workspaceError:e.workspaceError,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,armedTasks:e.armedBackgroundTasks.length,...e.armedSince!==void 0?{armedSince:e.armedSince}:{},awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await il(t.sessionId),d=vd({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,armedTasks:t.armedBackgroundTasks.length,...t.armedSince!==void 0?{armedSince:t.armedSince}:{},awaitingInput:t.awaitingInput}}let r=await this.store.read(e).catch(()=>{});if(!r)return;let s=await il(r.sessionId),o=vd(r,s.hasContent),i=s.mtime??r.updatedAt;return{sessionId:r.sessionId,upstreamSessionId:r.upstreamSessionId,cwd:r.cwd,title:r.title,agentId:r.agentId,currentModel:r.currentModel,currentUsage:Fi(r.currentUsage),importedFromMachine:r.importedFromMachine,importedFromUpstreamSessionId:r.importedFromUpstreamSessionId,parentSessionId:r.parentSessionId,forkedFromSessionId:r.forkedFromSessionId,forkedFromMessageId:r.forkedFromMessageId,forkSynthesisState:r.forkSynthesisState,originatingClient:r.originatingClient,interactive:o,priority:r.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}|${e.status??""}`,r=Date.now(),s=this.listCache.get(t);if(s&&s.expiresAt>r)return s.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:r+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],r=new Set,s=l=>e.includeNonInteractive?!0:l===!0,o=[...this.sessions.values()].filter(l=>_x(e.cwd,l));if(e.status==="cold")for(let l of o)r.add(l.sessionId);let i=e.status==="cold"?[]:await Promise.all(o.map(l=>il(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=o[l],u=i[l];r.add(f.sessionId);let p=vd({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!s(p))continue;let m=u.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,workspace:f.workspace,workspaceError:f.workspaceError,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"warm",agentPid:f.agentPid,busy:f.turnStartedAt!==void 0,armedTasks:f.armedBackgroundTasks.length,...f.armedSince!==void 0?{armedSince:f.armedSince}:{},awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}if(e.status==="warm")return t;let d=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!r.has(l.sessionId)&&_x(e.cwd,l)),c=await Promise.all(d.map(l=>il(l.sessionId)));for(let l=0;l<d.length;l+=1){let f=d[l],u=c[l],p=vd(f,u.hasContent);if(!s(p))continue;let m=u.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,workspace:f.workspace,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:Fi(f.currentUsage),importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((l,f)=>l.updatedAt<f.updatedAt?1:-1),t}async exportBundle(e,t={}){let r=await this.store.read(e);if(!r)return;let s;if(r.lineageId)s=r;else{let c=Vc(),l={...r,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),s=l}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Fx(e);if(o!=="references")return{record:s,history:i,promptHistory:a};let d={};for(let c of Cx(i)){let l=await bS(e,c);l&&(d[c]=l.toString("base64"))}return{record:s,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let r=await this.store.findByLineageId(e.session.lineageId);if(r){if(!t.replace){let i=new Error(`bundle already imported as ${r.sessionId}`);throw i.code=G.BundleAlreadyImported,i.existingSessionId=r.sessionId,i}let o=this.sessions.get(r.sessionId);return o&&await o.close({deleteRecord:!1,by:"bundle-import-overwrite"}).catch(()=>{}),await this.writeImportedRecord({sessionId:r.sessionId,bundle:e,preservedCreatedAt:r.createdAt,cwd:t.cwd}),{sessionId:r.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let s=`${wn}${bd()}`;return await this.writeImportedRecord({sessionId:s,bundle:e,cwd:t.cwd}),{sessionId:s,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let r=await this.store.read(e);if(!r){let C=new Error(`source session not found: ${e}`);throw C.code=G.SessionNotFound,C}let s=t.agentId??r.agentId,o=s!==r.agentId;if(o&&!await this.registry.getAgent(s)){let I=new Error(`agent ${s} not found in registry`);throw I.code=G.AgentNotInstalled,I}let i=await this.histories.load(e).catch(()=>[]),a=i,d,c=t.mode??"synthesis",l,f,u,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let C=mf(i,t.forkAt);if(C<0){let I=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw I.code=G.InvalidParams,I}d=t.forkAt,a=i.slice(0,C+1)}else{let C=gL(i);C?(d=C.messageId,a=i.slice(0,C.index+1)):(d="",a=i.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let I=mf(i,t.forkAt);if(I<0){let T=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw T.code=G.InvalidParams,T}d=t.forkAt,a=i.slice(0,I+1)}else d="",a=i;let C=await this.registry.getAgent(s);if(!C){let I=new Error(`agent ${s} not found in registry`);throw I.code=G.AgentNotInstalled,I}u=C,f=r.currentModel,l="running"}let m=await Fx(e),h=c==="synthesis",y={...r,lineageId:Vc(),agentId:s,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},w=nl({record:y,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:He,machine:To()}),k=`${wn}${bd()}`,b=t.cwd,S;if(t.cwd===void 0&&r.workspace!==void 0){let C=await this.deriveForkWorkspace(r.workspace,`${r.workspace.label}-fork-${k.slice(-6)}`);C!==void 0?(S=C,b=C.path):(b=r.workspace.sourceCwd,this.logger?.warn?.(`fork ${k}: could not derive an isolated workspace from ${r.workspace.path}; running unisolated in ${b}`))}return await this.writeImportedRecord({sessionId:k,bundle:w,cwd:b,...S!==void 0?{workspace:S}:{},forkedFromSessionId:e,forkedFromMessageId:d,...l!==void 0?{forkSynthesisState:l}:{}}),h&&(async()=>{try{let C=await gr(u,[],{npmRegistry:this.npmRegistry}),I=await _f({agentId:s,cwd:t.cwd??D.sessionDir(e),plan:C,history:a,modelId:f,sessionId:e,logger:this.logger,timeoutMs:p});I&&I.synopsis?await this.mutateRecord(k,{synopsis:I.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(k,{},["forkSynthesisState"]))}catch(C){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${C.message}`);try{await this.mutateRecord(k,{},["forkSynthesisState"])}catch(I){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${I.message}`)}}})(),{sessionId:k,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await kS(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Li.utimes(D.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await $i(D.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let r=new Date().toISOString(),s=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...s?{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,workspace:e.workspace,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??r,updatedAt:e.bundle.session.updatedAt})})}async agentStoreKey(e,t){let r=t.get(e);if(r!==void 0)return r;let s=e;try{let o=await this.registry.getAgent(e);o&&(s=Pg(o))}catch{}return t.set(e,s),s}async tombstoneAllGenerations(e,t,r){let s=await this.store.read(e).catch(()=>{}),o=new Map;for(let d of s?.upstreamGenerations??[])d.upstreamSessionId&&o.set(`${d.agentId}::${d.upstreamSessionId}`,{agentId:d.agentId,upstreamSessionId:d.upstreamSessionId});o.set(`${t.agentId}::${t.upstreamSessionId}`,{agentId:t.agentId,upstreamSessionId:t.upstreamSessionId});let i=new Date().toISOString(),a=new Map;for(let d of o.values())await this.tombstones.add({agentId:await this.agentStoreKey(d.agentId,a),upstreamSessionId:d.upstreamSessionId,deletedAt:i,upstreamUpdatedAt:t.upstreamUpdatedAt,cwd:t.cwd,...t.title!==void 0?{title:t.title}:{},reason:r,...t.interactive!==void 0?{interactive:t.interactive}:{}}).catch(()=>{})}async deleteRecord(e,t="user"){let r=await this.store.read(e);if(!r)return!1;if(r.upstreamSessionId){let s=await il(e),o=vd(r,s.hasContent);await this.tombstoneAllGenerations(e,{agentId:r.agentId,upstreamSessionId:r.upstreamSessionId,upstreamUpdatedAt:r.updatedAt,cwd:r.cwd,...r.title!==void 0?{title:r.title}:{},...o!==void 0?{interactive:o}:{}},t)}return r.workspace!==void 0&&await this.releaseWorkspace(r.workspace,e).catch(()=>{}),await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){let r=await this.agentStoreKey(e,new Map);return(await this.tombstones.read(r,t).catch(()=>{})??(r!==e?await this.tombstones.read(e,t).catch(()=>{}):void 0))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async isRetiredGeneration(e,t){let r=await this.store.read(e).catch(()=>{});return!r||r.upstreamSessionId===t?!1:(r.upstreamGenerations??[]).some(s=>s.upstreamSessionId===t)}async clearWorkspaceBinding(e){if(this.get(e)!==void 0)return"live";let t=await this.store.read(e).catch(()=>{});if(!t)return"missing";let r=t.workspace?.sourceCwd;return await this.mutateRecord(e,r!==void 0?{cwd:r}:{},["workspace"]),"cleared"}async setCwd(e,t){if(this.get(e)!==void 0)return"live";let r=await this.store.read(e).catch(()=>{});return r?r.workspace!==void 0?"bound":await this.dirExists(t)?(await this.mutateRecord(e,{cwd:t}),this.invalidateListCache(),"set"):"not-a-directory":"missing"}async setPriority(e,t){let r=this.get(e);if(r)return r.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let s=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,s),!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 r=this.get(e);return r?(await r.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,r){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r})}async persistAgentChange(e,t,r,s={}){await this.mutateRecord(e,{agentId:t,upstreamSessionId:r},void 0,o=>({upstreamGenerations:Bx(o,t,r,void 0,s)}))}async persistSnapshot(e,t){let r={};t.currentModel!==void 0&&(r.currentModel=t.currentModel),t.currentMode!==void 0&&(r.currentMode=t.currentMode),t.currentUsage!==void 0&&(r.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(r.agentCommands=t.agentCommands),t.agentModes!==void 0&&(r.agentModes=t.agentModes),t.agentModels!==void 0&&(r.agentModels=t.agentModels),t.interactive!==void 0&&(r.interactive=t.interactive),t.cwd!==void 0&&(r.cwd=t.cwd),await this.mutateRecord(e,r)}async mutateRecord(e,t,r=[],s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o,...t,...s?s(o):{},updatedAt:new Date().toISOString()};for(let a of r)delete i[a];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,r){return(await this.getExtensionState(e,t))[r]}async setExtensionStateKey(e,t,r,s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[r]:s},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let c={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(c)})}async deleteExtensionStateKey(e,t,r){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s?.extensionState?.[t])return;let o={...s.extensionState},i={...o[t]};if(!(r in i))return;delete i[r],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...s,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){return this.enqueueKeyed(this.metaWriteQueues,e,t)}enqueueKeyed(e,t,r){let o=(e.get(t)??Promise.resolve()).catch(()=>{}).then(r),i=o.catch(()=>{});return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)}),o}liveSessionsIn(e,t){let r=[];for(let s of this.sessions.values())s.sessionId!==t&&s.workspace?.path===e&&r.push(s);return r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1,by:"daemon-shutdown"}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(s=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${s instanceof Error?s.message:String(s)}`)});let r=t.targetAgentId;(async()=>{try{let s=await this.store.read(e);if(!s?.synopsis||s.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==s.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${r} (reusing artifact @${s.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,s.synopsis,s.summarizedThroughEntry,r)}catch(s){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${s instanceof Error?s.message:String(s)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async persistRollbackBreadcrumb(e,t){await this.mutateRecord(e,{},void 0,r=>{let s=r.rollbackBreadcrumb;return s!==void 0&&t.runId!==void 0&&s.runId===t.runId?(this.logger?.info(`compaction: keeping rollback breadcrumb pinned at ${s.previousUpstreamSessionId} for runId=${t.runId} sessionId=${e} (later swap of the same run)`),{}):{rollbackBreadcrumb:t}})}async getUpstreamGenerations(e){return(await this.store.read(e).catch(()=>{}))?.upstreamGenerations??[]}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,r){let s=this.get(e);if(s){if(t){let o=r.phase==="failed";s.broadcastPendingAgentSwap(o?null:t);return}s.broadcastCompactionPhase(r)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let r of e){let s=r.attentionFlags??[],o=s.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==s.length){let i=s.length-o.length;t+=i,await this.mutateRecord(r.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let r of t){let s=r.compactionState;if(s!=null){if(!e.has(s.status)){this.logger?.info(`compaction: not resuming sessionId=${r.sessionId} status=${s.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${r.sessionId} status=${s.status} from prior daemon`);try{this.scheduleCompaction(r.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${r.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=t.pendingAgentSwap;if(r)try{let s=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=s.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} with persisted synopsis (history=${s.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??s.length,r)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} via fresh synthesis (history=${s.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:r}))}catch(s){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${s instanceof Error?s.message:String(s)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=await MI(t.sessionId).catch(()=>[]);if(r.length===0)continue;let s=Date.now(),o=r.filter(d=>s-d.enqueuedAt<Mx),i=r.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${Mx/1e3}s)`),await zc(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await zc(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function lL(n,e){if(typeof n!="string"||n.length===0)return!1;let t=al.resolve(n),r=al.resolve(e);return t===r||t.startsWith(r+al.sep)}function _x(n,e){if(n===void 0||n.length===0)return!0;let t=$y(n);if($y(e.cwd)===t)return!0;let r=e.workspace?.sourceCwd;return r!==void 0&&$y(r)===t}function $y(n){return n.length>1&&n.endsWith("/")?n.replace(/\/+$/,""):n}function uL(n,e){let r=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,s=n.availableModes(),i=(s.length>0?s.map(l=>{let f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return hy({sessionId:n.sessionId,lineageId:e?.lineageId??Vc(),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:Nx(n.persistableUsage)??e?.currentUsage,agentCommands:r,agentModes:i,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,workspace:n.workspace,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,upstreamGenerations:e?Bx(e,n.agentId,n.upstreamSessionId):void 0,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Nx(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 fL(n){return n?{...n}:void 0}function pL(n){return(n.extendsChain??[n.id]).some(t=>t==="claude-acp"||t.startsWith("claude-acp-"))}var hL=[{type:"system",subtype:"background_tasks_changed"}];function Oy(n,e={}){if(!pL(n))return;let t={extraArgs:{"thinking-display":"summarized"}};return e.model&&(t.model=e.model),{claudeCode:{options:t,emitRawSDKMessages:hL}}}function Hf(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let r=n[e.nestedKey];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=e.fromObject(r);if(i!==void 0)return i}let s=n._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let o=mL(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Fy(n){return Hf(n,{nestedKey:"models",configId:"model",fromObject:e=>$n(e.currentModelId)??$n(e.currentModel)??$n(e.modelId)??$n(e.model),fromConfig:e=>$n(e.currentValue)})}function Mo(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==G.AuthRequired)return n;let r=c=>!!c&&typeof c=="object"&&!Array.isArray(c),s=r(t.data)?t.data:{},o=r(s._meta)?s._meta:{},i=r(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=G.AuthRequired,d.data={...s,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function $x(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function Ox(n,e,t,r){if(n&&typeof n=="object"&&n.code===G.AuthRequired)return n;let s=n instanceof Error?n.message:String(n),o=s.includes("stderr:"),i=o?"":e.stderrTailText(),a=r?`to reproduce: (cd ${$x(r.cwd)} && ${[r.command,...r.args].map($x).join(" ")})`:"";if(!i&&!a)return n;let d=[o?s:`agent ${t} failed to start: ${s}`];i&&d.push(`stderr: ${i}`),a&&d.push(a);let c=new Error(d.join(`
|
|
364
|
+
`));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(c.code=l.code),l.data!==void 0&&(c.data=l.data)}return c}function sl(n){return n._meta?.steering?.supported===!0}function ol(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.id!="string")continue;let s=typeof r.description=="string"?r.description:"",o=r.type==="agent"||r.type==="terminal"?r.type:void 0,i=typeof r.name=="string"?r.name:void 0,a=r._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:r.id,description:s,...o&&{type:o},...i!==void 0&&{name:i},...d&&{_meta:d}})}return e.length>0?e:void 0}function $n(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function mL(n,e){let t=n.configOptions;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r;if(s.id===e)return s}}function Ly(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Array.isArray(n.configOptions)}function Bf(n){let e=n.configOptions;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r,o=$n(s.id);if(!o||o==="model"||o==="mode"||o==="agent")continue;let i=oy(s.options);if(i.length===0)continue;let a=$n(s.description);t.push({id:o,name:$n(s.name)??o,...a?{description:a}:{},category:$n(s.category)??"other",type:"select",currentValue:$n(s.currentValue)??i[0].value,options:i})}return t}function kd(n){return n.length>0?n:void 0}function Ny(n){return Hf(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Kc(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Kc(e.options);return t.length>0?t:void 0}})??[]}function By(n){return Hf(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=hf(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=hf(e.options);return t.length>0?t:void 0}})??[]}function Dy(n){return Hf(n,{nestedKey:"modes",configId:"mode",fromObject:e=>$n(e.currentModeId)??$n(e.currentMode)??$n(e.modeId)??$n(e.mode),fromConfig:e=>$n(e.currentValue)})}function gL(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let r=t.params?.update;if(r?.sessionUpdate==="turn_complete"&&!(typeof r.messageId!="string"||r.messageId.length===0))return{index:e,messageId:r.messageId}}}async function Fx(n){try{let e=await Li.readFile(D.tuiHistoryFile(n),"utf8"),t=[];for(let r of e.split(`
|
|
365
|
+
`))if(r.length!==0)try{let s=JSON.parse(r);typeof s=="string"&&t.push(s)}catch{}return t}catch{return[]}}function Bx(n,e,t,r=new Date().toISOString(),s={}){let{retiredCost:o,retiredUsed:i,startedUsed:a,lifetimeCost:d,reason:c,runId:l}=s,f=m=>d!==void 0&&m.lifetimeCostAtStart!==void 0?Math.max(0,d-m.lifetimeCostAtStart):o,u=n.upstreamGenerations&&n.upstreamGenerations.length>0?[...n.upstreamGenerations]:n.upstreamSessionId?[{upstreamSessionId:n.upstreamSessionId,agentId:n.agentId}]:[],p=u[u.length-1];if(p&&p.upstreamSessionId===t){if(u.length>=2){let m=u[u.length-2];if(m){let h=f(m);u[u.length-2]={...m,...h!==void 0&&m.cost===void 0?{cost:h}:{},...i!==void 0&&m.usedAtEnd===void 0?{usedAtEnd:i}:{}}}}return(c!==void 0&&p.reason===void 0||a!==void 0&&p.usedAtStart===void 0||d!==void 0&&p.lifetimeCostAtStart===void 0)&&(u[u.length-1]={...p,...c!==void 0&&p.reason===void 0?{reason:c,...l!==void 0?{runId:l}:{}}:{},...a!==void 0&&p.usedAtStart===void 0?{usedAtStart:a}:{},...d!==void 0&&p.lifetimeCostAtStart===void 0?{lifetimeCostAtStart:d}:{}}),u}return p&&p.endedAt===void 0&&(u[u.length-1]={...p,endedAt:r,...(()=>{let m=f(p);return m!==void 0?{cost:m}:{}})(),...i!==void 0?{usedAtEnd:i}:{}}),u.push({upstreamSessionId:t,agentId:e,startedAt:r,...c!==void 0?{reason:c}:{},...l!==void 0?{runId:l}:{},...a!==void 0?{usedAtStart:a}:{},...d!==void 0?{lifetimeCostAtStart:d}:{}}),u}async function il(n){try{let e=await Li.stat(D.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function vd(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===_i?!1:e?!0:void 0}import{spawn as yL}from"child_process";import*as Wf from"fs";import*as Xs from"fs/promises";import*as jf from"path";import wL from"pino-roll";var Uf=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,r){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${r}s start ${t}\``;return this.tripped_=i,{tripped:i}}let s=this.now();this.recentExits.push(s);let o=s-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${r}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};ot();ed();var bL=1e3,kL=6e4,Hy=3e3,Sd=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,r,s={}){this.adapter=t,this.context=r,this.tokenRegistry=s.tokenRegistry,this.breakerOptions=s.breakerOptions,this.restartBaseMs=s.restartBaseMs??bL,this.restartCapMs=s.restartCapMs??kL;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let r=this.entries.get(e);r&&(r.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Xs.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let r=t.child;if(r){try{r.kill("SIGTERM")}catch{}e.push(new Promise(s=>{if(r.exitCode!==null||r.signalCode!==null){s();return}let o=setTimeout(()=>{try{r.kill("SIGKILL")}catch{}s()},Hy);r.on("exit",()=>{clearTimeout(o),s()})}))}}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 dl(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw dl(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw dl(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let r=t.child;return r?(await this.terminate(t,r),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 dl(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(r=>{t.failureReason=`spawn: ${r.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw dl(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let r=t.child;r&&await this.terminate(t,r);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let r=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let s=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Hy);typeof s.unref=="function"&&s.unref();try{await r}finally{clearTimeout(s)}}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 Uf(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Xs.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let r=this.adapter.paths.pidFile(t.name),s;try{let o=await Xs.readFile(r,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(s=i)}catch{}if(typeof s=="number"&&Uy(s)){try{process.kill(s,"SIGTERM")}catch{}let o=Date.now()+Hy;for(;Date.now()<o&&Uy(s);)await new Promise(i=>setTimeout(i,50));if(Uy(s))try{process.kill(s,"SIGKILL")}catch{}}await Xs.unlink(r).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let r=this.context;if(!r)throw new Error(`${this.managerName()}.spawn called before setContext`);let s=e.config,o=s.command.length>0?s.command:[s.name],i=jf.dirname(this.adapter.paths.logFile(s.name)),a;try{await Xs.mkdir(i,{recursive:!0}),a=await wL({file:jf.join(i,`${s.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",y=>{e.failureReason=`log stream: ${y.message}`})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${s.name} (attempt ${t+1})
|
|
366
366
|
`);let d=this.tokenRegistry?.mint(s.name,this.adapter.tokenRole)??r.serviceToken;e.processToken=d,e.version=void 0;let c={...Za(),HYDRA_ACP_DAEMON_URL:r.daemonUrl,HYDRA_ACP_DAEMON_HOST:r.daemonHost,HYDRA_ACP_DAEMON_PORT:String(r.daemonPort),HYDRA_ACP_TOKEN:d,HYDRA_ACP_WS_URL:r.daemonWsUrl,HYDRA_ACP_HOME:r.hydraHome,[this.adapter.nameEnvVar]:s.name,...s.env},[l,...f]=o;if(l===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${s.name} has empty command
|
|
367
|
-
`),a.end();return}let u=mt(l),p=[...f,...s.args].map(mt),m;try{m=
|
|
367
|
+
`),a.end();return}let u=mt(l),p=[...f,...s.args].map(mt),m;try{m=yL(u,p,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${s.name}: ${y.message}
|
|
368
368
|
`),a.end(),this.scheduleRestart(e,t);return}let h=y=>{try{a.write(typeof y=="string"?y:y.toString())}catch{}};if(m.stdout?.on("data",h),m.stderr?.on("data",h),typeof m.pid=="number")try{Wf.writeFileSync(this.adapter.paths.pidFile(s.name),`${m.pid}
|
|
369
369
|
`,{encoding:"utf8",mode:384})}catch(y){a.write(`[hydra-acp] failed to write pid file for ${s.name}: ${y.message}
|
|
370
370
|
`)}e.child=m,e.logStream=a,e.pid=typeof m.pid=="number"?m.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,m.on("error",y=>{a.write(`[hydra-acp] ${this.adapter.kind} ${s.name} error: ${y.message}
|
|
371
371
|
`)}),m.on("exit",(y,w)=>{try{Wf.unlinkSync(this.adapter.paths.pidFile(s.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${s.name} exited code=${y??"null"} signal=${w??"null"}
|
|
372
372
|
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof y=="number"?y:void 0,e.processToken&&(this.tokenRegistry?.revoke(s.name),e.processToken=void 0);let k=e.exitWaiters.splice(0);for(let S of k)S();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let b=e.breaker.recordExit(y,s.name,this.adapter.kind);if(typeof b=="object"){e.failureReason=b.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${s.name} circuit breaker tripped: ${b.tripped}
|
|
373
|
-
`);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let r=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(s=>{e.failureReason=`spawn: ${s.message}`})},r),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Uy(n){try{return process.kill(n,0),!0}catch{return!1}}function dl(n,e){return n.code=e,n}ve();var
|
|
373
|
+
`);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let r=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(s=>{e.failureReason=`spawn: ${s.message}`})},r),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Uy(n){try{return process.kill(n,0),!0}catch{return!1}}function dl(n,e){return n.code=e,n}ve();var vL={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:D.extensionsDir,logFile:D.extensionLogFile,pidFile:D.extensionPidFile}},qf=class extends Sd{constructor(e,t,r={}){super(e,vL,t,r)}};ve();var SL={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:D.transformersDir,logFile:D.transformerLogFile,pidFile:D.transformerPidFile}},zf=class extends Sd{connected=new Map;constructor(e,t,r={}){super(e,SL,t,r)}registerConnection(e,t,r){this.connected.set(e,{name:e,connection:t,intercepts:new Set(r)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let r of e){let s=this.connected.get(r);s&&t.push(s)}return t}interestedIn(e){let t=[];for(let r of this.connected.values())r.intercepts.has(e)&&t.push(r);return t}};var Kf=class{entries=new Map;changeHandlers=[];register(e,t,r){this.entries.set(e,{connection:t,commands:[...r]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,r]of this.entries)for(let s of r.commands)e.push({name:t,command:s});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};ve();Wa();rd();Tg();ve();rd();import*as ll from"fs/promises";import*as Gf from"path";var cl=n=>{process.stderr.write(n+`
|
|
374
374
|
`)};function Wy(n){cl=n??(e=>process.stderr.write(e+`
|
|
375
|
-
`))}async function Dx(n,e){let t=hr();if(!t)return;let r=await n.load(),s=new Map;for(let d of r.agents)s.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=Gf.join(D.agentsDir(),t),a;try{a=await ll.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;cl(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=s.get(c);if(l===void 0)continue;let f=o.get(c)??new Set,u=Gf.join(i,c),p;try{p=await ll.readdir(u,{withFileTypes:!0})}catch(m){cl(`hydra-acp: prune: failed to read ${u}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let y=Gf.join(u,h);try{await ll.rm(y,{recursive:!0,force:!0}),cl(`hydra-acp: pruned stale ${c} ${h} (${y})`)}catch(w){cl(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}ws();function Hx(n){let e,t=!1,r=0,s=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let l=await n.registry.load();for(let f of l.agents)await _g(f)==="yes"&&a.push(f.id)}catch(l){return s("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=r%a.length;r=(r+1)%a.length;let c=a[d];try{let{synced:l,skipped:f}=await n.manager.syncFromAgent(c);s("info",`${c}: synced ${l.length}, skipped ${f}`)}catch(l){s("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{s("warn",`tick crashed: ${d.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function jy(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},r=Date.now(),s=n.maxAgeMs>0?r-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(n.maxAgeMs>0&&h>s||i.push({sessionId:p.sessionId,lastUsedMs:h}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p,"expired")&&(c+=1)}catch(m){l+=1,t("warn",`delete ${p} failed: ${m.message}`)}let f=i.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${
|
|
375
|
+
`))}async function Dx(n,e){let t=hr();if(!t)return;let r=await n.load(),s=new Map;for(let d of r.agents)s.set(d.id,d.version??"current");let o=e.activeAgentVersions(),i=Gf.join(D.agentsDir(),t),a;try{a=await ll.readdir(i,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;cl(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=s.get(c);if(l===void 0)continue;let f=o.get(c)??new Set,u=Gf.join(i,c),p;try{p=await ll.readdir(u,{withFileTypes:!0})}catch(m){cl(`hydra-acp: prune: failed to read ${u}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let y=Gf.join(u,h);try{await ll.rm(y,{recursive:!0,force:!0}),cl(`hydra-acp: pruned stale ${c} ${h} (${y})`)}catch(w){cl(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}ws();function Hx(n){let e,t=!1,r=0,s=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},o=async()=>{let a=[];try{let l=await n.registry.load();for(let f of l.agents)await _g(f)==="yes"&&a.push(f.id)}catch(l){return s("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=r%a.length;r=(r+1)%a.length;let c=a[d];try{let{synced:l,skipped:f}=await n.manager.syncFromAgent(c);s("info",`${c}: synced ${l.length}, skipped ${f}`)}catch(l){s("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(d=>{i(d)}).catch(d=>{s("warn",`tick crashed: ${d.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function jy(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},r=Date.now(),s=n.maxAgeMs>0?r-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(n.maxAgeMs>0&&h>s||i.push({sessionId:p.sessionId,lastUsedMs:h}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p,"expired")&&(c+=1)}catch(m){l+=1,t("warn",`delete ${p} failed: ${m.message}`)}let f=i.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${IL(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:i.length,deleted:c,failed:l,deferred:f};return d!==void 0&&(u.oldestLastUsedMs=d),u}function Ux(n){let e,t=!1,r=!1,s=o=>{t||(e=setTimeout(()=>{(async()=>{if(!r){r=!0;try{await jy({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{r=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{s(n.intervalMs)})},o),e.unref())};return s(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function IL(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}er();Id();ot();Id();ve();import*as qx from"fs/promises";var CL=3e3;async function jx(){try{return(await qx.stat(D.config())).mtimeMs}catch{return}}function zx(n){let e=n.intervalMs??CL,t=!1,r,s,o=jx().then(d=>{s=d}),i=async()=>{await o;let d=await jx();if(d===s)return;s=d;let c;try{c=await Da()}catch(f){n.logger?.warn(`config-reload: config.json changed but did not parse (${f.message}); keeping the loaded config`);return}try{n.apply(c)}catch(f){n.logger?.warn(`config-reload: applying live config failed: ${f.message}`)}let l=Wx(n.bootConfig,c);n.onDrift?.(l),n.logger?.info(l.length>0?`config-reload: applied live config; restart-only keys differing from boot: ${l.join(", ")}`:"config-reload: applied live config")},a=()=>{t||(r=setTimeout(()=>{i().finally(a)},e),r.unref?.())};return a(),()=>{t=!0,r&&clearTimeout(r)}}ve();us();import*as Vx from"path";import{createHash as AL,randomBytes as RL,timingSafeEqual as TL}from"crypto";var Jx="hydra_session_",EL=3600*24*30,Kx=12,PL=32,ML=50;function _L(){return Vx.join(D.home(),"session-tokens.json")}function Gx(n){return AL("sha256").update(n).digest("hex")}function Yx(n){return RL(n).toString("hex")}function $L(){return Yx(Kx).slice(0,Kx*2)}function OL(){return`${Jx}${Yx(PL)}`}var Vf=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let r of e)this.records.set(r.hash,r)}static async load(){let e=[],t=_L(),r=await Wt(t);r&&Array.isArray(r.records)&&(e=r.records.filter(FL));let s=new n(e,t);return s.sweepExpired(new Date)>0&&await s.flush(),s}async issue(e={}){let t=OL(),r=Gx(t),s=$L(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:EL,a=new Date(o.getTime()+i*1e3),d={id:s,hash:r,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(r,d),this.scheduleWrite(),{id:s,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Jx))return;let t=Gx(e),r=this.records.get(t);if(!r)return;let s=Buffer.from(r.hash,"hex"),o=Buffer.from(t,"hex");if(s.length!==o.length||!TL(s,o))return;let i=new Date;if(new Date(r.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return r.lastUsedAt=i.toISOString(),this.scheduleWrite(),r.id}async revoke(e){for(let[t,r]of this.records)if(r.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:r,expiresAt:s,lastUsedAt:o})=>({id:e,label:t,createdAt:r,expiresAt:s,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[r,s]of this.records)new Date(s.expiresAt).getTime()<=e.getTime()&&(this.records.delete(r),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},ML))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>mn(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function FL(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}Js();var Qx="Bearer ",Jf=class{constructor(e){this.token=e}token;async validate(e){return LL(e,this.token)?"service":void 0}rotate(e){this.token=e}},Yf=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Qf=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let r=await t.validate(e);if(r!==void 0)return r}}};function Xx(n){return async function(t,r){let s=t.headers.authorization;if(!s||!s.startsWith(Qx)){r.code(401).send({error:"Missing bearer token"});return}let o=s.slice(Qx.length).trim(),i=await n.validator.validate(o);if(!i){r.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function Zx(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let r of t.split(",")){let s=r.trim(),o="hydra-acp-token.";if(s.startsWith(o))return s.slice(o.length)}if(n.url)try{let s=new URL(n.url,"http://localhost").searchParams.get("token");if(s)return s}catch{return}}var Xf=class{tokens=new Map;mint(e,t){let r=Ea();return this.tokens.set(r,{name:e,kind:t}),r}revoke(e){for(let[t,r]of this.tokens)r.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function LL(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r+=1)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var Zf=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),r=this.entries.get(e);if(!r||t-r.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}r.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,r]of this.entries)e-r.windowStart>this.windowMs&&this.entries.delete(t)}};Hc();ve();ot();zy();Oi();rp();import*as Qy from"fs";import*as CC from"os";import*as cp from"path";import*as Xy from"readline";$o();yr();wd();function sp(n,e={}){let t=f1(n),{events:r,window:s}=u1(t,e),o=p1(r),i=[];h1(i,n),s&&(s.from>1||s.to<s.total)&&(i.push(`_Showing turns ${s.from}-${s.to} of ${s.total}._`),i.push("")),m1(i,r,o,{includeTools:e.includeTools??!1,includeThoughts:e.includeThoughts??!1});let a=i.join(`
|
|
376
376
|
`);return a.endsWith(`
|
|
377
377
|
`)||(a+=`
|
|
378
|
-
`),a}function Vy(n,e){let t=n<0?e+n+1:n;return t<1?1:t>e?e:t}function
|
|
379
|
-
`)),n.push("")}function
|
|
380
|
-
`);for(let a=0;a<i.length;a++){let d=i[a];n.push(a===0&&a===i.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===i.length-1?`${d}${t}`:d)}s<r.length-1&&n.push("")}}function
|
|
378
|
+
`),a}function Vy(n,e){let t=n<0?e+n+1:n;return t<1?1:t>e?e:t}function u1(n,e){if(!(e.from!==void 0||e.to!==void 0||e.last!==void 0)&&e.sinceMs===void 0)return{events:n};let r=[],s=0;for(let{event:p}of n)p.kind==="user-text"&&(s+=1),r.push(s===0?1:s);let o=Math.max(s,1),i=1,a=o;if(e.last!==void 0&&e.last>0?i=Vy(o-e.last+1,o):(e.from!==void 0&&(i=Vy(e.from,o)),e.to!==void 0&&(a=Vy(e.to,o))),i>a)return{events:[],window:{from:i,to:a,total:o}};let d=e.sinceMs,c=new Set;d!==void 0&&n.forEach((p,m)=>{p.recordedAt>=d&&c.add(r[m])});let l=[],f,u;return n.forEach((p,m)=>{let h=r[m];h<i||h>a||d!==void 0&&!c.has(h)||(l.push(p),f??=h,u=h)}),{events:l,window:{from:f??i,to:u??a,total:o}}}function f1(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let r=t.params;if(!r||typeof r!="object")continue;let s=Cs(r.update,{cwd:n.session.cwd});s!==null&&e.push({event:s,recordedAt:t.recordedAt})}return e}function p1(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let r=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??r?.status??"pending"});continue}if(t.kind==="tool-call-update"){let r=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??r.title,status:t.status??r.status})}}return e}function h1(n,e){let t=e.session,r=Je(t.sessionId),s=t.title?.trim()||`Hydra session ${r}`;n.push(`# ${hl(s)}`),n.push("");let o=[];o.push(`- **Session:** \`${r}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0||a.cumulativeCost!==void 0)){let d=[];if(a.used!==void 0){let l=a.size!==void 0?`${Jy(a.size)}`:void 0;d.push(l?`${Jy(a.used)} / ${l} tokens`:`${Jy(a.used)} tokens`)}let c=rl(a);if(c!==void 0){let l=a.costCurrency??"USD";d.push(`$${c.toFixed(2)} ${l}`)}o.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(o.join(`
|
|
379
|
+
`)),n.push("")}function m1(n,e,t,r){let{includeTools:s,includeThoughts:o}=r;if(!e.some(h=>g1(h.event,o))){n.push("_No conversation history recorded._"),n.push("");return}let i=0,a="",d="",c=[],l=new Set,f=!1,u=()=>{if(c.length!==0){for(let h of c)n.push(h);n.push(""),c=[]}},p=()=>{u(),d.length>0&&(pC(n,d.trimEnd(),"*"),n.push(""),d=""),a.length!==0&&(n.push(a.trimEnd()),n.push(""),a="")},m=()=>{f||(f=!0)};for(let{event:h}of e)switch(h.kind){case"user-text":{p(),n.push("---"),n.push(""),i+=1,pC(n,h.text,"**"),n.push(""),f=!0;break}case"agent-text":m(),a+=h.text;break;case"agent-thought":{if(!o)break;m(),a.length>0&&(n.push(a.trimEnd()),n.push(""),a=""),d+=h.text;break}case"tool-call":{if(!s||(m(),(a.length>0||d.length>0)&&p(),l.has(h.toolCallId)))break;l.add(h.toolCallId);let y=t.get(h.toolCallId)??{title:h.title,status:h.status??"pending"};c.push(`- ${w1(y.status)} ${y1(y)}`);break}case"tool-call-update":break;case"plan":{m(),p(),n.push("**Plan:**"),n.push("");for(let y of h.entries){let w=y.status==="completed"?"[x]":"[ ]";n.push(`- ${w} ${hl(y.content)}`)}n.push("");break}case"mode-changed":m(),p(),n.push(`_mode: ${hl(h.mode)}_`),n.push("");break;case"model-changed":m(),p(),n.push(`_model: ${hl(h.model)}_`),n.push("");break;case"turn-complete":p();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}p()}function g1(n,e){switch(n.kind){case"agent-thought":return e;case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function y1(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${hl(n.title)}${t}`}function w1(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}var hC=String.raw`<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>`,b1=new RegExp(hC);function pC(n,e,t){if(b1.test(e)){k1(n,e);return}let r=e.split(/\n\s*\n/);for(let s=0;s<r.length;s++){let o=r[s];if(o.trim().length===0)continue;let i=o.split(`
|
|
380
|
+
`);for(let a=0;a<i.length;a++){let d=i[a];n.push(a===0&&a===i.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===i.length-1?`${d}${t}`:d)}s<r.length-1&&n.push("")}}function k1(n,e){let t=e.replace(/\s+$/,"");if(t.length===0)return;let r=0;for(let o of t.match(/`+/g)??[])r=Math.max(r,o.length);let s="`".repeat(Math.max(3,r+1));n.push(s);for(let o of t.split(`
|
|
381
381
|
`))n.push(o);n.push(s)}function hl(n){return n.replace(new RegExp(hC,"g"),e=>e.replace(/</g,"<").replace(/>/g,">"))}function Jy(n){return n.toLocaleString("en-US")}rn();er();xc();ap();_a();import{randomBytes as IC}from"crypto";function SC(n){let e=IC(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Yy(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async r=>{let s=[...n.baselineMcpServers??[]];n.stdinEnabled&&s.push(SC({name:"hydra-acp-stdin",session:r,tokenRegistry:e,getOrigin:t})),s.push(SC({name:"hydra-acp-recall",session:r,tokenRegistry:e,getOrigin:t}));let o=Rd(n.deps);return o!==void 0&&(o.bindToSession(r),s=[...s,...o.descriptors]),s}}function Rd(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=IC(32).toString("hex"),r=n.mcpTokenRegistry.reserve(t),s=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${s}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{r.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>r.abandon(a)}}var dp=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function xC(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!mi(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function AC(n,e,t,r={}){n.get("/v1/sessions",async c=>{let l=c.query,f=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true",u=l?.status==="warm"||l?.status==="cold"?l.status:void 0;return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:f,...u?{status:u}:{}})}}),n.get("/v1/sessions/:id",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.getOne(u);return p||(l.code(404).send({error:"session not found"}),l)}),n.post("/v1/sessions/search",async(c,l)=>{let f=c.body??{},u=typeof f.q=="string"?f.q:"";if(u.trim().length===0)return l.code(400).send({error:"q is required"}),l;let m={sessionIds:Array.isArray(f.sessionIds)?f.sessionIds.filter(y=>typeof y=="string"&&y.length>0):void 0};return typeof f.snippetWidth=="number"&&(m.snippetWidth=f.snippetWidth),await vC(e,u,m)}),n.post("/v1/sessions",async(c,l)=>{let f=c.body??{},u=mt(f.cwd??t.cwd),p=await Ma(u),m=f.agentId??p.agentId??t.agentId,h=Rd(r),y=h!==void 0?[...f.mcpServers??[],...h.descriptors]:f.mcpServers;try{let w=await e.create({cwd:u,agentId:m,mcpServers:y,...f.workspace!==void 0?{workspace:f.workspace}:{}});h!==void 0&&h.bindToSession(w),l.code(201).send({sessionId:w.sessionId,agentId:w.agentId,cwd:w.cwd,...w.workspace!==void 0?{workspace:w.workspace}:{},...w.workspaceError!==void 0?{workspaceError:w.workspaceError}:{}})}catch(w){h!==void 0&&h.abandon(w instanceof Error?w:void 0),l.code(500).send({error:w.message})}}),n.post("/v1/sessions/collect",async(c,l)=>{let f=c.body??{},u=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,p=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,m=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let h=await jy({manager:e,maxAgeMs:u,maxDeletions:p,selection:m,verbose:!1});l.code(200).send(h)}catch(h){l.code(500).send({error:h.message})}}),n.post("/v1/sessions/:id/kill",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){p.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let m=c.body??{},h={};(m.mode==="memory"||m.mode==="file")&&(h.mode=m.mode),typeof m.capacityBytes=="number"&&(h.capacityBytes=m.capacityBytes),typeof m.fileCapBytes=="number"&&(h.fileCapBytes=m.fileCapBytes),(h.mode??"memory")==="file"&&(h.filePathFor=y=>cp.join(CC.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(h)}catch(y){return l.code(409).send({error:y.message}),l}}),n.post("/v1/sessions/:id/stdin",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(!p)return l.code(404).send({error:"session not found"}),l;let m=c.body??{},h=typeof m.chunk=="string"?m.chunk:"",y=m.eof===!0;try{return p.streamWrite(h,y)}catch(w){return l.code(409).send({error:w.message}),l}}),n.patch("/v1/sessions/:id",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.body??{};if(p.cwd!==void 0){if(typeof p.cwd!="string"||!cp.isAbsolute(p.cwd)){l.code(400).send({error:"cwd must be an absolute path"});return}let h=await e.setCwd(u,p.cwd);if(h==="missing"){l.code(404).send({error:"session not found"});return}if(h==="not-a-directory"){l.code(400).send({error:`${p.cwd} is not a directory`});return}if(h==="live"){l.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(h==="bound"){l.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}l.code(204).send();return}if("workspace"in p){if(p.workspace!==null){l.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let h=await e.clearWorkspaceBinding(u);if(h==="missing"){l.code(404).send({error:"session not found"});return}if(h==="live"){l.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}l.code(204).send();return}if(p.priority!==void 0){let h=p.priority,y;if(h===null||h===0)y=void 0;else if(typeof h=="number"&&Number.isInteger(h)&&h>0)y=h;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(u,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(u)!==void 0||await e.hasRecord(u))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(u),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(u,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.delete("/v1/sessions/:id",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);if(p){await p.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(u),await e.hasRecord(u)&&await e.deleteRecord(u),l.code(204).send();return}if(!await e.deleteRecord(u)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.get("/v1/sessions/:id/export",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.query?.tools,m=p==="references"?"references":Sx(p),h=await e.exportBundle(u,m==="references"?{tools:"references"}:{});if(!h){l.code(404).send({error:"session not found"});return}let y=nl({record:h.record,history:m==="summary"?Ix(h.history,"summary"):h.history,promptHistory:h.promptHistory.length>0?h.promptHistory:void 0,...h.toolBlobs!==void 0?{toolBlobs:h.toolBlobs}:{},hydraVersion:He,machine:To(),hydraHost:xC(t)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${u}-${w}.hydra"`),l.code(200).send(y)}),n.get("/v1/sessions/:id/diff",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let m=c.query??{},h=m.fold==="true"||m.fold==="1",y=typeof m.paths=="string"&&m.paths.length>0?new Set(m.paths.split(",").map(k=>k.trim()).filter(k=>k.length>0)):void 0,w=xd(p.history);y&&(w=w.filter(k=>y.has(k.path))),h&&(w=w.map(k=>({...k,hunks:Cd(k.hunks)}))),l.code(200).send(w)}),n.get("/v1/sessions/:id/tools/:hash",async(c,l)=>{let f=c.params,u=await e.resolveCanonicalId(f.id)??f.id,p=await e.loadToolBlob(u,f.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),n.get("/v1/sessions/:id/transcript",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=await e.exportBundle(u);if(!p){l.code(404).send({error:"session not found"});return}let m=nl({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:He,machine:To(),hydraHost:xC(t)}),h=c.query,y=b=>b==="1"||b==="true"||b==="yes",w=b=>{let S=h?.[b];if(S===void 0||S==="")return;let C=Number(S);return Number.isFinite(C)?C:"bad"},k={};for(let b of["from","to","last","since"]){let S=w(b);if(S==="bad"){l.code(400).send({error:`${b} must be a number`});return}S!==void 0&&(k[b==="since"?"sinceMs":b]=S)}l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(sp(m,{includeTools:y(h?.tools),includeThoughts:y(h?.thoughts),...k}))}),n.post("/v1/sessions/:id/fork",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.body??{},m={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}m.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}m.cwd=mt(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}m.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}m.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}m.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}m.model=p.model}try{let h=await e.forkSession(u,m);l.code(201).send(h)}catch(h){let y=h;if(y.code===G.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===G.InvalidParams||y.code===G.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.post("/v1/sessions/import",async(c,l)=>{let f=c.body??{};if(f.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let u;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}u=f.cwd}let p;try{p=zr(f.bundle)}catch(m){l.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(p,{replace:f.replace===!0,...u!==void 0?{cwd:u}:{}});l.code(201).send(m)}catch(m){let h=m;if(h.code===G.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:h.existingSessionId});return}l.code(500).send({error:h.message})}}),n.get("/v1/sessions/:id/compact/status",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u),m;if(p?m=p.summarizedThroughEntry:m=await e.getSummarizedThroughEntry(u),m===void 0&&!await e.hasRecord(u))return l.code(404).send({error:"session not found"}),l;let h=await e.getCompactionState(u),y=await e.getRollbackBreadcrumb(u),w=await e.getPendingAgentSwap(u),k=!1,b,S=p?.currentUsage,C=typeof S?.used=="number"&&typeof S?.size=="number"&&S.size>0?{used:S.used,size:S.size}:void 0,I=await e.loadHistory(u,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(I.length>0&&t.compaction){let T=m??0,O=I.length,E=T<=I.length?T:0,$=I.slice(E),F=eC($);b=qy(F);let q=p?.currentModel,z=I.at(-1).recordedAt;k=tC({summarizedThroughEntry:T,totalEntries:O,unsummarizedChars:F,compactionInFlight:e.getCompactionInFlight(),currentModel:q,lastActivityMs:z,nowMs:Date.now(),config:t.compaction,...typeof S?.used=="number"?{agentReportedUsed:S.used}:{},...typeof S?.size=="number"?{agentReportedSize:S.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:k,...b!=null?{approxTokens:b}:{},...C!=null?{currentUsage:C}:{},...h!=null?{compactionState:h}:{},...y!=null?{rollbackBreadcrumb:y}:{},...w!=null?{pendingAgentSwap:w}:{}}}),n.post("/v1/sessions/:id/compact",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f;if(e.get(u)){e.scheduleCompaction(u),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(u),l.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(u),l.code(202).send({rolledBack:!0})}catch(p){let m=p instanceof Error?p.message:String(p);l.code(409).send({error:m})}}),n.post("/v1/sessions/:id/workspace/clean",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=c.body??{};if(p.deep!==void 0&&typeof p.deep!="boolean"){l.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}if(e.get(u)===void 0){l.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let m=await e.runWorkspaceAction(u,"clean",void 0,{deep:p.deep===!0});l.code(202).send({report:m})}catch(m){l.code(409).send({error:m instanceof Error?m.message:String(m)})}}),n.get("/v1/sessions/:id/history",async(c,l)=>{let f=c.params.id,u=c.query,p=u?.follow==="1"||u?.follow==="true",m=await e.resolveCanonicalId(f)??f,h=e.get(m),y,w,k=!1,b=1e4,S=[];if(h){p&&(w=h.onBroadcast(I=>{l.raw.writableEnded||(k?l.raw.write(JSON.stringify(I)+`
|
|
382
382
|
`):(S.push(I),S.length>b&&S.shift()))})),c.raw.on("close",()=>{w?.(),l.raw.writableEnded||l.raw.end()});try{y=await h.getHistorySnapshot()}catch(I){throw w?.(),I}}else{let I=await e.getHistory(m);if(I===void 0)return l.code(404).send({error:"session not found"}),l;y=I}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let C=new Set;for(let I of y??[]){l.raw.write(JSON.stringify(I)+`
|
|
383
383
|
`);let T=I;typeof T.recordedAt=="number"&&C.add(String(T.recordedAt))}for(;S.length>0;){let I=S.splice(0,S.length);for(let T of I){let O=T,E=typeof O.recordedAt=="number"?String(O.recordedAt):"";E&&C.has(E)||l.raw.write(JSON.stringify(T)+`
|
|
384
384
|
`)}}return k=!0,w||l.raw.end(),l});function s(c,l,f){let u=typeof c=="string"?c.trim():"";if(u.length===0)return null;let p;try{p=JSON.parse(u)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let m=p;if(typeof m.recordedAt!="number"||f!==void 0&&m.recordedAt<f||typeof m.params!="object"||m.params===null||Array.isArray(m.params))return null;let h=m.params;if(typeof h.update!="object"||h.update===null||Array.isArray(h.update))return null;let w=h.update.sessionUpdate;return typeof w!="string"||!l.has(w)?null:{recordedAt:m.recordedAt,entry:p}}function o(c,l,f){let p=l.params.update,m={sessionId:c,ts:new Date(l.recordedAt).toISOString(),kind:f,update:p};return p.messageId!==void 0&&p.messageId!==null&&(m.messageId=p.messageId),m}async function*i(c,l,f,u){for await(let p of l){let m=s(p,f,u);if(m){let h=m.entry.params.update.sessionUpdate;yield{ts:m.recordedAt,row:o(c,m.entry,h)}}}}async function a(c,l,f,u){let p=Xy.createInterface({input:Qy.createReadStream(l),crlfDelay:1/0}),m=i(c,p,f,u),h=await m.next(),y=h.done?null:h.value;return{sessionId:c,rl:p,gen:m,current:y,exhausted:y===null}}async function d(c){let l=await c.gen.next();l.done?(c.exhausted=!0,c.current=null):c.current=l.value}n.get("/v1/sessions/events",async(c,l)=>{let f=c.query,u=f.kinds;if(!u||u.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=u.split(",").map(b=>b.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let b of p)if(!dp.has(b))return l.code(400).send({error:`kind "${b}" is not queryable; allowed kinds: ${[...dp].join(", ")}`}),l;let m=new Set(p),h;if(f.since!==void 0&&f.since.trim().length>0){let b=new Date(f.since);if(isNaN(b.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;h=b.getTime()}let y=await e.list({includeNonInteractive:!0}),w=h!==void 0?y.filter(b=>new Date(b.updatedAt).getTime()>=h):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let k=[];for(let b of w)try{let S=D.historyFile(b.sessionId),C=await a(b.sessionId,S,m,h);C.exhausted||k.push(C)}catch(S){if(S.code==="ENOENT")continue;throw S}c.raw.on("close",()=>{for(let b of k)try{b.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;k.length>0;){let b=-1,S=1/0;for(let I=0;I<k.length;I++){let T=k[I];T.current!==null&&T.current.ts<S&&(S=T.current.ts,b=I)}if(b===-1)break;let C=k[b];if(l.raw.write(JSON.stringify(C.current.row)+`
|
|
385
385
|
`),await d(C),C.exhausted){try{C.rl.close()}catch{}k.splice(b,1)}}}catch(b){for(let S of k)try{S.rl.close()}catch{}throw b}return l.raw.end(),l}),n.get("/v1/sessions/:id/events",async(c,l)=>{let f=c.params.id,u=c.query,p=await e.resolveCanonicalId(f)??f;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let h=u.kinds;if(!h||h.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=h.split(",").map(I=>I.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let I of y)if(!dp.has(I))return l.code(400).send({error:`kind "${I}" is not queryable; allowed kinds: ${[...dp].join(", ")}`}),l;let w=new Set(y),k;if(u.since!==void 0&&u.since.trim().length>0){let I=new Date(u.since);if(isNaN(I.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;k=I.getTime()}let b=D.historyFile(p),S=Qy.createReadStream(b),C=Xy.createInterface({input:S,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let I of C){let T=typeof I=="string"?I.trim():"";if(T.length===0)continue;let O;try{O=JSON.parse(T)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",b);continue}if(!O||typeof O!="object"||Array.isArray(O)){console.debug("events endpoint: skipping non-object JSONL line in %s",b);continue}let E=O;if(typeof E.recordedAt!="number"||typeof E.params!="object"||E.params===null||Array.isArray(E.params))continue;let $=E.params;if(typeof $.update!="object"||$.update===null||Array.isArray($.update))continue;let F=$.update,q=F.sessionUpdate;if(typeof q!="string"||!w.has(q)||k!==void 0&&E.recordedAt<k)continue;let z={ts:new Date(E.recordedAt).toISOString(),kind:q,update:F};F.messageId!==void 0&&F.messageId!==null&&(z.messageId=F.messageId),l.raw.write(JSON.stringify(z)+`
|
|
386
|
-
`)}}catch(I){if(I.code==="ENOENT")return l.raw.end(),l;throw I}return l.raw.end(),l}),n.post("/v1/sessions/:id/prompt/:messageId/notify",async(c,l)=>{let f=c.params,u=f.id,p=await e.resolveCanonicalId(u)??u,m=f.messageId,h=c.body,y=typeof h?.callbackUrl=="string"?h.callbackUrl:"",w=typeof h?.secret=="string"?h.secret:"";if(!m||!y||!w){l.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let k;try{k=new URL(y)}catch{l.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(k.protocol!=="https:"&&k.protocol!=="http:"){l.code(400).send({error:"callbackUrl must be http or https"});return}let b=e.get(p);if(!b){l.code(404).send({error:"session not found or not warm"});return}let S=b.registerTurnNotify(m,y,w);if(S.alreadyTerminal){l.code(200).send({status:"already_terminal",stopReason:S.stopReason});return}l.code(202).send({status:"registered"})}),n.get("/v1/sessions/:id/attention",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);return!p&&!await e.hasRecord(u)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(u))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(c,l)=>{let f=c.query;if(!f.source||f.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let u=await e.list({includeNonInteractive:!0}),p=[];for(let m of u){let h=e.get(m.sessionId),y;h?y=h.listAttentionFlags():y=(await e.store.read(m.sessionId))?.attentionFlags??[];for(let w of y)w.source===f.source&&p.push({...w,sessionId:m.sessionId})}return{flags:p}}),n.post("/v1/sessions/:id/attention/clear",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,m=c.body??{},h=typeof m.source=="string"?m.source:"",y=typeof m.reason=="string"?m.reason:"";if((h.length>0||y.length>0)&&!(h.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}h.length===0&&y.length;let w=e.get(u);if(w){if(h.length>0&&y.length>0)w.clearAttentionFlag(h,y);else{let I=Array.from(w.listAttentionFlags()).map(T=>`${T.source}::${T.reason}`);for(let T of I)w.clearAttentionFlag(T.split("::")[0],T.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}let k=e.store,b=await k.read(u);if(!b){l.code(404).send({error:"session not found"});return}let S=b.attentionFlags??[],C;if(h.length>0&&y.length>0){let I=`${h}::${y}`;C=S.filter(T=>`${T.source}::${T.reason}`!==I)}else C=[];if(C.length===S.length&&C.every((I,T)=>I.source===S[T].source&&I.reason===S[T].reason)){l.code(204).send();return}await k.write({...b,attentionFlags:C}),l.code(204).send()})}ws();rn();function RC(n,e,t,r={}){n.get("/v1/agents",async()=>od(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let s=await e.refresh();return{version:s.version,agentCount:s.agents.length}}),n.post("/v1/agents/:id/install",async(s,o)=>{let i=s.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await gr(a,[],{npmRegistry:r.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(s,o)=>{let i=s.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===G.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}ve();function TC(n,e,t,r=()=>[]){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:D.home(),driftedKeys:r()}))}var
|
|
387
|
-
`;await Oo.mkdir(D.home(),{recursive:!0}),await Oo.writeFile(Zy(),r,{encoding:"utf8",mode:384})}async function up(){try{return(await Oo.readFile(Zy(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function fp(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await Oo.readFile(Zy(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await LC(n,i,a.length,{N:r,r:s,p:o,maxmem:NC});return d.length!==a.length?!1:WL(d,a)}var KL=Fo.object({password:Fo.string().min(1),label:Fo.string().min(1).max(256).optional(),ttlSec:Fo.number().int().positive().optional()}),GL=Fo.object({id:Fo.string().optional()}).optional(),VL=Fo.object({token:Fo.string().min(32)});function DC(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,r)=>{let s=JL(t);if(e.rateLimiter.isBlocked(s))return r.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=KL.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}if(!await up())return r.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await fp(o.password))return e.rateLimiter.recordFailure(s),r.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(s);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return r.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,r)=>{let s;try{s=GL.parse(t.body??void 0)}catch{return r.code(400).send({error:"Invalid request body"})}let o=s?.id??t.authIdentity;if(!o||o==="service")return r.code(200).send({revoked:!1});let i=await e.store.revoke(o);return r.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,r)=>r.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,r)=>r.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions",async(t,r)=>{let s=await e.store.revokeAll();return r.code(200).send({revoked:s})}),n.delete("/v1/auth/sessions/:id",async(t,r)=>{let s=t.params.id;return await e.store.revoke(s)?r.code(204).send():r.code(404).send({error:"Not found"})}),n.post("/v1/auth/rotate-token",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=VL.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(s.token),r.code(200).send({rotated:!0})})}function JL(n){return n.ip||"unknown"}Ri();wd();Td();import{nanoid as ew}from"nanoid";lf();rn();ws();_a();er();import{randomBytes as qC}from"crypto";import*as zC from"os";import*as KC from"path";id();var YL=200;function QL(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[vt];if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.sentBy;if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o={};if(typeof s.sessionId=="string"&&s.sessionId.length>0&&(o.sessionId=s.sessionId),typeof s.label=="string"&&s.label.length>0&&(o.label=s.label.slice(0,YL)),s.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function HC(n,e,t){let r=QL(n);if(!r)return;let s={};if(r.label!==void 0&&(s.fromLabel=r.label),r.awaiting===!0&&(s.awaiting=!0),r.sessionId!==void 0){let o=await e.resolveCanonicalId(r.sessionId)??r.sessionId,i=await e.getOne(o);if(i){s.fromSession=o,i.title&&(s.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;s.depth=(a??0)+1}else t?.(r.sessionId)}if(!(s.fromSession===void 0&&s.fromLabel===void 0))return s}var gl=new Map;function UC(n,e){let t=gl.get(n);t||(t=new Set,gl.set(n,t)),t.add(e);let r=!1;return()=>{if(r)return;r=!0;let s=gl.get(n);s&&(s.delete(e),s.size===0&&gl.delete(n))}}function WC(n,e){if(n===e)return!0;let t=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(t.has(s))continue;t.add(s);let o=gl.get(s);if(o){if(o.has(n))return!0;for(let i of o)r.push(i)}}return!1}function le(n,e,t){let r=new Error(e);return r.code=n,t!==void 0&&(r.data=t),r}function nN(n){if(!n||typeof n!="object")return 512;let r=n.params?.update;if(!r)return 512;let s=512,o=r.content;if(typeof o=="string")s+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(s+=a.text.length),typeof a.data=="string"&&(s+=a.data.length)}let i=r.toolCall;if(i&&(typeof i.rawInput=="string"?s+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(s+=256),typeof i.rawOutput=="string"?s+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(s+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(s+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(s+=c.text.length)}}return s}function tr(n,e,t){let r=n.get(e);if(!r)throw le(G.SessionNotFound,t??`session ${e} not found`);return r}async function Bi(n,e){let t=Rd(n),r,s,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(r=qC(32).toString("hex"),s=n.mcpTokenRegistry.reserve(r),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${r}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=Yy({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),s!==void 0&&s.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(c),r!==void 0&&s!==void 0&&n.mcpTokenRegistry!==void 0){let l=r,f=n.mcpTokenRegistry;s.complete(c),c.onClose(()=>{f.unbind(l)})}return fN(c,n),VC(c.sessionId,n),c}function GC(n,e){n.get("/acp",{websocket:!0},async(t,r)=>{let s=Zx({headers:r.headers,url:r.url});if(!s||!await e.validator.validate(s)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(s),i=As(t),a=new jn(i),d={clientId:`hydra_client_${ew(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let c=(f,u)=>{if(d.attached.get(f)?.readonly)throw le(G.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=FS.parse(f??{});u.clientInfo?.name&&(d.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p)),uN()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},m=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.verb!="string")return;let w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(h=>h!==void 0):[];return f.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let m=p??{},h=typeof m.instructions=="string"?m.instructions:void 0,y=Array.isArray(m.tools)?m.tools.map(w=>{if(!w||typeof w!="object")return;let k=w;if(typeof k.name!="string"||k.name.length===0||typeof k.description!="string"||k.inputSchema===null||typeof k.inputSchema!="object")return;let b={name:k.name,description:k.description,inputSchema:k.inputSchema};return k.outputSchema!==null&&typeof k.outputSchema=="object"&&(b.outputSchema=k.outputSchema),b}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,h,y),{ok:!0,registered:y.length}});let u=p=>{let m=p??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw le(G.InvalidParams,"sessionId is required");return m.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let m=u(p),h=p??{};if(typeof h.key!="string"||h.key.length===0)throw le(G.InvalidParams,"key is required");if(!e.manager)throw le(G.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(m,o.name,h.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let m=u(p);if(!e.manager)throw le(G.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(m,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let m=u(p),h=p??{};if(typeof h.key!="string"||h.key.length===0)throw le(G.InvalidParams,"key is required");if(h.value===void 0)throw le(G.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw le(G.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(m,o.name,h.key,h.value)}catch(y){throw le(G.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let m=u(p),h=p??{};if(typeof h.key!="string"||h.key.length===0)throw le(G.InvalidParams,"key is required");if(!e.manager)throw le(G.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(m,o.name,h.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async m=>{let h=m??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw le(G.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(h.sessionId,o.name),{ok:!0}})}a.onClose(()=>{f.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async u=>{let p=u??{},m=Array.isArray(p.intercepts)?p.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,m),e.manager?.defaultTransformers.includes(o.name))){let h=e.transformers.resolveChain([o.name])[0];if(h)for(let y of e.manager.liveSessions())y.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let p=u??{},m=typeof p.sessionId=="string"?p.sessionId:void 0,h=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!m)throw le(-32602,"emit_message requires sessionId");if(!h&&w!=="client_broadcast")throw le(-32602,"emit_message requires method");let k=tr(e.manager,m),b=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(b)return k.dischargeClaim(b,y),{ok:!0};if(w==="chain")return{ok:!0,response:await k.emitToChain(o.name,h,y)};if(w==="queue"){if(h!=="session/prompt")throw le(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await k.emitToQueue(o.name,y)}}if(w==="daemon")return{ok:!0,response:await k.emitToChain(o.name,h,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw le(-32602,"client_broadcast requires an envelope object");return k.broadcastClientUpdate(y),{ok:!0}}throw le(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let p=u??{},m=typeof p.sessionId=="string"?p.sessionId:void 0;if(!m)throw le(-32602,"hydra-acp/session/request_permission requires sessionId");return tr(e.manager,m).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async u=>aN(u,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let p=u??{},m=typeof p.agentId=="string"?p.agentId:void 0,h=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,k=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,b=k&&typeof k.title=="string"?k.title:void 0,S=k&&typeof k.model=="string"?k.model:void 0;if(!h&&y){let q=e.manager.get(y);q&&(h=q.cwd)}if(!h)throw le(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let C=await Ma(h),I=m??C.agentId??e.defaultAgent,T=await e.registry?.getAgent(I),O=mr(C.models,T??{id:I})?.value,E=S??O,$=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:I,cwd:h,parentSessionId:y,interactive:$,transformChain:[],title:b,model:E})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw le(G.InvalidParams,"fork_session requires sessionId");let m=typeof p.forkAt=="string"?p.forkAt:void 0,h=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,k=typeof p.model=="string"&&p.model.length>0?p.model:void 0,b=await e.manager.forkSession(p.sessionId,{...m!==void 0?{forkAt:m}:{},...h!==void 0?{cwd:h}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...k!==void 0?{model:k}:{}}),S=e.manager.get(b.sessionId);if(!S){let T=await e.manager.loadFromDisk(b.sessionId);if(!T)throw le(G.InternalError,`fork ${b.sessionId} vanished before it could be attached`);S=await Bi(e,{...T,onInstallProgress:pp(a)})}Ed(d,S,S.sessionId);let C=Lo(a,S,d),{entries:I}=await S.attach(C,"full");d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:C.clientId,readonly:!1});for(let T of I){if(a.isClosed())break;await a.notify(T.method,bs(T.params,T.recordedAt)).catch(()=>{})}return{...b,sessionId:S.sessionId}}),a.onRequest("session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw le(G.InvalidParams,"session/fork requires sessionId");let m=typeof p.cwd=="string"?p.cwd:void 0,h=await e.manager.forkSession(p.sessionId,{...m!==void 0?{cwd:m}:{},mode:"verbatim"}),y=e.manager.get(h.sessionId);if(!y){let b=await e.manager.loadFromDisk(h.sessionId);if(!b)throw le(G.InternalError,`fork ${h.sessionId} vanished before it could be attached`);y=await Bi(e,{...b,onInstallProgress:pp(a)})}Ed(d,y,y.sessionId);let w=Lo(a,y,d),{entries:k}=await y.attach(w,"full");d.attached.set(y.sessionId,{sessionId:y.sessionId,clientId:w.clientId,readonly:!1});for(let b of k){if(a.isClosed())break;await a.notify(b.method,bs(b.params,b.recordedAt)).catch(()=>{})}return{sessionId:y.sessionId}});let f=async(u,p)=>{let m=u??{};if(typeof m.sessionId!="string")throw le(G.InvalidParams,`${p} requires sessionId`);let h=await e.manager.resolveCanonicalId(m.sessionId)??m.sessionId,y=e.manager.get(h);if(y)return await y.close({deleteRecord:!0,by:`session/delete ${d.clientId}`}),await e.manager.waitForDeletion(h),await e.manager.hasRecord(h)&&await e.manager.deleteRecord(h),{id:h,existed:!0};let w=await e.manager.deleteRecord(h);return{id:h,existed:w}};a.onRequest("session/delete",async u=>(await f(u,"session/delete"),{})),a.onRequest("session/close",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw le(G.InvalidParams,"session/close requires sessionId");c(p.sessionId,"session/close");let m=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,h=e.manager.get(m);if(h)return await h.close({deleteRecord:!1,by:`session/close ${d.clientId}`+(d.processIdentity?` (${d.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(m))return{};throw le(G.SessionNotFound,`session ${m} not found`)}),a.onRequest("hydra-acp/session/delete",async u=>{let{id:p,existed:m}=await f(u,"hydra-acp/session/delete");if(!m)throw le(G.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let p=u??{},m=typeof p.childSessionId=="string"?p.childSessionId:void 0,h=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!m)throw le(-32602,"await_child requires childSessionId");let w=tr(e.manager,m,`child session ${m} not found`);return new Promise(k=>{let C=[],I=[],T=0,O=!1,E,$,F=!1,q=()=>{F||(F=!0,clearTimeout(z),E?.(),$?.(),k(O?{entries:C,truncated:!0}:{entries:C}))};E=w.onBroadcast(X=>{let oe=nN(X);for(C.push(X),I.push(oe),T+=oe;C.length>0&&(C.length>1e3||T>1048576);)C.shift(),T-=I.shift()??0,O=!0;h==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&q()});let z=setTimeout(q,y);typeof z.unref=="function"&&z.unref(),$=w.onClose(()=>q())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let p=u??{},m=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!m)throw le(-32602,"close_child_session requires childSessionId");let h=e.manager.get(m);return h&&await h.close({deleteRecord:!1,by:`child_session/close ${d.clientId}`}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>dN(u,o.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>cN(u,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let p=u??{},m=typeof p.token=="string"?p.token:void 0,h=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return m&&h&&e.manager.get(h)?.keepAliveClaim(m,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw le(G.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=await e.manager.loadToolBlob(p,u.hash);if(m===null)throw le(G.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>rN(f,e)),a.onRequest("logout",async f=>sN(f,e)),a.onRequest("session/new",async f=>{let u=LS.parse(f),p=_n(f?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(ae=>typeof ae=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(m)??[],y=await Ma(u.cwd),w=p.agentId??y.agentId??e.defaultAgent,k=await e.registry?.getAgent(w),b=mr(y.models,k??{id:w})?.value,S,C,I=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){S=qC(32).toString("hex"),C=e.mcpTokenRegistry.reserve(S);let Ce={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${S}`}]};I=[...u.mcpServers??[],Ce]}let T,O,E=Rd(e);E!==void 0&&(I=[...I??[],...E.descriptors]);let $=Yy({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),F;try{F=await e.manager.create({cwd:u.cwd,agentId:w,mcpServers:I,title:p.title,agentArgs:p.agentArgs,model:p.model??b,onInstallProgress:pp(a),transformChain:h,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...p.workspace!==void 0?{workspace:p.workspace}:{},...$?{mintMcpServersForSwap:$}:{}})}catch(ae){throw C!==void 0&&C.abandon(ae instanceof Error?ae:void 0),O!==void 0&&O.abandon(ae instanceof Error?ae:void 0),E!==void 0&&E.abandon(ae instanceof Error?ae:void 0),ae}if(S!==void 0&&C!==void 0&&e.mcpTokenRegistry!==void 0){let ae=S,Ce=e.mcpTokenRegistry;C.complete(F),F.onClose(()=>{Ce.unbind(ae)})}if(T!==void 0&&O!==void 0&&e.mcpTokenRegistry!==void 0){let ae=T,Ce=e.mcpTokenRegistry;O.complete(F),F.onClose(()=>{Ce.unbind(ae)})}E!==void 0&&E.bindToSession(F),VC(F.sessionId,e);let q,z;try{Ed(d,F,F.sessionId),q=Lo(a,F,d),{entries:z}=await F.attach(q,"full")}catch(ae){throw await F.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),ae}d.attached.set(F.sessionId,{sessionId:F.sessionId,clientId:q.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let ae of z){if(a.isClosed())break;await a.notify(ae.method,bs(ae.params,ae.recordedAt)).catch(()=>{})}})()});let X=hp(F),oe=mp(F);return{sessionId:F.sessionId,...X?{modes:X}:{},...oe?{models:oe}:{},configOptions:F.buildConfigOptions(),_meta:gp(e.manager,F,{clientId:q.clientId})}}),a.onRequest("session/attach",async f=>{let u=BS.parse(f),p=u.clientInfo?.version;p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p));let m=_n(u._meta),h=m.resume,y=m.readonly===!0,w=m.env;n.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${y}`);let k=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,b=e.manager.get(k);if(!b&&y){let F=await e.manager.loadFromDisk(k);if(!F)throw le(G.SessionNotFound,`session ${u.sessionId} not found`);let q=await e.manager.loadHistory(k),z=u.clientId??`cli_${ew(8)}`;d.attached.set(F.hydraSessionId,{sessionId:F.hydraSessionId,clientId:z,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${F.hydraSessionId} clientId=${z} attachedCount=${d.attached.size} replayed=${q.length}`);for(let X of q)await a.notify(X.method,bs(X.params,X.recordedAt)).catch(()=>{});return{sessionId:F.hydraSessionId,clientId:z,connectedClients:[z],historyPolicy:"full",replayed:q.length,_meta:lN(F)}}let S=!b;if(!b){let F=await e.manager.loadFromDisk(k),q=await oN(k,h,F?.upstreamSessionId,e.manager);q.kind==="ignore"&&n.log.warn(q.logMessage);let z=F;if(h&&q.kind==="honor"&&(z={...F,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:F?.workspace?.path??h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!z)throw le(G.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(z.agentId,z.upstreamSessionId))throw le(G.SessionNotFound,`session ${u.sessionId} was deleted`);let X=z.originatingClient?z:{...z,originatingClient:d.clientInfo},oe=w!==void 0?{...X,forwardedEnv:w}:X;b=await Bi(e,{...oe,onInstallProgress:pp(a)})}Ed(d,b,b.sessionId);let C=Lo(a,b,d,u.clientInfo,u.clientId),I=m.replayMode==="drip",{entries:T,appliedPolicy:O}=await b.attach(C,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:I,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:C.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(b.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${b.sessionId} clientId=${C.clientId} attachedCount=${d.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${O} replayed=${T.length} readonly=${y}${I?" replayMode=drip":""}`),I){let F=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,q=750;(async()=>{let z=null;for(let X of T){let oe=typeof X.recordedAt=="number"?X.recordedAt:null;if(z!==null&&oe!==null){let ae=Math.min(q,Math.max(0,(oe-z)/F));ae>0&&await new Promise(Ce=>setTimeout(Ce,ae))}oe!==null&&(z=oe);try{await a.notify(X.method,bs(X.params,oe??void 0))}catch{return}}})()}else for(let F=0;F<T.length&&!a.isClosed();F++){let q=T[F],z=a.notify(q.method,bs(q.params,q.recordedAt)).catch(()=>{});(F+1)%200===0&&await z}b.replayPendingPermissions(C);let E=hp(b),$=mp(b);return{sessionId:b.sessionId,clientId:C.clientId,connectedClients:b.connectedClients(C.clientId),historyPolicy:O,replayed:T.length,...E?{modes:E}:{},...$?{models:$}:{},configOptions:b.buildConfigOptions(),_meta:gp(e.manager,b,{resurrected:S})}}),a.onRequest("session/detach",async f=>{let u=DS.parse(f),p=d.attached.get(u.sessionId);if(!p)throw le(G.SessionNotFound,"client not attached to that session");let m=e.manager.get(u.sessionId);return m?.detach(p.clientId),d.attached.delete(u.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[vt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=HS.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(y=>y.originatingClient?.name!==_i).map(US)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw le(G.InternalError,"agent registry unavailable");return od(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let u=f??{};if(typeof u.agentId!="string"||u.agentId.length===0)throw le(G.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(u.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let u=jS.parse(f);c(u.sessionId,"session/prompt");let p=await HC(u,e.manager,w=>{n.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${w} sessionId=${u.sessionId}`)});if(p?.fromSession!==void 0){if((p.depth??0)>3)throw n.log.warn(`session/prompt: refusing depth ${p.depth} chain from ${p.fromSession} to ${u.sessionId}`),le(G.InvalidRequest,`message chain too deep (${p.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(p.awaiting===!0&&WC(p.fromSession,u.sessionId))throw n.log.warn(`session/prompt: refusing deadlock ${p.fromSession} -> ${u.sessionId}`),le(G.InvalidRequest,`would deadlock: ${u.sessionId} is already blocked waiting on ${p.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let m=d.attached.get(u.sessionId);if(!m)throw n.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),le(G.SessionNotFound,"not attached to session");let h=e.manager.get(u.sessionId);if(!h){let w=await e.manager.loadFromDisk(u.sessionId);if(!w)throw le(G.SessionNotFound,`session ${u.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),h=await Bi(e,w);let k=Lo(a,h,d,void 0,m.clientId);await h.attach(k,"none")}let y=p?.awaiting===!0&&p.fromSession!==void 0?UC(p.fromSession,u.sessionId):void 0;try{return await h.prompt(m.clientId,u,p)}finally{y?.()}});let l=f=>{let u;try{u=nf.parse(f)}catch(h){n.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=d.attached.get(u.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let m=e.manager.get(u.sessionId);m&&m.cancel(p.clientId).catch(h=>{n.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=nf.parse(f);return c(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=zS.parse(f);return c(u.sessionId,"hydra-acp/prompt/cancel"),tr(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=nf.parse(f);return c(u.sessionId,"hydra-acp/session/force_cancel"),tr(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=KS.parse(f);return c(u.sessionId,"hydra-acp/prompt/update"),tr(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=GS.parse(f);c(u.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(u.sessionId);if(!p)throw le(G.SessionNotFound,"not attached to session");return tr(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("_session/steering",async f=>{let u=VS.parse(f);c(u.sessionId,"_session/steering");let p=d.attached.get(u.sessionId);if(!p)throw le(G.SessionNotFound,"not attached to session");let m=e.manager.get(u.sessionId);if(!m){let h=await e.manager.loadFromDisk(u.sessionId);if(!h)throw le(G.SessionNotFound,`session ${u.sessionId} not found`);m=await Bi(e,h);let y=Lo(a,m,d,void 0,p.clientId);await m.attach(y,"none")}return m.steer(p.clientId,u)}),a.onRequest("session/resume",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw le(G.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let b=await e.manager.loadFromDisk(m);if(!b)throw le(G.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Bi(e,b)}Ed(d,h,h.sessionId);let y=Lo(a,h,d);await h.attach(y,"pending_only"),d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1}),h.replayPendingPermissions(y);let w=hp(h),k=mp(h);return{sessionId:h.sessionId,...w?{modes:w}:{},...k?{models:k}:{},configOptions:h.buildConfigOptions(),_meta:gp(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw le(G.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let S=await e.manager.loadFromDisk(m);if(!S)throw le(G.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Bi(e,S)}Ed(d,h,h.sessionId);let y=Lo(a,h,d),{entries:w}=await h.attach(y,"full");d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1});for(let S of w){if(a.isClosed())break;await a.notify(S.method,bs(S.params,S.recordedAt)).catch(()=>{})}h.replayPendingPermissions(y);let k=hp(h),b=mp(h);return{sessionId:h.sessionId,...k?{modes:k}:{},...b?{models:b}:{},configOptions:h.buildConfigOptions(),_meta:gp(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&c(u,"session/set_model");let p=iN(f,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),le(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:"_hydra_current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:m}=p,h=await p.session.forwardModelChange(m,f);return p.session.applyAgentConfigOptionResponse(h,"model"),p.session.applyModelChange(m),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw le(G.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw le(G.InvalidParams,"session/set_mode requires string modeId");let m=tr(e.manager,u.sessionId),h=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=w=>le(G.InvalidParams,w),m=u?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=tr(e.manager,u.sessionId),y=h.buildConfigOptions().find(w=>w.id===u.configId);if(!y)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!y.options.some(w=>w.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{if(u.value!==h.currentModel){let w=await h.forwardModelChange(u.value);h.applyAgentConfigOptionResponse(w,"model")}h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:{let w=await h.forwardRequest("session/set_config_option",{sessionId:u.sessionId,configId:u.configId,value:u.value});h.applyAgentConfigOptionResponse(w,u.configId)&&h.broadcastConfigOptions()}}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=u.startsWith("session/"),h=u.startsWith("hydra-acp/");if(!m&&!h||f===null||typeof f!="object"||p.has(u))throw le(G.MethodNotFound,`Method not found: ${u}`);let y=f.sessionId;if(typeof y!="string")throw le(G.MethodNotFound,`Method not found: ${u}`);return c(y,u),tr(e.manager,y).forwardRequest(u,f)})})}async function rN(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw le(G.InvalidParams,"authenticate requires a non-empty methodId string");let r=t.methodId,s=t._meta?.["hydra-acp"],o=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===r);if(!c){let p=d.map(m=>m.id);throw le(G.InvalidParams,`authenticate: methodId ${JSON.stringify(r)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).join(", ")}]`)}let l=c._meta?.type,f=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(l==="agent"||l==="terminal"?l:f!==void 0?"terminal":"agent"))==="terminal"){let p=(b,S)=>{if(!Array.isArray(b))throw le(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be a string[]; got ${b===null?"null":typeof b}`);for(let C of b)if(typeof C!="string")throw le(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be string[]; got non-string entry ${JSON.stringify(C)}`);return b},m=await e.manager.planSpawnForAgent(a.agentId),h,y;if(f?.args!==void 0){let b=typeof f.command=="string"?f.command:void 0;h=b!==void 0&&KC.isAbsolute(b)?b:m.command,y=p(f.args,'_meta["terminal-auth"].args')}else{let b=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=b!==void 0?p(b.raw,b.label):[];h=m.command,y=[...m.args,...S]}let w={};for(let[b,S]of Object.entries(process.env))typeof S=="string"&&(w[b]=S);Object.assign(w,m.env);let k=zC.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${r}`),{kind:"terminal",command:h,args:y,env:w,cwd:k}}try{return await a.connection.request("authenticate",{methodId:r})}catch(p){throw Mo(p,a)}}async function sN(n,e){let r=(n??{})._meta?.["hydra-acp"],s=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,i=s!==void 0?e.manager.getAgentForSession(s):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function pp(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(rf,t).catch(()=>{})}}function hp(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(s=>{let o={id:s.id,name:s.name??s.id};return s.description!==void 0&&(o.description=s.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function mp(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(s=>{let o={modelId:s.modelId};return s.name!==void 0&&(o.name=s.name),s.description!==void 0&&(o.description=s.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}async function oN(n,e,t,r){return e?await r.isRetiredGeneration(n,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${n} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function iN(n,e){if(!n||typeof n!="object")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let r=e.get(t.sessionId);if(!r)return{kind:"error",code:G.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let s=r.availableModels(),o=ud(t.modelId,s);if(o.kind==="none")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:r,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=s.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return r.currentModel!==void 0&&r.currentModel.length>0?{kind:"no_op",session:r,sessionId:t.sessionId,currentModel:r.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(r.currentModel)} agentId=${r.agentId} known=[${i}]`}:{kind:"error",code:G.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${r.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${r.agentId} known=[${i}] (no current model to fall back to)`}}async function aN(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)throw le(G.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw le(G.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw le(G.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return tr(t.manager,s).addTransformer(o),{ok:!0}}async function dN(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw le(G.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw le(G.InvalidParams,"hydra-acp/attention/set requires string reason");return tr(t.manager,s).setAttentionFlag(e,o,r.payload),{ok:!0}}async function cN(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw le(G.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw le(G.InvalidParams,"hydra-acp/attention/clear requires string reason");return tr(t.manager,s).clearAttentionFlag(e,o),{ok:!0}}function lN(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,workspace:n.workspace,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:Fi(n.currentUsage),forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels,armedTaskList:[]};return{[vt]:tf(e,t)}}function gp(n,e,t={}){let r=n.liveListEntry(e),s={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return Dc(e.agentMeta,tf(r,s))}function uN(){return{protocolVersion:1,agentInfo:{name:"hydra",version:He},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:{...Dc(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}}),steering:{supported:!0}}}}function fN(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let r=e.transformers.resolveChain([t])[0];r&&n.addTransformer(r)}}function VC(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let r of t)r.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Lo(n,e,t,r,s){return{clientId:s??`cli_${ew(8)}`,connection:n,clientInfo:r}}function Ed(n,e,t){let r=n.attached.get(t);r&&(e.detach(r.clientId),n.attached.delete(t))}var yp=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,r,s=new Promise((i,a)=>{t=i,r=a});s.catch(()=>{});let o={session:void 0,sessionReady:s,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),r(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:r}=this.reserve(e);r(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let r=this.byToken.get(e);r!==void 0&&r.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let r of t.disposers)try{await r()}catch{}}}size(){return this.byToken.size}};import{randomUUID as pN}from"crypto";import{McpServer as hN}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as mN}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as vn}from"zod";function tw(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function zn(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var JC="Bearer ";function Pd(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(JC))return;let t=e.slice(JC.length).trim();return t.length>0?t:void 0}function gN(n){let e=new hN({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:vn.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let r=n.streamTail(t);return zn(r)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:vn.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let r=n.streamHead(t);return zn(r)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:vn.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:vn.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:vn.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:r,wait_ms:s})=>{let o=await n.streamRead(t,r,s);return zn(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:vn.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:vn.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:r})=>{let s=await n.streamWaitFor(t,r),o=n.streamInfo();return zn({outcome:s,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:vn.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:vn.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:vn.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:vn.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:vn.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:vn.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:vn.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:vn.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:vn.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let r={pattern:t.pattern};t.regex!==void 0&&(r.regex=t.regex),t.case_insensitive!==void 0&&(r.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(r.invert=t.invert),t.max_matches!==void 0&&(r.maxMatches=t.max_matches),t.max_bytes!==void 0&&(r.maxBytes=t.max_bytes),t.context_before!==void 0&&(r.contextBefore=t.context_before),t.context_after!==void 0&&(r.contextAfter=t.context_after),t.cursor!==void 0&&(r.cursor=t.cursor);let s=n.streamGrep(r);return zn(s)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return zn(t)}),e}var yN=1e4;function YC(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=gN(a),l=new mN({sessionIdGenerator:()=>pN()});await c.connect(l);let f={server:c,transport:l};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Pd(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),yN)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let f=await r(d,l);a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)})}ff();import{randomUUID as wN}from"crypto";import{McpServer as bN}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as kN}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Rs}from"zod";function vN(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var QC=2e3,XC=2e4;function SN(n,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return fd([n]);let r=[],s=jc(t);s!==void 0?r.push(`Tool: ${s}`):typeof t.title=="string"&&t.title.length>0&&r.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&r.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&r.push(a.path);let i=uf(t);return i!==void 0&&r.push(i),r.join(`
|
|
386
|
+
`)}}catch(I){if(I.code==="ENOENT")return l.raw.end(),l;throw I}return l.raw.end(),l}),n.post("/v1/sessions/:id/prompt/:messageId/notify",async(c,l)=>{let f=c.params,u=f.id,p=await e.resolveCanonicalId(u)??u,m=f.messageId,h=c.body,y=typeof h?.callbackUrl=="string"?h.callbackUrl:"",w=typeof h?.secret=="string"?h.secret:"";if(!m||!y||!w){l.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let k;try{k=new URL(y)}catch{l.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(k.protocol!=="https:"&&k.protocol!=="http:"){l.code(400).send({error:"callbackUrl must be http or https"});return}let b=e.get(p);if(!b){l.code(404).send({error:"session not found or not warm"});return}let S=b.registerTurnNotify(m,y,w);if(S.alreadyTerminal){l.code(200).send({status:"already_terminal",stopReason:S.stopReason});return}l.code(202).send({status:"registered"})}),n.get("/v1/sessions/:id/attention",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,p=e.get(u);return!p&&!await e.hasRecord(u)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(u))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(c,l)=>{let f=c.query;if(!f.source||f.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let u=await e.list({includeNonInteractive:!0}),p=[];for(let m of u){let h=e.get(m.sessionId),y;h?y=h.listAttentionFlags():y=(await e.store.read(m.sessionId))?.attentionFlags??[];for(let w of y)w.source===f.source&&p.push({...w,sessionId:m.sessionId})}return{flags:p}}),n.post("/v1/sessions/:id/attention/clear",async(c,l)=>{let f=c.params.id,u=await e.resolveCanonicalId(f)??f,m=c.body??{},h=typeof m.source=="string"?m.source:"",y=typeof m.reason=="string"?m.reason:"";if((h.length>0||y.length>0)&&!(h.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}h.length===0&&y.length;let w=e.get(u);if(w){if(h.length>0&&y.length>0)w.clearAttentionFlag(h,y);else{let I=Array.from(w.listAttentionFlags()).map(T=>`${T.source}::${T.reason}`);for(let T of I)w.clearAttentionFlag(T.split("::")[0],T.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(u)){l.code(404).send({error:"session not found"});return}let k=e.store,b=await k.read(u);if(!b){l.code(404).send({error:"session not found"});return}let S=b.attentionFlags??[],C;if(h.length>0&&y.length>0){let I=`${h}::${y}`;C=S.filter(T=>`${T.source}::${T.reason}`!==I)}else C=[];if(C.length===S.length&&C.every((I,T)=>I.source===S[T].source&&I.reason===S[T].reason)){l.code(204).send();return}await k.write({...b,attentionFlags:C}),l.code(204).send()})}ws();rn();function RC(n,e,t,r={}){n.get("/v1/agents",async()=>od(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let s=await e.refresh();return{version:s.version,agentCount:s.agents.length}}),n.post("/v1/agents/:id/install",async(s,o)=>{let i=s.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await gr(a,[],{npmRegistry:r.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(s,o)=>{let i=s.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===G.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}ve();function TC(n,e,t,r=()=>[]){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:D.home(),driftedKeys:r()}))}var B1=/^[A-Za-z0-9._-]+$/;function lp(n,e,t){let r=e==="extension"?"extensions":"transformers",s=`/v1/${r}`;n.get(s,async()=>({[r]:t.list()})),n.get(`${s}/:name`,async(o,i)=>{let a=o.params.name,d=t.get(a);if(!d){i.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(s,async(o,i)=>{let a=o.body??{},d=D1(a);if("error"in d){i.code(400).send({error:d.error});return}try{let c=t.register(d.config);i.code(201).send(c)}catch(c){ml(i,c)}}),n.delete(`${s}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(d){ml(i,d)}}),n.post(`${s}/:name/start`,async(o,i)=>{let a=o.params.name;try{let d=await t.startByName(a);i.code(200).send(d)}catch(d){ml(i,d)}}),n.post(`${s}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let d=await t.stopByName(a);i.code(200).send(d)}catch(d){ml(i,d)}}),n.post(`${s}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let d=await t.restartByName(a);i.code(200).send(d)}catch(d){ml(i,d)}})}function ml(n,e){let t=e.code,r=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:r});return}if(t==="CONFLICT"){n.code(409).send({error:r});return}n.code(500).send({error:r})}function D1(n){let e=n.name;if(typeof e!="string"||!B1.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let r=n.args;if(r!==void 0&&(!Array.isArray(r)||r.some(i=>typeof i!="string")))return{error:"args must be string[]"};let s=n.env;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))return{error:"env must be an object of string\u2192string"};if(s&&Object.values(s).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:r??[],env:s??{},enabled:o===void 0?!0:o}}}function EC(n,e){lp(n,"extension",e)}function PC(n,e){lp(n,"transformer",e)}function MC(n,e){n.get("/v1/config",async()=>e())}import{z as Fo}from"zod";ve();import*as Oo from"fs/promises";import*as FC from"path";import{randomBytes as H1,scrypt as U1,timingSafeEqual as W1}from"crypto";import{promisify as j1}from"util";var LC=j1(U1);function Zy(){return FC.join(D.home(),"password-hash")}var _C=32768,$C=8,OC=1,q1=64,z1=16,NC=128*1024*1024;async function BC(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=H1(z1),t=await LC(n,e,q1,{N:_C,r:$C,p:OC,maxmem:NC}),r=`scrypt$${_C}$${$C}$${OC}$${e.toString("hex")}$${t.toString("hex")}
|
|
387
|
+
`;await Oo.mkdir(D.home(),{recursive:!0}),await Oo.writeFile(Zy(),r,{encoding:"utf8",mode:384})}async function up(){try{return(await Oo.readFile(Zy(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function fp(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await Oo.readFile(Zy(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await LC(n,i,a.length,{N:r,r:s,p:o,maxmem:NC});return d.length!==a.length?!1:W1(d,a)}var K1=Fo.object({password:Fo.string().min(1),label:Fo.string().min(1).max(256).optional(),ttlSec:Fo.number().int().positive().optional()}),G1=Fo.object({id:Fo.string().optional()}).optional(),V1=Fo.object({token:Fo.string().min(32)});function DC(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,r)=>{let s=J1(t);if(e.rateLimiter.isBlocked(s))return r.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=K1.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}if(!await up())return r.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await fp(o.password))return e.rateLimiter.recordFailure(s),r.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(s);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return r.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,r)=>{let s;try{s=G1.parse(t.body??void 0)}catch{return r.code(400).send({error:"Invalid request body"})}let o=s?.id??t.authIdentity;if(!o||o==="service")return r.code(200).send({revoked:!1});let i=await e.store.revoke(o);return r.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,r)=>r.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,r)=>r.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions",async(t,r)=>{let s=await e.store.revokeAll();return r.code(200).send({revoked:s})}),n.delete("/v1/auth/sessions/:id",async(t,r)=>{let s=t.params.id;return await e.store.revoke(s)?r.code(204).send():r.code(404).send({error:"Not found"})}),n.post("/v1/auth/rotate-token",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=V1.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(s.token),r.code(200).send({rotated:!0})})}function J1(n){return n.ip||"unknown"}Ri();wd();Td();import{nanoid as ew}from"nanoid";lf();rn();ws();_a();er();import{randomBytes as qC}from"crypto";import*as zC from"os";import*as KC from"path";id();var Y1=200;function Q1(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[vt];if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.sentBy;if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o={};if(typeof s.sessionId=="string"&&s.sessionId.length>0&&(o.sessionId=s.sessionId),typeof s.label=="string"&&s.label.length>0&&(o.label=s.label.slice(0,Y1)),s.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function HC(n,e,t){let r=Q1(n);if(!r)return;let s={};if(r.label!==void 0&&(s.fromLabel=r.label),r.awaiting===!0&&(s.awaiting=!0),r.sessionId!==void 0){let o=await e.resolveCanonicalId(r.sessionId)??r.sessionId,i=await e.getOne(o);if(i){s.fromSession=o,i.title&&(s.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;s.depth=(a??0)+1}else t?.(r.sessionId)}if(!(s.fromSession===void 0&&s.fromLabel===void 0))return s}var gl=new Map;function UC(n,e){let t=gl.get(n);t||(t=new Set,gl.set(n,t)),t.add(e);let r=!1;return()=>{if(r)return;r=!0;let s=gl.get(n);s&&(s.delete(e),s.size===0&&gl.delete(n))}}function WC(n,e){if(n===e)return!0;let t=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(t.has(s))continue;t.add(s);let o=gl.get(s);if(o){if(o.has(n))return!0;for(let i of o)r.push(i)}}return!1}function le(n,e,t){let r=new Error(e);return r.code=n,t!==void 0&&(r.data=t),r}function nN(n){if(!n||typeof n!="object")return 512;let r=n.params?.update;if(!r)return 512;let s=512,o=r.content;if(typeof o=="string")s+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(s+=a.text.length),typeof a.data=="string"&&(s+=a.data.length)}let i=r.toolCall;if(i&&(typeof i.rawInput=="string"?s+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(s+=256),typeof i.rawOutput=="string"?s+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(s+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(s+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(s+=c.text.length)}}return s}function tr(n,e,t){let r=n.get(e);if(!r)throw le(G.SessionNotFound,t??`session ${e} not found`);return r}async function Bi(n,e){let t=Rd(n),r,s,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(r=qC(32).toString("hex"),s=n.mcpTokenRegistry.reserve(r),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${r}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=Yy({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),s!==void 0&&s.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(c),r!==void 0&&s!==void 0&&n.mcpTokenRegistry!==void 0){let l=r,f=n.mcpTokenRegistry;s.complete(c),c.onClose(()=>{f.unbind(l)})}return fN(c,n),VC(c.sessionId,n),c}function GC(n,e){n.get("/acp",{websocket:!0},async(t,r)=>{let s=Zx({headers:r.headers,url:r.url});if(!s||!await e.validator.validate(s)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(s),i=As(t),a=new jn(i),d={clientId:`hydra_client_${ew(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of d.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);d.attached.clear()});let c=(f,u)=>{if(d.attached.get(f)?.readonly)throw le(G.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=FS.parse(f??{});u.clientInfo?.name&&(d.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p)),uN()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},m=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.verb!="string")return;let w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(h=>h!==void 0):[];return f.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let m=p??{},h=typeof m.instructions=="string"?m.instructions:void 0,y=Array.isArray(m.tools)?m.tools.map(w=>{if(!w||typeof w!="object")return;let k=w;if(typeof k.name!="string"||k.name.length===0||typeof k.description!="string"||k.inputSchema===null||typeof k.inputSchema!="object")return;let b={name:k.name,description:k.description,inputSchema:k.inputSchema};return k.outputSchema!==null&&typeof k.outputSchema=="object"&&(b.outputSchema=k.outputSchema),b}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,h,y),{ok:!0,registered:y.length}});let u=p=>{let m=p??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw le(G.InvalidParams,"sessionId is required");return m.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let m=u(p),h=p??{};if(typeof h.key!="string"||h.key.length===0)throw le(G.InvalidParams,"key is required");if(!e.manager)throw le(G.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(m,o.name,h.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let m=u(p);if(!e.manager)throw le(G.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(m,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let m=u(p),h=p??{};if(typeof h.key!="string"||h.key.length===0)throw le(G.InvalidParams,"key is required");if(h.value===void 0)throw le(G.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw le(G.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(m,o.name,h.key,h.value)}catch(y){throw le(G.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let m=u(p),h=p??{};if(typeof h.key!="string"||h.key.length===0)throw le(G.InvalidParams,"key is required");if(!e.manager)throw le(G.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(m,o.name,h.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async m=>{let h=m??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw le(G.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(h.sessionId,o.name),{ok:!0}})}a.onClose(()=>{f.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async u=>{let p=u??{},m=Array.isArray(p.intercepts)?p.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,m),e.manager?.defaultTransformers.includes(o.name))){let h=e.transformers.resolveChain([o.name])[0];if(h)for(let y of e.manager.liveSessions())y.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let p=u??{},m=typeof p.sessionId=="string"?p.sessionId:void 0,h=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!m)throw le(-32602,"emit_message requires sessionId");if(!h&&w!=="client_broadcast")throw le(-32602,"emit_message requires method");let k=tr(e.manager,m),b=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(b)return k.dischargeClaim(b,y),{ok:!0};if(w==="chain")return{ok:!0,response:await k.emitToChain(o.name,h,y)};if(w==="queue"){if(h!=="session/prompt")throw le(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await k.emitToQueue(o.name,y)}}if(w==="daemon")return{ok:!0,response:await k.emitToChain(o.name,h,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw le(-32602,"client_broadcast requires an envelope object");return k.broadcastClientUpdate(y),{ok:!0}}throw le(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let p=u??{},m=typeof p.sessionId=="string"?p.sessionId:void 0;if(!m)throw le(-32602,"hydra-acp/session/request_permission requires sessionId");return tr(e.manager,m).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async u=>aN(u,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let p=u??{},m=typeof p.agentId=="string"?p.agentId:void 0,h=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,k=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,b=k&&typeof k.title=="string"?k.title:void 0,S=k&&typeof k.model=="string"?k.model:void 0;if(!h&&y){let q=e.manager.get(y);q&&(h=q.cwd)}if(!h)throw le(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let C=await Ma(h),I=m??C.agentId??e.defaultAgent,T=await e.registry?.getAgent(I),O=mr(C.models,T??{id:I})?.value,E=S??O,$=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:I,cwd:h,parentSessionId:y,interactive:$,transformChain:[],title:b,model:E})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw le(G.InvalidParams,"fork_session requires sessionId");let m=typeof p.forkAt=="string"?p.forkAt:void 0,h=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,k=typeof p.model=="string"&&p.model.length>0?p.model:void 0,b=await e.manager.forkSession(p.sessionId,{...m!==void 0?{forkAt:m}:{},...h!==void 0?{cwd:h}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...k!==void 0?{model:k}:{}}),S=e.manager.get(b.sessionId);if(!S){let T=await e.manager.loadFromDisk(b.sessionId);if(!T)throw le(G.InternalError,`fork ${b.sessionId} vanished before it could be attached`);S=await Bi(e,{...T,onInstallProgress:pp(a)})}Ed(d,S,S.sessionId);let C=Lo(a,S,d),{entries:I}=await S.attach(C,"full");d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:C.clientId,readonly:!1});for(let T of I){if(a.isClosed())break;await a.notify(T.method,bs(T.params,T.recordedAt)).catch(()=>{})}return{...b,sessionId:S.sessionId}}),a.onRequest("session/fork",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw le(G.InvalidParams,"session/fork requires sessionId");let m=typeof p.cwd=="string"?p.cwd:void 0,h=await e.manager.forkSession(p.sessionId,{...m!==void 0?{cwd:m}:{},mode:"verbatim"}),y=e.manager.get(h.sessionId);if(!y){let b=await e.manager.loadFromDisk(h.sessionId);if(!b)throw le(G.InternalError,`fork ${h.sessionId} vanished before it could be attached`);y=await Bi(e,{...b,onInstallProgress:pp(a)})}Ed(d,y,y.sessionId);let w=Lo(a,y,d),{entries:k}=await y.attach(w,"full");d.attached.set(y.sessionId,{sessionId:y.sessionId,clientId:w.clientId,readonly:!1});for(let b of k){if(a.isClosed())break;await a.notify(b.method,bs(b.params,b.recordedAt)).catch(()=>{})}return{sessionId:y.sessionId}});let f=async(u,p)=>{let m=u??{};if(typeof m.sessionId!="string")throw le(G.InvalidParams,`${p} requires sessionId`);let h=await e.manager.resolveCanonicalId(m.sessionId)??m.sessionId,y=e.manager.get(h);if(y)return await y.close({deleteRecord:!0,by:`session/delete ${d.clientId}`}),await e.manager.waitForDeletion(h),await e.manager.hasRecord(h)&&await e.manager.deleteRecord(h),{id:h,existed:!0};let w=await e.manager.deleteRecord(h);return{id:h,existed:w}};a.onRequest("session/delete",async u=>(await f(u,"session/delete"),{})),a.onRequest("session/close",async u=>{let p=u??{};if(typeof p.sessionId!="string")throw le(G.InvalidParams,"session/close requires sessionId");c(p.sessionId,"session/close");let m=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,h=e.manager.get(m);if(h)return await h.close({deleteRecord:!1,by:`session/close ${d.clientId}`+(d.processIdentity?` (${d.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(m))return{};throw le(G.SessionNotFound,`session ${m} not found`)}),a.onRequest("hydra-acp/session/delete",async u=>{let{id:p,existed:m}=await f(u,"hydra-acp/session/delete");if(!m)throw le(G.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let p=u??{},m=typeof p.childSessionId=="string"?p.childSessionId:void 0,h=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!m)throw le(-32602,"await_child requires childSessionId");let w=tr(e.manager,m,`child session ${m} not found`);return new Promise(k=>{let C=[],I=[],T=0,O=!1,E,$,F=!1,q=()=>{F||(F=!0,clearTimeout(z),E?.(),$?.(),k(O?{entries:C,truncated:!0}:{entries:C}))};E=w.onBroadcast(X=>{let oe=nN(X);for(C.push(X),I.push(oe),T+=oe;C.length>0&&(C.length>1e3||T>1048576);)C.shift(),T-=I.shift()??0,O=!0;h==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&q()});let z=setTimeout(q,y);typeof z.unref=="function"&&z.unref(),$=w.onClose(()=>q())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let p=u??{},m=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!m)throw le(-32602,"close_child_session requires childSessionId");let h=e.manager.get(m);return h&&await h.close({deleteRecord:!1,by:`child_session/close ${d.clientId}`}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>dN(u,o.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>cN(u,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let p=u??{},m=typeof p.token=="string"?p.token:void 0,h=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return m&&h&&e.manager.get(h)?.keepAliveClaim(m,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw le(G.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=await e.manager.loadToolBlob(p,u.hash);if(m===null)throw le(G.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>rN(f,e)),a.onRequest("logout",async f=>sN(f,e)),a.onRequest("session/new",async f=>{let u=LS.parse(f),p=_n(f?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(ae=>typeof ae=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(m)??[],y=await Ma(u.cwd),w=p.agentId??y.agentId??e.defaultAgent,k=await e.registry?.getAgent(w),b=mr(y.models,k??{id:w})?.value,S,C,I=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){S=qC(32).toString("hex"),C=e.mcpTokenRegistry.reserve(S);let Ce={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${S}`}]};I=[...u.mcpServers??[],Ce]}let T,O,E=Rd(e);E!==void 0&&(I=[...I??[],...E.descriptors]);let $=Yy({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),F;try{F=await e.manager.create({cwd:u.cwd,agentId:w,mcpServers:I,title:p.title,agentArgs:p.agentArgs,model:p.model??b,onInstallProgress:pp(a),transformChain:h,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...p.workspace!==void 0?{workspace:p.workspace}:{},...$?{mintMcpServersForSwap:$}:{}})}catch(ae){throw C!==void 0&&C.abandon(ae instanceof Error?ae:void 0),O!==void 0&&O.abandon(ae instanceof Error?ae:void 0),E!==void 0&&E.abandon(ae instanceof Error?ae:void 0),ae}if(S!==void 0&&C!==void 0&&e.mcpTokenRegistry!==void 0){let ae=S,Ce=e.mcpTokenRegistry;C.complete(F),F.onClose(()=>{Ce.unbind(ae)})}if(T!==void 0&&O!==void 0&&e.mcpTokenRegistry!==void 0){let ae=T,Ce=e.mcpTokenRegistry;O.complete(F),F.onClose(()=>{Ce.unbind(ae)})}E!==void 0&&E.bindToSession(F),VC(F.sessionId,e);let q,z;try{Ed(d,F,F.sessionId),q=Lo(a,F,d),{entries:z}=await F.attach(q,"full")}catch(ae){throw await F.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),ae}d.attached.set(F.sessionId,{sessionId:F.sessionId,clientId:q.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let ae of z){if(a.isClosed())break;await a.notify(ae.method,bs(ae.params,ae.recordedAt)).catch(()=>{})}})()});let X=hp(F),oe=mp(F);return{sessionId:F.sessionId,...X?{modes:X}:{},...oe?{models:oe}:{},configOptions:F.buildConfigOptions(),_meta:gp(e.manager,F,{clientId:q.clientId})}}),a.onRequest("session/attach",async f=>{let u=BS.parse(f),p=u.clientInfo?.version;p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p));let m=_n(u._meta),h=m.resume,y=m.readonly===!0,w=m.env;n.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${y}`);let k=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,b=e.manager.get(k);if(!b&&y){let F=await e.manager.loadFromDisk(k);if(!F)throw le(G.SessionNotFound,`session ${u.sessionId} not found`);let q=await e.manager.loadHistory(k),z=u.clientId??`cli_${ew(8)}`;d.attached.set(F.hydraSessionId,{sessionId:F.hydraSessionId,clientId:z,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${F.hydraSessionId} clientId=${z} attachedCount=${d.attached.size} replayed=${q.length}`);for(let X of q)await a.notify(X.method,bs(X.params,X.recordedAt)).catch(()=>{});return{sessionId:F.hydraSessionId,clientId:z,connectedClients:[z],historyPolicy:"full",replayed:q.length,_meta:lN(F)}}let S=!b;if(!b){let F=await e.manager.loadFromDisk(k),q=await oN(k,h,F?.upstreamSessionId,e.manager);q.kind==="ignore"&&n.log.warn(q.logMessage);let z=F;if(h&&q.kind==="honor"&&(z={...F,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:F?.workspace?.path??h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!z)throw le(G.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(z.agentId,z.upstreamSessionId))throw le(G.SessionNotFound,`session ${u.sessionId} was deleted`);let X=z.originatingClient?z:{...z,originatingClient:d.clientInfo},oe=w!==void 0?{...X,forwardedEnv:w}:X;b=await Bi(e,{...oe,onInstallProgress:pp(a)})}Ed(d,b,b.sessionId);let C=Lo(a,b,d,u.clientInfo,u.clientId),I=m.replayMode==="drip",{entries:T,appliedPolicy:O}=await b.attach(C,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:I,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:C.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(b.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${b.sessionId} clientId=${C.clientId} attachedCount=${d.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${O} replayed=${T.length} readonly=${y}${I?" replayMode=drip":""}`),I){let F=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,q=750;(async()=>{let z=null;for(let X of T){let oe=typeof X.recordedAt=="number"?X.recordedAt:null;if(z!==null&&oe!==null){let ae=Math.min(q,Math.max(0,(oe-z)/F));ae>0&&await new Promise(Ce=>setTimeout(Ce,ae))}oe!==null&&(z=oe);try{await a.notify(X.method,bs(X.params,oe??void 0))}catch{return}}})()}else for(let F=0;F<T.length&&!a.isClosed();F++){let q=T[F],z=a.notify(q.method,bs(q.params,q.recordedAt)).catch(()=>{});(F+1)%200===0&&await z}b.replayPendingPermissions(C);let E=hp(b),$=mp(b);return{sessionId:b.sessionId,clientId:C.clientId,connectedClients:b.connectedClients(C.clientId),historyPolicy:O,replayed:T.length,...E?{modes:E}:{},...$?{models:$}:{},configOptions:b.buildConfigOptions(),_meta:gp(e.manager,b,{resurrected:S})}}),a.onRequest("session/detach",async f=>{let u=DS.parse(f),p=d.attached.get(u.sessionId);if(!p)throw le(G.SessionNotFound,"client not attached to that session");let m=e.manager.get(u.sessionId);return m?.detach(p.clientId),d.attached.delete(u.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[vt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=HS.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(y=>y.originatingClient?.name!==_i).map(US)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw le(G.InternalError,"agent registry unavailable");return od(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let u=f??{};if(typeof u.agentId!="string"||u.agentId.length===0)throw le(G.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(u.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let u=jS.parse(f);c(u.sessionId,"session/prompt");let p=await HC(u,e.manager,w=>{n.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${w} sessionId=${u.sessionId}`)});if(p?.fromSession!==void 0){if((p.depth??0)>3)throw n.log.warn(`session/prompt: refusing depth ${p.depth} chain from ${p.fromSession} to ${u.sessionId}`),le(G.InvalidRequest,`message chain too deep (${p.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(p.awaiting===!0&&WC(p.fromSession,u.sessionId))throw n.log.warn(`session/prompt: refusing deadlock ${p.fromSession} -> ${u.sessionId}`),le(G.InvalidRequest,`would deadlock: ${u.sessionId} is already blocked waiting on ${p.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let m=d.attached.get(u.sessionId);if(!m)throw n.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),le(G.SessionNotFound,"not attached to session");let h=e.manager.get(u.sessionId);if(!h){let w=await e.manager.loadFromDisk(u.sessionId);if(!w)throw le(G.SessionNotFound,`session ${u.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),h=await Bi(e,w);let k=Lo(a,h,d,void 0,m.clientId);await h.attach(k,"none")}let y=p?.awaiting===!0&&p.fromSession!==void 0?UC(p.fromSession,u.sessionId):void 0;try{return await h.prompt(m.clientId,u,p)}finally{y?.()}});let l=f=>{let u;try{u=nf.parse(f)}catch(h){n.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=d.attached.get(u.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let m=e.manager.get(u.sessionId);m&&m.cancel(p.clientId).catch(h=>{n.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=nf.parse(f);return c(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=zS.parse(f);return c(u.sessionId,"hydra-acp/prompt/cancel"),tr(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=nf.parse(f);return c(u.sessionId,"hydra-acp/session/force_cancel"),tr(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=KS.parse(f);return c(u.sessionId,"hydra-acp/prompt/update"),tr(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=GS.parse(f);c(u.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(u.sessionId);if(!p)throw le(G.SessionNotFound,"not attached to session");return tr(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("_session/steering",async f=>{let u=VS.parse(f);c(u.sessionId,"_session/steering");let p=d.attached.get(u.sessionId);if(!p)throw le(G.SessionNotFound,"not attached to session");let m=e.manager.get(u.sessionId);if(!m){let h=await e.manager.loadFromDisk(u.sessionId);if(!h)throw le(G.SessionNotFound,`session ${u.sessionId} not found`);m=await Bi(e,h);let y=Lo(a,m,d,void 0,p.clientId);await m.attach(y,"none")}return m.steer(p.clientId,u)}),a.onRequest("session/resume",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw le(G.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let b=await e.manager.loadFromDisk(m);if(!b)throw le(G.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Bi(e,b)}Ed(d,h,h.sessionId);let y=Lo(a,h,d);await h.attach(y,"pending_only"),d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1}),h.replayPendingPermissions(y);let w=hp(h),k=mp(h);return{sessionId:h.sessionId,...w?{modes:w}:{},...k?{models:k}:{},configOptions:h.buildConfigOptions(),_meta:gp(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw le(G.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let S=await e.manager.loadFromDisk(m);if(!S)throw le(G.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Bi(e,S)}Ed(d,h,h.sessionId);let y=Lo(a,h,d),{entries:w}=await h.attach(y,"full");d.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1});for(let S of w){if(a.isClosed())break;await a.notify(S.method,bs(S.params,S.recordedAt)).catch(()=>{})}h.replayPendingPermissions(y);let k=hp(h),b=mp(h);return{sessionId:h.sessionId,...k?{modes:k}:{},...b?{models:b}:{},configOptions:h.buildConfigOptions(),_meta:gp(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&c(u,"session/set_model");let p=iN(f,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),le(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:"_hydra_current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:m}=p,h=await p.session.forwardModelChange(m,f);return p.session.applyAgentConfigOptionResponse(h,"model"),p.session.applyModelChange(m),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw le(G.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw le(G.InvalidParams,"session/set_mode requires string modeId");let m=tr(e.manager,u.sessionId),h=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=w=>le(G.InvalidParams,w),m=u?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=tr(e.manager,u.sessionId),y=h.buildConfigOptions().find(w=>w.id===u.configId);if(!y)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!y.options.some(w=>w.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{if(u.value!==h.currentModel){let w=await h.forwardModelChange(u.value);h.applyAgentConfigOptionResponse(w,"model")}h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:{let w=await h.forwardRequest("session/set_config_option",{sessionId:u.sessionId,configId:u.configId,value:u.value});h.applyAgentConfigOptionResponse(w,u.configId)&&h.broadcastConfigOptions()}}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=u.startsWith("session/"),h=u.startsWith("hydra-acp/");if(!m&&!h||f===null||typeof f!="object"||p.has(u))throw le(G.MethodNotFound,`Method not found: ${u}`);let y=f.sessionId;if(typeof y!="string")throw le(G.MethodNotFound,`Method not found: ${u}`);return c(y,u),tr(e.manager,y).forwardRequest(u,f)})})}async function rN(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw le(G.InvalidParams,"authenticate requires a non-empty methodId string");let r=t.methodId,s=t._meta?.["hydra-acp"],o=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===r);if(!c){let p=d.map(m=>m.id);throw le(G.InvalidParams,`authenticate: methodId ${JSON.stringify(r)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).join(", ")}]`)}let l=c._meta?.type,f=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(l==="agent"||l==="terminal"?l:f!==void 0?"terminal":"agent"))==="terminal"){let p=(b,S)=>{if(!Array.isArray(b))throw le(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be a string[]; got ${b===null?"null":typeof b}`);for(let C of b)if(typeof C!="string")throw le(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be string[]; got non-string entry ${JSON.stringify(C)}`);return b},m=await e.manager.planSpawnForAgent(a.agentId),h,y;if(f?.args!==void 0){let b=typeof f.command=="string"?f.command:void 0;h=b!==void 0&&KC.isAbsolute(b)?b:m.command,y=p(f.args,'_meta["terminal-auth"].args')}else{let b=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=b!==void 0?p(b.raw,b.label):[];h=m.command,y=[...m.args,...S]}let w={};for(let[b,S]of Object.entries(process.env))typeof S=="string"&&(w[b]=S);Object.assign(w,m.env);let k=zC.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${r}`),{kind:"terminal",command:h,args:y,env:w,cwd:k}}try{return await a.connection.request("authenticate",{methodId:r})}catch(p){throw Mo(p,a)}}async function sN(n,e){let r=(n??{})._meta?.["hydra-acp"],s=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,i=s!==void 0?e.manager.getAgentForSession(s):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function pp(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(rf,t).catch(()=>{})}}function hp(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(s=>{let o={id:s.id,name:s.name??s.id};return s.description!==void 0&&(o.description=s.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function mp(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(s=>{let o={modelId:s.modelId};return s.name!==void 0&&(o.name=s.name),s.description!==void 0&&(o.description=s.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}async function oN(n,e,t,r){return e?await r.isRetiredGeneration(n,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${n} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function iN(n,e){if(!n||typeof n!="object")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let r=e.get(t.sessionId);if(!r)return{kind:"error",code:G.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let s=r.availableModels(),o=ud(t.modelId,s);if(o.kind==="none")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:r,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=s.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return r.currentModel!==void 0&&r.currentModel.length>0?{kind:"no_op",session:r,sessionId:t.sessionId,currentModel:r.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(r.currentModel)} agentId=${r.agentId} known=[${i}]`}:{kind:"error",code:G.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${r.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${r.agentId} known=[${i}] (no current model to fall back to)`}}async function aN(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)throw le(G.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw le(G.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw le(G.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return tr(t.manager,s).addTransformer(o),{ok:!0}}async function dN(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw le(G.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw le(G.InvalidParams,"hydra-acp/attention/set requires string reason");return tr(t.manager,s).setAttentionFlag(e,o,r.payload),{ok:!0}}async function cN(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw le(G.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw le(G.InvalidParams,"hydra-acp/attention/clear requires string reason");return tr(t.manager,s).clearAttentionFlag(e,o),{ok:!0}}function lN(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,workspace:n.workspace,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:Fi(n.currentUsage),forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels,armedTaskList:[]};return{[vt]:tf(e,t)}}function gp(n,e,t={}){let r=n.liveListEntry(e),s={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return Dc(e.agentMeta,tf(r,s))}function uN(){return{protocolVersion:1,agentInfo:{name:"hydra",version:He},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:{...Dc(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}}),steering:{supported:!0}}}}function fN(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let r=e.transformers.resolveChain([t])[0];r&&n.addTransformer(r)}}function VC(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let r of t)r.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Lo(n,e,t,r,s){return{clientId:s??`cli_${ew(8)}`,connection:n,clientInfo:r}}function Ed(n,e,t){let r=n.attached.get(t);r&&(e.detach(r.clientId),n.attached.delete(t))}var yp=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,r,s=new Promise((i,a)=>{t=i,r=a});s.catch(()=>{});let o={session:void 0,sessionReady:s,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),r(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:r}=this.reserve(e);r(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let r=this.byToken.get(e);r!==void 0&&r.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let r of t.disposers)try{await r()}catch{}}}size(){return this.byToken.size}};import{randomUUID as pN}from"crypto";import{McpServer as hN}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as mN}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as vn}from"zod";function tw(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function zn(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var JC="Bearer ";function Pd(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(JC))return;let t=e.slice(JC.length).trim();return t.length>0?t:void 0}function gN(n){let e=new hN({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:vn.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let r=n.streamTail(t);return zn(r)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:vn.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let r=n.streamHead(t);return zn(r)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:vn.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:vn.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:vn.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:r,wait_ms:s})=>{let o=await n.streamRead(t,r,s);return zn(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:vn.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:vn.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:r})=>{let s=await n.streamWaitFor(t,r),o=n.streamInfo();return zn({outcome:s,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:vn.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:vn.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:vn.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:vn.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:vn.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:vn.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:vn.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:vn.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:vn.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let r={pattern:t.pattern};t.regex!==void 0&&(r.regex=t.regex),t.case_insensitive!==void 0&&(r.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(r.invert=t.invert),t.max_matches!==void 0&&(r.maxMatches=t.max_matches),t.max_bytes!==void 0&&(r.maxBytes=t.max_bytes),t.context_before!==void 0&&(r.contextBefore=t.context_before),t.context_after!==void 0&&(r.contextAfter=t.context_after),t.cursor!==void 0&&(r.cursor=t.cursor);let s=n.streamGrep(r);return zn(s)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return zn(t)}),e}var yN=1e4;function YC(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=gN(a),l=new mN({sessionIdGenerator:()=>pN()});await c.connect(l);let f={server:c,transport:l};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Pd(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),yN)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let f=await r(d,l);a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)})}ff();import{randomUUID as wN}from"crypto";import{McpServer as bN}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as kN}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Rs}from"zod";function vN(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var QC=2e3,XC=2e4;function SN(n,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return fd([n]);let r=[],s=jc(t);s!==void 0?r.push(`Tool: ${s}`):typeof t.title=="string"&&t.title.length>0&&r.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&r.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&r.push(a.path);let i=uf(t);return i!==void 0&&r.push(i),r.join(`
|
|
388
388
|
`)}function IN(n,e){if(n.length<=148)return n;let s=Math.floor(148/2),o=e-s;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function xN(n){let e=new bN({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:Rs.string().min(1).describe("Case-insensitive substring to search for."),limit:Rs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Rs.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:r=10,include_tool_calls:s=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return zn({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=[],a=t.toLowerCase();for await(let{entryId:c,entry:l}of o.iterRecallNewestFirst()){let f=tw(l);if(!f)continue;let{kind:u,update:p}=f;if((u==="tool_call"||u==="tool_call_update")&&!s)continue;let m=SN(l,u,p),h=m.toLowerCase().indexOf(a);if(h<0)continue;let y=vN(u),w=IN(m,h),k=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(i.push({entryId:c,speaker:y,snippet:w,timestamp:k}),i.length>=r)break}i.sort((c,l)=>c.entryId-l.entryId);let d=i.length>=r;return zn({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Rs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Rs.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:r})=>{let s=await n();if(!s.summarizedThroughEntry||s.summarizedThroughEntry===0)return zn({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(r<t)throw new Error(`range: to_entry (${r}) must be >= from_entry (${t})`);let o=r-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await s.getRecallTotalCount();if(i===0)return zn({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(r,i-1),c=a>t||d<r;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await s.sliceRecallHistory(a,d),f=fd(l,{toolOutput:{maxPerCall:QC,maxTotal:XC}});return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:c}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:Rs.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:Rs.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:Rs.string().optional(),limit:Rs.number().int().min(1).max(100).optional(),include_output:Rs.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:r,file_path:s,limit:o=20,include_output:i=!0})=>{let a=await n();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return zn({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let d=typeof t=="string"&&t.length>0,c=typeof r=="string"&&r.length>0,l=typeof s=="string"&&s.length>0;if(!d&&!c&&!l)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let f=new Map,u=Math.max(o*4,200);for await(let{entryId:k,entry:b}of a.iterRecallNewestFirst()){let S=tw(b);if(!S)continue;let{kind:C,update:I}=S;if(C!=="tool_call"&&C!=="tool_call_update")continue;let T=typeof I.toolCallId=="string"&&I.toolCallId.length>0?I.toolCallId:`__noid_${k}`,O=f.get(T);if(O||(O={entryId:k,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},f.set(T,O)),k<O.entryId&&(O.entryId=k),!O.nameAuthoritative){let $=jc(I);$!==void 0?(O.toolName=$,O.nameAuthoritative=!0):typeof I.name=="string"&&I.name.length>0?(O.toolName=I.name,O.nameAuthoritative=!0):C==="tool_call"&&typeof I.title=="string"&&I.title.length>0&&(O.toolName=I.title,O.nameAuthoritative=!0)}if(O.kind===void 0&&typeof I.kind=="string"&&I.kind.length>0&&(O.kind=I.kind),O.output===void 0){let $=uf(I);$!==void 0&&(O.output=$)}let E=I.rawInput;if(E&&typeof E=="object"&&!Array.isArray(E)&&Object.keys(E).length>0)for(let[$,F]of Object.entries(E))O.rawInput[$]===void 0&&(O.rawInput[$]=F);if(Array.isArray(I.locations))for(let $ of I.locations){let F=$?.path;typeof F=="string"&&F.length>0&&!O.locations.includes(F)&&O.locations.push(F)}if(typeof I.status=="string"&&O.status==="in_progress"&&(O.status=I.status),b.recordedAt!==void 0&&O.timestamp===void 0&&(O.timestamp=String(b.recordedAt)),f.size>=u)break}let p=[...f.keys()].sort((k,b)=>f.get(k).entryId-f.get(b).entryId),m=[],h=XC,y=!1;for(let k of p){let b=f.get(k);if(b.toolName=Kg({name:b.toolName,rawInput:b.rawInput,...b.kind!==void 0?{kind:b.kind}:{}}),d&&!b.toolName.toLowerCase().includes(t.toLowerCase())||c&&(b.kind??"").toLowerCase()!==r.toLowerCase())continue;if(l){let I=s.toLowerCase(),T=["file_path","filePath","path"],O=!1;for(let E of T){let $=b.rawInput[E];if(typeof $=="string"&&$.toLowerCase().includes(I)){O=!0;break}}if(!O){for(let E of b.locations)if(E.toLowerCase().includes(I)){O=!0;break}}if(!O)continue}let S={};for(let[I,T]of Object.entries(b.rawInput))typeof T=="string"?S[I]=T.length>500?T.slice(0,497)+"\u2026":T:(typeof T=="number"||typeof T=="boolean")&&(S[I]=T);b.locations.length>0&&S.locations===void 0&&(S.locations=b.locations);let C={entryId:b.entryId,tool:b.toolName,args:S,status:b.status,timestamp:b.timestamp};if(b.kind!==void 0&&(C.kind=b.kind),i&&b.output!==void 0){let I=b.output,T=Math.min(QC,h);if(T<=0)y=!0;else{let O=I.length<=T?I:I.slice(0,T-1)+"\u2026";C.output=O,C.outputBytes=I.length,C.outputTruncated=O.length<I.length,h-=O.length}}if(m.push(C),m.length>=o)break}let w=m.length>=o;return zn({calls:m,truncated:w,...y?{outputBudgetExhausted:y}:{}})}),e}var CN=1e4;function ZC(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=xN(a),l=new kN({sessionIdGenerator:()=>wN()});await c.connect(l);let f={server:c,transport:l};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Pd(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await r(d,async()=>{if(c.session!==void 0)return c.session;let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),CN)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)})}var wp=class{byName=new Map;changeHandlers=[];register(e,t,r,s){this.byName.set(e,{connection:t,instructions:r,tools:[...s]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let r of this.changeHandlers)try{r(e,t)}catch{}}};import{StreamableHTTPServerTransport as $N}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as ON}from"crypto";import{Server as AN}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as RN,ListToolsRequestSchema as TN}from"@modelcontextprotocol/sdk/types.js";function eA(n,e,t,r){let s=typeof t=="function"?async()=>t():async()=>t,o=new AN({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(TN,async()=>{let a=r?.peekSessionId?.();if(a!==void 0&&r?.fetchSessionTools!==void 0)try{let d=await r.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(RN,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,f=PN(l,d.sendNotification);try{let u=await s(),p=await MN(e.connection,n,c,a.params.arguments??{},u);return _N(p,c)}catch(u){return nw(u instanceof Error?u.message:String(u))}finally{f()}}),o}var EN=15e3;function PN(n,e,t=EN){if(n===void 0)return()=>{};let r=0,s=setInterval(()=>{r+=1,e({method:"notifications/progress",params:{progressToken:n,progress:r}}).catch(()=>{})},t);return s.unref?.(),()=>clearInterval(s)}async function MN(n,e,t,r,s){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:r,sessionId:s})}function _N(n,e){if(n===null||typeof n!="object")return nw(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:nw(`extension ${e} omitted content array`)}function nw(n){return{content:[{type:"text",text:n}],isError:!0}}var FN=1e4;function tA(n,e,t){let r=new Map;async function s(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let f of r.values()){let u=f.get(l);u!==void 0&&(f.delete(l),s(u))}}async function i(l,f){for(let[u,p]of r){if(e.lookup(u)?.session?.sessionId!==l)continue;let h=p.get(f);if(h!==void 0)try{await h.server.sendToolListChanged()}catch{}}}t.onChange(l=>{o(l)});async function a(l,f){let u=r.get(l);u===void 0&&(u=new Map,r.set(l,u),e.addDisposer(l,async()=>{let S=r.get(l);if(S!==void 0){r.delete(l);for(let C of S.values())await s(C)}}));let p=u.get(f);if(p!==void 0)return p.transport;let m=t.lookup(f);if(m===void 0)return;let k=eA(f,m,async()=>{let S=e.lookup(l);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let C,I=new Promise(O=>{C=setTimeout(()=>O(void 0),FN)}),T=await Promise.race([S.sessionReady.catch(()=>{}),I]);if(C!==void 0&&clearTimeout(C),T===void 0)throw new Error("session not ready");return T.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async S=>{let C=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:S});if(!C||typeof C!="object")return;let I=C.tools;if(!Array.isArray(I))return;let T=[];for(let O of I){if(!O||typeof O!="object")continue;let E=O;if(typeof E.name!="string"||E.name.length===0||typeof E.description!="string"||E.inputSchema===null||typeof E.inputSchema!="object")continue;let $={name:E.name,description:E.description,inputSchema:E.inputSchema};E.outputSchema!==null&&typeof E.outputSchema=="object"&&($.outputSchema=E.outputSchema),T.push($)}return T}}),b=new $N({sessionIdGenerator:()=>ON()});return await k.connect(b),u.set(f,{server:k,transport:b}),b}async function d(l,f){let u=Pd(l);if(u===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){f.code(404).send({error:"unknown mcp token"});return}let m=l.params.name,h=await a(u,m);if(h===void 0){f.code(404).send({error:`unknown mcp server: ${m}`});return}f.hijack(),await h.handleRequest(l.raw,f.raw,l.body)}let c={config:{skipAuth:!0}};return n.post("/mcp/:name",c,async(l,f)=>{await d(l,f)}),n.get("/mcp/:name",c,async(l,f)=>{await d(l,f)}),n.delete("/mcp/:name",c,async(l,f)=>{await d(l,f)}),{notifyToolListChanged:i}}async function aA(n,e){WN(n),Lc(n.daemon.scrubEnv);let t=n,r=n.daemon.tls?await Ts.readFile(mt(n.daemon.tls.key)):void 0,s=n.daemon.tls?await Ts.readFile(mt(n.daemon.tls.cert)):void 0;await Ts.mkdir(D.home(),{recursive:!0});let{stream:o,fileStream:i}=await HN(n.daemon.logLevel),a=LN({logger:{level:n.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(NN,{options:{handleProtocols:fS}}),xg(ce=>{a.log.info(ce)}),Rg(ce=>{a.log.info(ce)});let d=await Vf.load(),c=new Zf,l=new Xf,f=new Jf(e),u=new Qf([f,new Yf(d),l]),p=Xx({validator:u});a.addHook("onRequest",async(ce,Oe)=>{ce.routeOptions.config?.skipAuth||ce.url==="/acp"||ce.url?.startsWith("/acp?")||await p(ce,Oe)});let m=setInterval(()=>{d.sweepExpired()},300*1e3);m.unref();let h=setInterval(()=>{c.sweepExpired()},300*1e3);h.unref();let y=new Zu(n,{onFetched:()=>{Dx(y,S)}});Wy(ce=>a.log.info(ce));let w={info:ce=>a.log.info(ce),warn:ce=>a.log.warn(ce)},k=ce=>Ro.spawn({...ce,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:w});wS(n.compressToolContent);let b=new Kf,S=new Df(y,k,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:n.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:w,npmRegistry:n.npmRegistry,extensionCommands:b,defaultCwd:n.defaultCwd,disableWorkspaceSnapshots:n.disableWorkspaceSnapshots}),C=new qf(_m(n),void 0,{tokenRegistry:l}),I=new zf($m(n),void 0,{tokenRegistry:l}),T=[];TC(a,He,_o(n),()=>T);let O=new yp,E=new wp,$,F=()=>{if($!==void 0)return $;let ce=a.server.address();return $=`http://127.0.0.1:${ce&&typeof ce=="object"?ce.port:n.daemon.port}`,$},q={agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction};AC(a,S,q,{extensionMcp:E,mcpTokenRegistry:O,getDaemonOrigin:F}),RC(a,y,S,{npmRegistry:n.npmRegistry}),EC(a,C),PC(a,I),MC(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]})),DC(a,{store:d,rateLimiter:c,staticTokenValidator:f}),YC(a,O),ZC(a,O);let z=tA(a,O,E);GC(a,{validator:u,manager:S,defaultAgent:n.defaultAgent,processRegistry:l,onExtensionVersion:(ce,Oe)=>C.reportVersion(ce,Oe),onTransformerVersion:(ce,Oe)=>I.reportVersion(ce,Oe),transformers:I,extensionCommands:b,mcpTokenRegistry:O,extensionMcp:E,extensionMcpControls:z,getDaemonOrigin:F,registry:y});let X=!!n.daemon.tls;await a.listen({host:X?"127.0.0.1":n.daemon.host,port:X?0:n.daemon.port});let oe=a.server.address(),ae=oe&&typeof oe=="object"?oe.port:n.daemon.port,Ce,jt=n.daemon.host,Pt=ae;if(X&&r&&s){Ce=UN({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:ae,tlsOptions:{key:r,cert:s},logger:a.log});let ce=Ce.address();ce&&typeof ce=="object"&&(Pt=ce.port)}await Ts.mkdir(D.home(),{recursive:!0}),await pv({pid:process.pid,host:jt,port:Pt,loopbackPort:ae,startedAt:new Date().toISOString()});let Xe={daemonUrl:`http://127.0.0.1:${ae}`,daemonHost:"127.0.0.1",daemonPort:ae,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${ae}/acp`,hydraHome:D.home()};C.setContext(Xe),I.setContext(Xe),await C.start(),await I.start();try{await S.reconcilePermissionFlags()}catch(ce){a.log.warn(`permission flag reconcile failed: ${ce.message}`)}S.resurrectPendingQueues().catch(ce=>{a.log.warn(`queue replay scan failed: ${ce.message}`)}),S.resumePendingCompactions().catch(ce=>{a.log.warn(`compaction resume scan failed: ${ce.message}`)}),S.resumePendingAgentSwaps().catch(ce=>{a.log.warn(`agent-swap resume scan failed: ${ce.message}`)});let tt=n.daemon.agentSyncIntervalMinutes*60*1e3,pe=tt>0?Hx({registry:y,manager:S,intervalMs:tt,logger:w}):void 0,Ve=n.daemon.sessionGcIntervalMinutes*60*1e3,Ee=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Pe=Ve>0?Ux({manager:S,intervalMs:Ve,maxAgeMs:Ee,logger:w}):void 0,In=zx({bootConfig:n,apply:ce=>{t=ce,y.setConfig(ce),S.setLiveConfig({defaultModels:ce.defaultModels}),q.agentId=ce.defaultAgent,q.cwd=ce.defaultCwd,Lc(ce.daemon.scrubEnv)},onDrift:ce=>{T=ce},logger:w});return{app:a,manager:S,registry:y,extensions:C,transformers:I,mcpTokenRegistry:O,extensionMcp:E,processRegistry:l,shutdown:async()=>{In(),Pe&&Pe(),pe&&pe(),clearInterval(m),clearInterval(h);let ce=async(Oe,fe)=>{try{await fe()}catch(an){a.log.warn(`shutdown step ${Oe} failed: ${an instanceof Error?an.message:String(an)}`)}};await ce("sessionTokenStore.flush",()=>d.flush()),await ce("extensions.stop",()=>C.stop()),await ce("transformers.stop",()=>I.stop()),await ce("manager.closeAll",()=>S.closeAll()),await ce("manager.flushSynopsis",()=>S.flushSynopsis(3e4)),await ce("manager.shutdownSynopsis",()=>S.shutdownSynopsis()),await ce("manager.flushMetaWrites",()=>S.flushMetaWrites()),await ce("manager.flushHistoryWrites",()=>S.flushHistoryWrites()),xg(null),Rg(null),Wy(null),Ce&&await ce("tlsTerminator.close",()=>new Promise(Oe=>Ce.close(()=>Oe()))),await ce("app.close",()=>a.close());try{sA.unlinkSync(D.pidFile())}catch{}await ce("fileStream.flushSync",()=>i.flushSync())}}}var rA=20;async function DN(n,e){let t=Md.dirname(n),r=Md.basename(n,".log"),s=new RegExp(`^${r}\\.(\\d+)\\.log$`),o;try{o=await Ts.readdir(t)}catch{return}let i=[];for(let d of o){let c=d.match(s);c&&i.push({name:d,n:Number(c[1])})}if(i.length<=e)return;i.sort((d,c)=>d.n-c.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>Ts.unlink(Md.join(t,d.name))))}async function HN(n){await DN(D.logFile(),rA);let e=await BN({file:D.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:rA,removeOtherLogFiles:!0}}),t=nA.destination(2);return{stream:nA.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function UN(n){let e=iA.createServer(n.tlsOptions,t=>{let r=oA.connect({host:n.upstreamHost,port:n.upstreamPort}),s=!1,o=i=>{if(!s){s=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{r.destroy()}catch{}}};t.on("error",o),r.on("error",o),t.on("close",()=>o()),r.on("close",()=>o()),t.pipe(r),r.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function WN(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.`)}Hi();er();Id();yl();async function uA(n={}){let e=await Da(),t=await yc();if(await bp(e)){let s=await Od();process.stdout.write(`Daemon already running${s?` (pid ${s.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
|
|
389
389
|
`);return}if(Ra(n,"foreground")){process.title="hydra-acp-daemon";let s=await aA(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
|
|
390
390
|
`);let o=1e4,i=!1,a=async()=>{i&&(process.stderr.write(`Second signal received; exiting immediately.
|