@hydra-acp/cli 0.1.82 → 0.1.83

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/index.js CHANGED
@@ -99,7 +99,7 @@ ${Cn}`:Cn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type
99
99
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof p=="number"?p:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let m=e.exitWaiters.splice(0);for(let y of m)y();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let h=e.breaker.recordExit(p,r.name,this.adapter.kind);if(typeof h=="object"){e.failureReason=h.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${h.tripped}
100
100
  `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Bn(n){try{return process.kill(n,0),!0}catch{return!1}}function at(n,e){return n.code=e,n}var sd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:w.extensionsDir,logFile:w.extensionLogFile,pidFile:w.extensionPidFile}},Nt=class extends qe{constructor(e,t,s={}){super(e,sd,t,s)}};var rd={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:w.transformersDir,logFile:w.transformerLogFile,pidFile:w.transformerPidFile}},jt=class extends qe{connected=new Map;constructor(e,t,s={}){super(e,rd,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}};var Ht=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};import*as ct from"fs/promises";import*as Bt from"path";var dt=n=>{process.stderr.write(n+`
101
101
  `)};function Un(n){dt=n??(e=>process.stderr.write(e+`
102
- `))}async function Nr(n,e){let t=ae();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=Bt.join(w.agentsDir(),t),a;try{a=await ct.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;dt(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let u=i.get(c)??new Set,f=Bt.join(o,c),p;try{p=await ct.readdir(f,{withFileTypes:!0})}catch(g){dt(`hydra-acp: prune: failed to read ${f}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let h=Bt.join(f,m);try{await ct.rm(h,{recursive:!0,force:!0}),dt(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){dt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function jr(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await hn(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function Dn(n){let e=n.maxDeletions??200,t=(p,g)=>{n.logger&&n.logger[p](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,t("warn",`delete ${p} failed: ${g.message}`)}let u=o.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${id(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function Hr(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Dn({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function id(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`}import{createHash as od}from"crypto";function Ln(n){if(Array.isArray(n))return n.map(Ln);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Ln(n[t]);return e}return n}function Br(n){let{tui:e,...t}=n,s=JSON.stringify(Ln(t));return od("sha256").update(s).digest("hex").slice(0,16)}import*as Lr from"path";import{createHash as ad,randomBytes as dd,timingSafeEqual as cd}from"crypto";var qr="hydra_session_",ud=3600*24*30,Ur=12,ld=32,fd=50;function pd(){return Lr.join(w.home(),"session-tokens.json")}function Dr(n){return ad("sha256").update(n).digest("hex")}function Jr(n){return dd(n).toString("hex")}function gd(){return Jr(Ur).slice(0,Ur*2)}function md(){return`${qr}${Jr(ld)}`}var Ut=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=pd(),s=await oe(t);s&&Array.isArray(s.records)&&(e=s.records.filter(hd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=md(),s=Dr(t),r=gd(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:ud,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(qr))return;let t=Dr(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!cd(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},fd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ne(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 hd(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")}var zr="Bearer ",Dt=class{constructor(e){this.token=e}token;async validate(e){return yd(e,this.token)?"service":void 0}},Lt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},qt=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Wr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(zr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(zr.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Qr(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Jt=class{tokens=new Map;mint(e,t){let s=mt();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function yd(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var zt=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as pt from"os";import*as fi from"path";import{posix as wd}from"path";import vd from"strip-ansi";function ut(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Id=/[\x00-\x08\x0b-\x1f\x7f]/g;function ee(n){return vd(n).replace(Id,"")}function L(n){return ee(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Yr(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Md(t);case"agent_thought_chunk":case"agent_thought":return Rd(t);case"user_message_chunk":return Ed(t);case"prompt_received":return Pd(t);case"tool_call":return Td(t,e);case"tool_call_update":return Nd(t,e);case"plan":return Bd(t);case"current_mode_update":return Ud(t);case"current_model_update":return Dd(t);case"turn_complete":return Ld(t);case"usage_update":return Cd(t);case"available_commands_update":return Ad(t);case"available_modes_update":return xd(t);case"session_info_update":return Sd(t);case"config_option_update":return bd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function bd(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function Sd(n){let e=U(n,"title"),t=e!==void 0?L(e):void 0,s=n._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(t===void 0&&r===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),i}function kd(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:L(r)};typeof s.description=="string"&&(i.description=L(s.description)),e.push(i)}return e}function Ad(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:kd(e)}:null}function xd(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:L(r.id)};typeof r.name=="string"&&(i.name=L(r.name)),typeof r.description=="string"&&(i.description=L(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Cd(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 Md(n){let e=lt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ut(n)}}function Rd(n){let e=typeof n.text=="string"?ee(n.text):lt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ut(n)}}function Ed(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=lt(n.content);return t===null?null:{kind:"user-text",text:t}}function Pd(n){let e=qd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Kr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Vr(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 Wt(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Vr(r.oldText),o=Vr(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Xr(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:ee(t)}function Td(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title")??U(n,"name")??U(n,"label")??"tool call",r=U(n,"name")??U(n,"title");if(Kr(r)){let g=Xr(n);if(g!==null){let m=U(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=ti(L(s),n,e),o=U(n,"status"),a=U(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Wt(n);c!==null&&(d.editDiff=c);let l=ei(n);l!==void 0&&(d.detail=l);let u=qn(n);u!==void 0&&(d.detailFull=u);let f=Zr(n);f!==void 0&&(d.locations=f);let p=ut(n);return p!==void 0&&(d.workerTaskId=p),d}function Zr(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Gr=64;function ei(n){let e=qn(n);if(e===void 0)return;let t=n.rawInput;return t&&typeof t.command=="string"?Fd(e,Gr):Od(e,Gr)}function qn(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return ee(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Ee(L(s))}var _d=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function $d(n){for(let e of _d)if(n.startsWith(e))return!0;return!1}function ti(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Ee(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Ee(o)}return $d(n)?Ee(`/${n}`):t.cwd&&t.cwd.length>0?Ee(wd.resolve(t.cwd,n)):n}function Fd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Od(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Nd(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title"),r=s!==void 0?ti(L(s),n,e):void 0,i=U(n,"status"),o=Wt(n),a=ei(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=U(n,"name")??s;if(Kr(c)){let g={kind:"exit-plan-mode",toolCallId:t},m=Xr(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=qn(n);u!==void 0&&(l.detailFull=u);let f=Zr(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let g=jd(n);g!==null&&(l.errorText=g),Hd(n,g)&&(l.upstreamInterrupted=!0)}let p=ut(n);return p!==void 0&&(l.workerTaskId=p),l}function jd(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=lt(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ee(s)}return null}function Hd(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Bd(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?L(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function Ud(n){let e=U(n,"currentModeId")??U(n,"currentMode")??U(n,"mode");return e?{kind:"mode-changed",mode:L(e)}:null}function Dd(n){let e=U(n,"currentModel")??U(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:L(e),...s&&s.length>0?{availableModels:s}:{}}}function Ld(n){let e=U(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function lt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ee(e.text):null}function qd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=lt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function U(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ni(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=zd(o);if(c.length===0)continue;let l=c;if(d!==void 0){let u=e.get(d)??[],f=[];for(let p of c)u.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)Jd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function si(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Jd(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function zd(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=Wt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function ri(n){let e=Wd(n),t=Qd(e),s=[];Vd(s,n),Gd(s,e,t);let r=s.join(`
102
+ `))}async function Nr(n,e){let t=ae();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=Bt.join(w.agentsDir(),t),a;try{a=await ct.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;dt(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let u=i.get(c)??new Set,f=Bt.join(o,c),p;try{p=await ct.readdir(f,{withFileTypes:!0})}catch(g){dt(`hydra-acp: prune: failed to read ${f}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let h=Bt.join(f,m);try{await ct.rm(h,{recursive:!0,force:!0}),dt(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){dt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function jr(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await hn(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${c}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function Dn(n){let e=n.maxDeletions??200,t=(p,g)=>{n.logger&&n.logger[p](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,t("warn",`delete ${p} failed: ${g.message}`)}let u=o.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${id(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function Hr(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Dn({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function id(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`}import{createHash as od}from"crypto";function Ln(n){if(Array.isArray(n))return n.map(Ln);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Ln(n[t]);return e}return n}function Br(n){let{tui:e,...t}=n,s=JSON.stringify(Ln(t));return od("sha256").update(s).digest("hex").slice(0,16)}import*as Lr from"path";import{createHash as ad,randomBytes as dd,timingSafeEqual as cd}from"crypto";var qr="hydra_session_",ud=3600*24*30,Ur=12,ld=32,fd=50;function pd(){return Lr.join(w.home(),"session-tokens.json")}function Dr(n){return ad("sha256").update(n).digest("hex")}function Jr(n){return dd(n).toString("hex")}function gd(){return Jr(Ur).slice(0,Ur*2)}function md(){return`${qr}${Jr(ld)}`}var Ut=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=pd(),s=await oe(t);s&&Array.isArray(s.records)&&(e=s.records.filter(hd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=md(),s=Dr(t),r=gd(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:ud,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(qr))return;let t=Dr(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!cd(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},fd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ne(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 hd(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")}var zr="Bearer ",Dt=class{constructor(e){this.token=e}token;async validate(e){return yd(e,this.token)?"service":void 0}},Lt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},qt=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Wr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(zr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(zr.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Qr(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Jt=class{tokens=new Map;mint(e,t){let s=mt();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function yd(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var zt=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as pt from"os";import*as fi from"path";import{posix as wd}from"path";import vd from"strip-ansi";function ut(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Id=/[\x00-\x08\x0b-\x1f\x7f]/g;function ee(n){return vd(n).replace(Id,"")}function L(n){return ee(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Yr(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Md(t);case"agent_thought_chunk":case"agent_thought":return Rd(t);case"user_message_chunk":return Ed(t);case"prompt_received":return Pd(t);case"tool_call":return Td(t,e);case"tool_call_update":return Nd(t,e);case"plan":return Bd(t);case"current_mode_update":return Ud(t);case"current_model_update":return Dd(t);case"turn_complete":return Ld(t);case"usage_update":return Cd(t);case"available_commands_update":return Ad(t);case"available_modes_update":return xd(t);case"session_info_update":return Sd(t);case"config_option_update":return bd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function bd(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function Sd(n){let e=U(n,"title"),t=e!==void 0?L(e):void 0,s=n._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(t===void 0&&r===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),i}function kd(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:L(r)};typeof s.description=="string"&&(i.description=L(s.description)),e.push(i)}return e}function Ad(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:kd(e)}:null}function xd(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:L(r.id)};typeof r.name=="string"&&(i.name=L(r.name)),typeof r.description=="string"&&(i.description=L(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Cd(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 Md(n){let e=lt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ut(n)}}function Rd(n){let e=typeof n.text=="string"?ee(n.text):lt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ut(n)}}function Ed(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=lt(n.content);return t===null?null:{kind:"user-text",text:t}}function Pd(n){let e=qd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Kr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Vr(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 Wt(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Vr(r.oldText),o=Vr(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Xr(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:ee(t)}function Td(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title")??U(n,"name")??U(n,"label")??"tool call",r=U(n,"name")??U(n,"title");if(Kr(r)){let g=Xr(n);if(g!==null){let m=U(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=ti(L(s),n,e),o=U(n,"status"),a=U(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Wt(n);c!==null&&(d.editDiff=c);let l=ei(n);l!==void 0&&(d.detail=l);let u=qn(n);u!==void 0&&(d.detailFull=u);let f=Zr(n);f!==void 0&&(d.locations=f);let p=ut(n);return p!==void 0&&(d.workerTaskId=p),d}function Zr(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Gr=64;function ei(n){let e=qn(n);if(e===void 0)return;let t=L(e),s=n.rawInput;return s&&typeof s.command=="string"?Fd(t,Gr):Od(t,Gr)}function qn(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return ee(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Ee(L(s))}var _d=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function $d(n){for(let e of _d)if(n.startsWith(e))return!0;return!1}function ti(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Ee(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Ee(o)}return $d(n)?Ee(`/${n}`):t.cwd&&t.cwd.length>0?Ee(wd.resolve(t.cwd,n)):n}function Fd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Od(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Nd(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title"),r=s!==void 0?ti(L(s),n,e):void 0,i=U(n,"status"),o=Wt(n),a=ei(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=U(n,"name")??s;if(Kr(c)){let g={kind:"exit-plan-mode",toolCallId:t},m=Xr(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=qn(n);u!==void 0&&(l.detailFull=u);let f=Zr(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let g=jd(n);g!==null&&(l.errorText=g),Hd(n,g)&&(l.upstreamInterrupted=!0)}let p=ut(n);return p!==void 0&&(l.workerTaskId=p),l}function jd(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=lt(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ee(s)}return null}function Hd(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Bd(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?L(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function Ud(n){let e=U(n,"currentModeId")??U(n,"currentMode")??U(n,"mode");return e?{kind:"mode-changed",mode:L(e)}:null}function Dd(n){let e=U(n,"currentModel")??U(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:L(e),...s&&s.length>0?{availableModels:s}:{}}}function Ld(n){let e=U(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function lt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ee(e.text):null}function qd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=lt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function U(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ni(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=zd(o);if(c.length===0)continue;let l=c;if(d!==void 0){let u=e.get(d)??[],f=[];for(let p of c)u.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)Jd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function si(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Jd(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function zd(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,l=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=Wt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function ri(n){let e=Wd(n),t=Qd(e),s=[];Vd(s,n),Gd(s,e,t);let r=s.join(`
103
103
  `);return r.endsWith(`
104
104
  `)||(r+=`
105
105
  `),r}function Wd(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=Yr(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Qd(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Vd(n,e){let t=e.session,s=er(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Re(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${Jn(a.size)}`:void 0;d.push(c?`${Jn(a.used)} / ${c} tokens`:`${Jn(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${c}`)}i.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(i.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydra-acp/cli",
3
- "version": "0.1.82",
3
+ "version": "0.1.83",
4
4
  "description": "Multi-client ACP session daemon: spawn agents, attach over WSS, multiplex sessions across editors.",
5
5
  "license": "MIT",
6
6
  "type": "module",