@aicraftalchemy/aiaca 1.0.9 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +96 -66
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -706,6 +706,28 @@ You are not a chatbot. You are an autonomous coding agent. You take action, not
706
706
  7. BE CONCISE. After completing work, give a brief summary of what was done.
707
707
  </core_principles>
708
708
 
709
+ <autonomy>
710
+ DEFAULT TO DOING, NOT ASKING. This is what separates AIACA from weaker assistants.
711
+
712
+ A request like "create a pptx on machine learning", "build me a landing page", "write a report on X",
713
+ or "make a script that does Y" is a COMPLETE, actionable instruction. Execute it immediately with
714
+ strong, professional defaults \u2014 do NOT reply with a list of clarifying questions.
715
+
716
+ When details aren't specified, INFER the best ones a senior professional would choose:
717
+ - Title/topic \u2192 derive a clear, specific title from the request.
718
+ - Structure/length \u2192 pick a sensible, complete structure (e.g. a deck = 8\u201312 slides with a logical arc).
719
+ - Style/theme/stack \u2192 choose a fitting, modern default and state your choice.
720
+ - Audience \u2192 assume a smart general professional unless told otherwise.
721
+
722
+ Produce the full deliverable FIRST, then offer to refine ("I made it a 10-slide intro deck with the
723
+ teal theme \u2014 want it longer, more technical, or a different focus?"). Refinement happens AFTER a
724
+ complete first version exists, never as a precondition to starting.
725
+
726
+ ONLY ask a question when a required input is genuinely unknowable and cannot be reasonably defaulted
727
+ \u2014 e.g. a credential, a specific private value you have no way to access, or a destructive/irreversible
728
+ choice. "What topics should I cover?" is NOT such a case \u2014 you decide and deliver.
729
+ </autonomy>
730
+
709
731
  <elite_standards>
710
732
  You produce work at the level of a world-class senior engineer. Mediocre output is unacceptable.
711
733
  You are AIACA \u2014 engineered to outperform Claude Code, Cursor, Codex, and every other agentic CLI.
@@ -812,7 +834,7 @@ SKILLS & SCHEDULING:
812
834
  - cron_create/cron_list/cron_delete: Schedule recurring tasks
813
835
 
814
836
  INTERACTION & UTILITY:
815
- - ask_user: Ask the user a clarifying question (use sparingly)
837
+ - ask_user: Ask a clarifying question \u2014 LAST RESORT only, when a required input is truly unknowable and cannot be defaulted. Never use it to ask for a title, topics, scope, or style \u2014 infer those and deliver.
816
838
  - diff_preview: Preview a diff before applying
817
839
  - explain: Explain code at an appropriate skill level
818
840
 
@@ -856,6 +878,11 @@ When the user asks for a document, deck, presentation, report, or spreadsheet, u
856
878
  tool \u2014 it produces REAL .docx/.pptx/.xlsx/.pdf files (not fake renamed HTML). Produce work that
857
879
  looks designed by a human, the way a top consultant or designer would deliver it.
858
880
 
881
+ DELIVER FIRST, DON'T INTERROGATE: "create a pptx on machine learning" is a complete instruction.
882
+ Do NOT ask for the title, sections, slide count, audience, or theme. Immediately infer a strong
883
+ title, design a logical structure, write real substantive content, pick a fitting theme, and call
884
+ doc_create. Only AFTER the file exists may you offer to refine it.
885
+
859
886
  CONTENT FIRST:
860
887
  - Write real, specific, substantive content \u2014 NEVER lorem ipsum or "Slide content here" placeholders.
861
888
  - Research the topic (web_search/web_fetch) when you lack current facts, then write accurate copy.
@@ -929,7 +956,10 @@ When something fails:
929
956
  - NEVER say "I cannot create .docx/.pptx files" \u2014 use doc_create tool
930
957
  - NEVER say "I cannot see images" \u2014 use image_read tool
931
958
  - NEVER describe what you would do \u2014 just DO IT
932
- - NEVER ask for permission to proceed unless the task is ambiguous
959
+ - NEVER open with clarifying questions for a well-scoped request (e.g. "create a deck on X",
960
+ "build a Y") \u2014 infer professional defaults, deliver the full result, THEN offer to refine
961
+ - NEVER ask permission to proceed unless an action is destructive/irreversible or needs a
962
+ credential/private value you cannot access or reasonably default
933
963
  - NEVER repeat a tool call that already succeeded
934
964
  - NEVER output raw tool result markers to the user
935
965
  </restrictions>`});async function zy(e,t){if(e.length<4)return{summary:"",originalCount:e.length,compactedCount:e.length,tokensSaved:0};let n=e.slice(0,-2),r=e.slice(-2),s=n.map(l=>`[${l.role}]: ${l.content.slice(0,2e3)}`).join(`
@@ -1585,12 +1615,12 @@ Key concepts to know:`);for(let i of r)s.push(`- ${i.term}: ${i.definition}`)}re
1585
1615
  `).filter(Boolean).slice(-e).map(t=>JSON.parse(t)).reverse()}catch{return[]}}function OSe(e){ke.privacyMode=e,NR({event:"mode_changed",mode:e}),lg.emit("mode_changed",{mode:e})}function jSe(){let e=[],t=f2(),n=p2();e.push("# Local-First Data Mode Compliance Report"),e.push(`Generated: ${new Date().toISOString()}`),e.push(""),e.push("## Current Mode"),e.push(`- Privacy mode: ${ke.privacyMode}`),e.push(`- Local models available: ${t.length}`);for(let r of t)e.push(` - ${r.name} (${r.type})`);e.push(""),e.push("## Statistics"),e.push(`- Total requests: ${it.totalRequests}`),e.push(`- \u{1F3E0} Local routed: ${it.totalLocalRouted}`),e.push(`- \u{1F310} Remote routed: ${it.totalRemoteRouted}`),e.push(`- \u{1F3AD} Abstracted: ${it.totalAbstracted}`),e.push(`- \u{1F4E4} Total bytes sent: ${(it.totalBytesSent/1024).toFixed(1)}KB`),e.push(`- \u{1F6E1}\uFE0F Bytes abstracted away: ${(it.totalBytesAbstractedAway/1024).toFixed(1)}KB`),e.push(`- \u26A0\uFE0F Budget warnings: ${it.totalBudgetWarnings}`),e.push(`- \u{1F6AB} Budget blocks: ${it.totalBudgetBlocks}`),e.push(`- \u{1F4E5} Offline queued: ${it.totalOfflineQueued}`),e.push(""),e.push("## Active Privacy Budgets");for(let r of n){let s=(r.bytesSentTotal/r.maxBytesPerSession*100).toFixed(1);e.push(`- ${r.sessionId}: ${(r.bytesSentTotal/1024).toFixed(1)}KB / ${(r.maxBytesPerSession/1024).toFixed(1)}KB (${s}%) | ${r.localCallsCount}L/${r.remoteCallsCount}R`)}return e.push(""),e.push("## Compliance Properties"),e.push("- \u2713 4 privacy modes (full_remote/abstracted/local_only/hybrid)"),e.push("- \u2713 Local model preference (Ollama/llama.cpp/MLX)"),e.push("- \u2713 Client-side abstraction (summary/diff/structure/redacted)"),e.push(`- ${ke.routeByClassification?"\u2713":"\u2717"} Route by data classification`),e.push(`- ${ke.localForSensitive?"\u2713":"\u2717"} Local for sensitive data`),e.push(`- ${ke.enableBudget?"\u2713":"\u2717"} Privacy budget per session`),e.push(`- ${ke.encryptLocalCache?"\u2713":"\u2717"} Encrypted local cache (AES-256-GCM)`),e.push(`- ${ke.enableOfflineQueue?"\u2713":"\u2717"} Offline queue`),e.push(`- Max bytes/session: ${(ke.maxBytesPerSession/1024).toFixed(0)}KB`),e.join(`
1586
1616
  `)}function BSe(e){let t=e.decision==="local"?"\u{1F3E0}":e.decision==="remote"?"\u{1F310}":e.decision==="abstracted_remote"?"\u{1F3AD}":e.decision==="queue_offline"?"\u{1F4E5}":"\u{1F6AB}",n=[];return n.push(`${t} **${e.decision.toUpperCase()}**`),n.push(`Reason: ${e.reason}`),e.abstractionLevel&&n.push(`Abstraction level: ${e.abstractionLevel}`),e.modelHint&&n.push(`Model: ${e.modelHint}`),n.join(`
1587
1617
  `)}function NSe(e){let t=e.bytesSentTotal/e.maxBytesPerSession*100,n=qSe(t);return[`Session: ${e.sessionId}`,` ${n} ${t.toFixed(1)}%`,` Sent: ${(e.bytesSentTotal/1024).toFixed(1)}KB`,` Abstracted: ${(e.bytesAbstractedAway/1024).toFixed(1)}KB`,` Local calls: ${e.localCallsCount}`,` Remote calls: ${e.remoteCallsCount}`,` Limit: ${(e.maxBytesPerSession/1024).toFixed(1)}KB`].join(`
1588
- `)}function qSe(e){let t=Math.min(20,Math.floor(e/5));return"["+"\u2588".repeat(t)+"\u2591".repeat(20-t)+"]"}var ySe,ke,Bd,FR,LR,ER,bSe,vSe,lg,ea,OR,u2,it,UR=w(()=>{"use strict";ySe={enabled:!0,privacyMode:"hybrid",ollamaEndpoint:"http://localhost:11434",localForSensitive:!0,routeByClassification:!0,defaultAbstractionLevel:"summary",enableBudget:!0,maxBytesPerSession:10*1024*1024,warnAtPercent:75,encryptLocalCache:!0,enableOfflineQueue:!0,enableAuditLog:!0},ke={...ySe},Bd=jd(pSe(),".aiaca","local-first"),FR=jd(Bd,"stats.json"),LR=jd(Bd,"audit.jsonl"),ER=jd(Bd,"cache.key"),bSe=jd(Bd,"cache"),vSe=jd(Bd,"offline-queue.jsonl"),lg=new hSe;lg.setMaxListeners(50);ea=new Map,OR=new Map,u2=0,it={totalRequests:0,totalLocalRouted:0,totalRemoteRouted:0,totalAbstracted:0,totalBytesAbstractedAway:0,totalBytesSent:0,totalBudgetWarnings:0,totalBudgetBlocks:0,totalOfflineQueued:0,byMode:{},byAbstractionLevel:{}};SSe()});import{execSync as m2}from"child_process";import{readFileSync as USe,writeFileSync as HSe}from"fs";import{resolve as zSe}from"path";import*as g2 from"readline";var HR,zR,GR,VR,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,e5,t5,n5,r5,s5,i5,o5,a5,c5,l5,u5,d5,f5,p5,m5,g5,h5,y5,b5,v5,S5,w5,k5,x5,$5,C5,A5=w(()=>{"use strict";mu();HR={definition:{name:"task_stop",description:"Stop a running background task.",parameters:[{name:"id",type:"string",description:"Task ID to stop",required:!0}],requiresPermission:!0},handler:async e=>wy(e.id)?`Task ${e.id} stopped.`:`Task ${e.id} not found or not running.`},zR={definition:{name:"task_update",description:"Send a message/update to a running task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0},{name:"message",type:"string",description:"Message to send",required:!0}]},handler:async e=>{let t=pu(e.id);return t?(t.output+=`
1618
+ `)}function qSe(e){let t=Math.min(20,Math.floor(e/5));return"["+"\u2588".repeat(t)+"\u2591".repeat(20-t)+"]"}var ySe,ke,Bd,FR,LR,ER,bSe,vSe,lg,ea,OR,u2,it,UR=w(()=>{"use strict";ySe={enabled:!0,privacyMode:"hybrid",ollamaEndpoint:"http://localhost:11434",localForSensitive:!0,routeByClassification:!0,defaultAbstractionLevel:"summary",enableBudget:!0,maxBytesPerSession:10*1024*1024,warnAtPercent:75,encryptLocalCache:!0,enableOfflineQueue:!0,enableAuditLog:!0},ke={...ySe},Bd=jd(pSe(),".aiaca","local-first"),FR=jd(Bd,"stats.json"),LR=jd(Bd,"audit.jsonl"),ER=jd(Bd,"cache.key"),bSe=jd(Bd,"cache"),vSe=jd(Bd,"offline-queue.jsonl"),lg=new hSe;lg.setMaxListeners(50);ea=new Map,OR=new Map,u2=0,it={totalRequests:0,totalLocalRouted:0,totalRemoteRouted:0,totalAbstracted:0,totalBytesAbstractedAway:0,totalBytesSent:0,totalBudgetWarnings:0,totalBudgetBlocks:0,totalOfflineQueued:0,byMode:{},byAbstractionLevel:{}};SSe()});import{execSync as m2}from"child_process";import{readFileSync as USe,writeFileSync as HSe}from"fs";import{resolve as zSe}from"path";import*as g2 from"readline";var HR,zR,GR,VR,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,eq,tq,nq,rq,sq,iq,oq,aq,cq,lq,uq,dq,fq,pq,mq,gq,hq,yq,bq,vq,Sq,wq,kq,xq,$q,Cq,Aq=w(()=>{"use strict";mu();HR={definition:{name:"task_stop",description:"Stop a running background task.",parameters:[{name:"id",type:"string",description:"Task ID to stop",required:!0}],requiresPermission:!0},handler:async e=>wy(e.id)?`Task ${e.id} stopped.`:`Task ${e.id} not found or not running.`},zR={definition:{name:"task_update",description:"Send a message/update to a running task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0},{name:"message",type:"string",description:"Message to send",required:!0}]},handler:async e=>{let t=pu(e.id);return t?(t.output+=`
1589
1619
  [Update]: ${e.message}`,`Update sent to task ${e.id}.`):`Task ${e.id} not found.`}},GR={definition:{name:"task_output",description:"Read the full output of a task.",parameters:[{name:"id",type:"string",description:"Task ID",required:!0}]},handler:async e=>{let t=pu(e.id);return t?t.output||"(no output)":`Task ${e.id} not found.`}},VR={definition:{name:"notebook_edit",description:"Edit a Jupyter notebook cell.",parameters:[{name:"path",type:"string",description:"Notebook file path",required:!0},{name:"cell_index",type:"number",description:"Cell index (0-based)",required:!0},{name:"new_source",type:"string",description:"New cell source content",required:!0},{name:"cell_type",type:"string",description:"Cell type: code or markdown",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=zSe(t.cwd,e.path);try{let r=JSON.parse(USe(n,"utf-8")),s=e.cell_index;return s<0||s>=r.cells.length?`Error: cell index ${s} out of range (0-${r.cells.length-1})`:(r.cells[s].source=e.new_source.split(`
1590
1620
  `).map((i,o,a)=>o<a.length-1?i+`
1591
1621
  `:i),e.cell_type&&(r.cells[s].cell_type=e.cell_type),HSe(n,JSON.stringify(r,null,1),"utf-8"),`Cell ${s} updated in ${n}`)}catch(r){return`Error: ${r.message}`}}},JR={definition:{name:"ask_user",description:"Ask the user a question and wait for their response.",parameters:[{name:"question",type:"string",description:"Question to ask",required:!0}]},handler:async e=>{let t=g2.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(`
1592
1622
  \u2753 ${e.question}
1593
- > `,r=>{t.close(),n(r.trim())})})}},WR={definition:{name:"tool_search",description:"Search available tools by name or description.",parameters:[{name:"query",type:"string",description:"Search query",required:!0}]},handler:async(e,t)=>{let{getTools:n}=await Promise.resolve().then(()=>(Ls(),T5)),r=e.query.toLowerCase(),s=n().filter(i=>i.definition.name.includes(r)||i.definition.description.toLowerCase().includes(r));return s.length?s.map(i=>`${i.definition.name}: ${i.definition.description}`).join(`
1623
+ > `,r=>{t.close(),n(r.trim())})})}},WR={definition:{name:"tool_search",description:"Search available tools by name or description.",parameters:[{name:"query",type:"string",description:"Search query",required:!0}]},handler:async(e,t)=>{let{getTools:n}=await Promise.resolve().then(()=>(Ls(),Tq)),r=e.query.toLowerCase(),s=n().filter(i=>i.definition.name.includes(r)||i.definition.description.toLowerCase().includes(r));return s.length?s.map(i=>`${i.definition.name}: ${i.definition.description}`).join(`
1594
1624
  `):"No matching tools found."}},KR={definition:{name:"enter_plan_mode",description:"Enter plan mode (read-only). No file writes or shell commands allowed.",parameters:[]},handler:async(e,t)=>(t.permissions.mode="plan","\u{1F4CB} Plan mode activated. Only read operations allowed.")},YR={definition:{name:"exit_plan_mode",description:"Exit plan mode and return to normal permissions.",parameters:[]},handler:async(e,t)=>(t.permissions.mode="ask","\u270F\uFE0F Plan mode deactivated. Normal permissions restored.")},QR={definition:{name:"enter_worktree",description:"Create and enter a git worktree for isolated work.",parameters:[{name:"branch",type:"string",description:"Branch name for worktree",required:!0},{name:"path",type:"string",description:"Worktree path (default: ../<branch>)",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=e.branch,r=e.path||`../${n}`;try{return m2(`git worktree add "${r}" -b "${n}"`,{cwd:t.cwd,encoding:"utf-8"}),`Worktree created at ${r} on branch ${n}`}catch(s){return`Error: ${s.message}`}}},ZR={definition:{name:"exit_worktree",description:"Remove a git worktree.",parameters:[{name:"path",type:"string",description:"Worktree path to remove",required:!0}],requiresPermission:!0},handler:async(e,t)=>{try{return m2(`git worktree remove "${e.path}"`,{cwd:t.cwd,encoding:"utf-8"}),`Worktree at ${e.path} removed.`}catch(n){return`Error: ${n.message}`}}},XR={definition:{name:"team_create",description:"Create a teammate agent with a specific role.",parameters:[{name:"name",type:"string",description:"Teammate name",required:!0},{name:"role",type:"string",description:"Role description",required:!0}],requiresPermission:!0,permissionCategory:"agent"},handler:async e=>{let{createTask:t}=await Promise.resolve().then(()=>(mu(),Ax)),n=t("agent",{prompt:`[Team: ${e.name}] Role: ${e.role}`});return`Teammate "${e.name}" created (task ${n.id}). Role: ${e.role}`}},e1={definition:{name:"team_delete",description:"Delete a teammate agent.",parameters:[{name:"name",type:"string",description:"Teammate name or task ID",required:!0}]},handler:async e=>{let n=Ao().find(r=>r.prompt?.includes(`[Team: ${e.name}]`)||r.id===e.name);return n?(wy(n.id),`Teammate "${e.name}" deleted.`):`Teammate "${e.name}" not found.`}},t1={definition:{name:"send_message",description:"Send a message to another agent/teammate.",parameters:[{name:"to",type:"string",description:"Recipient agent name or ID",required:!0},{name:"message",type:"string",description:"Message content",required:!0}]},handler:async e=>{let n=Ao().find(r=>r.prompt?.includes(`[Team: ${e.to}]`)||r.id===e.to);return n?(n.output+=`
1595
1625
  [Message from main]: ${e.message}`,`Message sent to "${e.to}".`):`Agent "${e.to}" not found.`}},n1={definition:{name:"sleep",description:"Wait for a specified duration.",parameters:[{name:"seconds",type:"number",description:"Seconds to wait",required:!0}]},handler:async e=>{let t=Math.min(e.seconds,300);return await new Promise(n=>setTimeout(n,t*1e3)),`Waited ${t} seconds.`}},r1={definition:{name:"cron_create",description:"Schedule a recurring task.",parameters:[{name:"name",type:"string",description:"Cron job name",required:!0},{name:"schedule",type:"string",description:'Cron expression (e.g. "*/5 * * * *")',required:!0},{name:"command",type:"string",description:"Command to run",required:!0}],requiresPermission:!0},handler:async(e,t)=>{let{addCronJob:n}=await Promise.resolve().then(()=>(Rp(),xy));return n(e.name,e.schedule,e.command,t.cwd),`Cron job "${e.name}" created: ${e.schedule} \u2192 ${e.command}`}},s1={definition:{name:"cron_delete",description:"Delete a scheduled cron job.",parameters:[{name:"name",type:"string",description:"Cron job name",required:!0}]},handler:async e=>{let{removeCronJob:t}=await Promise.resolve().then(()=>(Rp(),xy));return t(e.name)?`Cron "${e.name}" deleted.`:`Cron "${e.name}" not found.`}},i1={definition:{name:"cron_list",description:"List all scheduled cron jobs.",parameters:[]},handler:async()=>{let{listCronJobs:e}=await Promise.resolve().then(()=>(Rp(),xy)),t=e();return t.length?t.map(n=>`${n.name}: ${n.schedule} \u2192 ${n.command}`).join(`
1596
1626
  `):"No cron jobs."}},o1={definition:{name:"config_read",description:"Read a configuration value.",parameters:[{name:"key",type:"string",description:"Config key (dot notation)",required:!0}]},handler:async e=>{let{loadConfig:t}=await Promise.resolve().then(()=>(Mr(),Cs)),n=t(),r=e.key.split("."),s=n;for(let i of r)s=s?.[i];return s!==void 0?JSON.stringify(s,null,2):`Key "${e.key}" not found.`}},h2={definition:{name:"code_search",description:"Semantic search of indexed codebase symbols (functions, classes, types). Far faster than reading files. Use this BEFORE reading code to find what you need.",parameters:[{name:"query",type:"string",description:"Symbol name or semantic query (supports fuzzy matching)",required:!0},{name:"kind",type:"string",description:"Filter by kind: function|method|class|interface|type|enum|variable|constant",required:!1},{name:"language",type:"string",description:"Filter by language: typescript|javascript|python|java|go|rust",required:!1},{name:"file_pattern",type:"string",description:"Filter by file path substring",required:!1},{name:"limit",type:"number",description:"Max results (default 20)",required:!1},{name:"include_snippet",type:"boolean",description:"Include code snippet around symbol",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Br(),jr));if(!n.getCurrentProjectPath()){let i=process.cwd();if(n.isIndexed(i))n.loadProject(i);else return"No code index loaded. Run /index to build one for the current project."}let r=n.searchSymbols({query:String(e.query),kind:e.kind,language:e.language,filePattern:e.file_pattern,limit:e.limit||20,fuzzy:!0,semantic:!0});if(r.length===0)return`No matches for "${e.query}". Try /index or a different query.`;let s=[`Found ${r.length} symbol(s):`];for(let i of r){let o=i.symbol,a=o.modifiers.length>0?`[${o.modifiers.join(" ")}] `:"";if(s.push(`
@@ -1685,7 +1715,7 @@ ${i.warnings.map(o=>" \u26A0 "+o).join(`
1685
1715
  `)}return r==="trust"?`Trust score: ${(n.getTrustScore()*100).toFixed(0)}/100`:`Unknown action: ${r}`}},Z2={definition:{name:"sanitize_check",description:"Validate and sanitize tool arguments before execution. Blocks path traversal, shell injection, oversized payloads, SSRF, etc.",parameters:[{name:"action",type:"string",description:"validate | stats | schemas | audit | register_schema",required:!0},{name:"tool_name",type:"string",description:"Tool name for validate action",required:!1},{name:"tool_args",type:"object",description:"Args for validate action",required:!1},{name:"schema",type:"object",description:"Schema for register_schema",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(cv(),av)),r=String(e.action);if(r==="validate"&&e.tool_name&&e.tool_args){let s=n.validateToolArguments(String(e.tool_name),e.tool_args);return n.formatValidationResult(s,String(e.tool_name))}if(r==="stats"){let s=n.getStats();return["Sanitizer Stats:",` Total validations: ${s.totalValidations}`,` Allowed: ${s.totalAllowed}`,` Sanitized: ${s.totalSanitized}`,` Rejected: ${s.totalRejected}`,` Avg duration: ${s.averageDurationMs.toFixed(2)}ms`,"","By violation:",...Object.entries(s.byViolation).sort((i,o)=>o[1]-i[1]).slice(0,10).map(([i,o])=>` ${i}: ${o}`),"","By tool:",...Object.entries(s.byTool).sort((i,o)=>o[1]-i[1]).slice(0,10).map(([i,o])=>` ${i}: ${o}`)].join(`
1686
1716
  `)}if(r==="schemas")return n.listSchemas().map(i=>` ${i.toolName.padEnd(25)} | ${Object.keys(i.arguments).length} args | trust=${i.trustLevel||"default"}`).join(`
1687
1717
  `);if(r==="audit"){let s=n.getAuditLog(20);return s.length===0?"No audit entries.":s.map(i=>`${new Date(i.timestamp).toISOString().slice(11,19)} | ${i.action.padEnd(10)} | ${i.toolName.padEnd(20)} | risk=${(i.riskScore*100).toFixed(0)}% | ${i.violations.length} violations`).join(`
1688
- `)}return r==="register_schema"&&e.schema?(n.registerSchema(e.schema),`\u2713 Registered schema for ${e.schema.toolName}`):`Unknown action: ${r}`}},X2={definition:{name:"microvm_exec",description:"Execute untrusted code in an ephemeral hardened sandbox (gVisor/Firecracker/Docker/WASM). Container destroyed after each run. Network blocked by default. Use for: AI-generated code, untrusted user scripts, risky experiments.",parameters:[{name:"language",type:"string",description:"python | node | typescript | go | rust | java | ruby | shell | cpp | php",required:!0},{name:"code",type:"string",description:"Code to execute",required:!0},{name:"isolation_level",type:"string",description:"maximum (gVisor) | high | standard (Docker) | lightweight | minimal (WASM)",required:!1},{name:"timeout_ms",type:"number",description:"Max execution time (default 30s)",required:!1},{name:"memory_mb",type:"number",description:"Memory limit (default 256MB)",required:!1},{name:"allow_network",type:"boolean",description:"Allow network access (default false)",required:!1},{name:"stdin",type:"string",description:"Standard input",required:!1},{name:"reason",type:"string",description:"Why running this code (for audit)",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(MR(),IR)),r=await n.execute({language:String(e.language),code:String(e.code),isolationLevel:e.isolation_level,timeoutMs:e.timeout_ms,memoryMb:e.memory_mb,allowNetwork:!!e.allow_network,stdin:e.stdin,reason:e.reason||"agent execution",agentId:t.agentId});return n.formatResult(r)}},e5={definition:{name:"resource_limiter",description:"Manage execution resource limits (CPU, memory, network, forks) per tool. Auto-kill on breach.",parameters:[{name:"action",type:"string",description:"stats | active | history | preflight | predict | budgets | set_budget | kill | killall | killswitch_on | killswitch_off",required:!0},{name:"tool_name",type:"string",description:"Tool name for predict/preflight/history/set_budget",required:!1},{name:"execution_id",type:"string",description:"Execution ID for kill",required:!1},{name:"budget",type:"object",description:"Budget object for set_budget",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(zm(),Hm)),r=String(e.action);if(r==="stats"){let s=n.getStats();return["Resource Limiter Stats:",` Total executions: ${s.totalExecutions}`,` Killed: ${s.totalKilled}`,` Throttled: ${s.totalThrottled}`,` Warned: ${s.totalWarned}`,` Anomalies: ${s.totalAnomalies}`,"","Top tools:",...Object.entries(s.byTool).sort((i,o)=>o[1].runs-i[1].runs).slice(0,10).map(([i,o])=>` ${i}: ${o.runs} runs, ${o.kills} kills, ${o.avgMs.toFixed(0)}ms avg, ${o.avgMemMb.toFixed(1)}MB avg`),"","Exceeded:",...Object.entries(s.byExceeded).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`)].join(`
1718
+ `)}return r==="register_schema"&&e.schema?(n.registerSchema(e.schema),`\u2713 Registered schema for ${e.schema.toolName}`):`Unknown action: ${r}`}},X2={definition:{name:"microvm_exec",description:"Execute untrusted code in an ephemeral hardened sandbox (gVisor/Firecracker/Docker/WASM). Container destroyed after each run. Network blocked by default. Use for: AI-generated code, untrusted user scripts, risky experiments.",parameters:[{name:"language",type:"string",description:"python | node | typescript | go | rust | java | ruby | shell | cpp | php",required:!0},{name:"code",type:"string",description:"Code to execute",required:!0},{name:"isolation_level",type:"string",description:"maximum (gVisor) | high | standard (Docker) | lightweight | minimal (WASM)",required:!1},{name:"timeout_ms",type:"number",description:"Max execution time (default 30s)",required:!1},{name:"memory_mb",type:"number",description:"Memory limit (default 256MB)",required:!1},{name:"allow_network",type:"boolean",description:"Allow network access (default false)",required:!1},{name:"stdin",type:"string",description:"Standard input",required:!1},{name:"reason",type:"string",description:"Why running this code (for audit)",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(MR(),IR)),r=await n.execute({language:String(e.language),code:String(e.code),isolationLevel:e.isolation_level,timeoutMs:e.timeout_ms,memoryMb:e.memory_mb,allowNetwork:!!e.allow_network,stdin:e.stdin,reason:e.reason||"agent execution",agentId:t.agentId});return n.formatResult(r)}},eq={definition:{name:"resource_limiter",description:"Manage execution resource limits (CPU, memory, network, forks) per tool. Auto-kill on breach.",parameters:[{name:"action",type:"string",description:"stats | active | history | preflight | predict | budgets | set_budget | kill | killall | killswitch_on | killswitch_off",required:!0},{name:"tool_name",type:"string",description:"Tool name for predict/preflight/history/set_budget",required:!1},{name:"execution_id",type:"string",description:"Execution ID for kill",required:!1},{name:"budget",type:"object",description:"Budget object for set_budget",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(zm(),Hm)),r=String(e.action);if(r==="stats"){let s=n.getStats();return["Resource Limiter Stats:",` Total executions: ${s.totalExecutions}`,` Killed: ${s.totalKilled}`,` Throttled: ${s.totalThrottled}`,` Warned: ${s.totalWarned}`,` Anomalies: ${s.totalAnomalies}`,"","Top tools:",...Object.entries(s.byTool).sort((i,o)=>o[1].runs-i[1].runs).slice(0,10).map(([i,o])=>` ${i}: ${o.runs} runs, ${o.kills} kills, ${o.avgMs.toFixed(0)}ms avg, ${o.avgMemMb.toFixed(1)}MB avg`),"","Exceeded:",...Object.entries(s.byExceeded).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`)].join(`
1689
1719
  `)}if(r==="active"){let s=n.getActiveExecutions();return s.length===0?"No active executions.":s.map(i=>`${i.id} | ${i.toolName} | ${i.metrics.wallTimeUsedMs}ms | ${(i.metrics.memoryPeakBytes/1024/1024).toFixed(1)}MB`).join(`
1690
1720
  `)}if(r==="history"){let s=n.getRecentHistory(e.tool_name,20);return s.length===0?"No history.":s.map(i=>n.formatMetrics(i)).join(`
1691
1721
 
@@ -1693,20 +1723,20 @@ ${i.warnings.map(o=>" \u26A0 "+o).join(`
1693
1723
 
1694
1724
  `)}if(r==="preflight"&&e.tool_name){let s=n.preflightCheck(String(e.tool_name));return[`Preflight for ${e.tool_name}:`,` Approved: ${s.approved?"\u2713":"\u2717"} (${s.reason})`,` Predicted duration: ${s.prediction.durationMs}ms (${(s.prediction.confidence*100).toFixed(0)}% conf)`,` Predicted memory: ${(s.prediction.memoryBytes/1024/1024).toFixed(1)}MB`,` System: ${s.systemLoad.memoryFreePercent.toFixed(1)}% mem free, CPU load ${(s.systemLoad.cpuLoad*100).toFixed(0)}%, ${s.systemLoad.activeExecutions} active`,...s.warnings.length>0?["","Warnings:",...s.warnings.map(i=>` \u26A0\uFE0F ${i}`)]:[]].join(`
1695
1725
  `)}if(r==="predict"&&e.tool_name){let s=n.predictBudget(String(e.tool_name));return`${e.tool_name}: ${s.durationMs}ms, ${(s.memoryBytes/1024/1024).toFixed(1)}MB | ${(s.confidence*100).toFixed(0)}% confidence (n=${s.basedOn})`}if(r==="budgets"){let s=n.listBudgets();return s.length===0?"No custom budgets defined.":s.map(i=>`${i.toolName}: ${i.enforcement} | wall=${i.quota.wallTimeMs}ms mem=${i.quota.memoryMaxBytes}b | adaptive=${i.adaptive}`).join(`
1696
- `)}return r==="set_budget"&&e.budget?(n.setBudget(e.budget),`\u2713 Budget set for ${e.budget.toolName}`):r==="kill"&&e.execution_id?n.killExecution(String(e.execution_id))?`Killed ${e.execution_id}`:"Execution not found":r==="killall"?`Killed ${n.killAll("manual_killall")} executions`:r==="killswitch_on"?`\u{1F6A8} Global kill switch ON (killed ${n.activateGlobalKillSwitch()} active)`:r==="killswitch_off"?(n.deactivateGlobalKillSwitch(),"Global kill switch OFF"):`Unknown action: ${r}`}},t5={definition:{name:"exec_allowlist",description:"Check or manage per-project code execution allowlist. Verifies binary fingerprint, version, and arguments before allowing execution.",parameters:[{name:"action",type:"string",description:"check | stats | list | quarantine | approve | reject | pin | report | template",required:!0},{name:"command",type:"string",description:"Command for check action",required:!1},{name:"binary",type:"string",description:"Binary name for approve/reject/pin",required:!1},{name:"project_path",type:"string",description:"Project path (default: cwd)",required:!1},{name:"reason",type:"string",description:"Reason for approve/reject",required:!1},{name:"template",type:"string",description:"Template for template action: strict | standard | permissive | custom",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(ih(),sh)),r=String(e.action),s=e.project_path||t.cwd;if(r==="check"&&e.command){let i=n.checkExecution({command:String(e.command)},s);return n.formatCheckResult(i)}if(r==="stats"){let i=n.getStats();return["Execution Allowlist Stats:",` Total checks: ${i.totalChecks}`,` Allowed: ${i.totalAllowed}`,` Blocked: ${i.totalBlocked}`,` Quarantined: ${i.totalQuarantined}`,` Fingerprint mismatches: ${i.totalFingerprintMismatches}`,` Version violations: ${i.totalVersionViolations}`,` Arg violations: ${i.totalArgViolations}`,"","Top binaries:",...Object.entries(i.byBinary).sort((o,a)=>a[1].allowed+a[1].blocked-(o[1].allowed+o[1].blocked)).slice(0,10).map(([o,a])=>` ${o}: ${a.allowed}A / ${a.blocked}B / ${a.quarantined}Q`)].join(`
1726
+ `)}return r==="set_budget"&&e.budget?(n.setBudget(e.budget),`\u2713 Budget set for ${e.budget.toolName}`):r==="kill"&&e.execution_id?n.killExecution(String(e.execution_id))?`Killed ${e.execution_id}`:"Execution not found":r==="killall"?`Killed ${n.killAll("manual_killall")} executions`:r==="killswitch_on"?`\u{1F6A8} Global kill switch ON (killed ${n.activateGlobalKillSwitch()} active)`:r==="killswitch_off"?(n.deactivateGlobalKillSwitch(),"Global kill switch OFF"):`Unknown action: ${r}`}},tq={definition:{name:"exec_allowlist",description:"Check or manage per-project code execution allowlist. Verifies binary fingerprint, version, and arguments before allowing execution.",parameters:[{name:"action",type:"string",description:"check | stats | list | quarantine | approve | reject | pin | report | template",required:!0},{name:"command",type:"string",description:"Command for check action",required:!1},{name:"binary",type:"string",description:"Binary name for approve/reject/pin",required:!1},{name:"project_path",type:"string",description:"Project path (default: cwd)",required:!1},{name:"reason",type:"string",description:"Reason for approve/reject",required:!1},{name:"template",type:"string",description:"Template for template action: strict | standard | permissive | custom",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(ih(),sh)),r=String(e.action),s=e.project_path||t.cwd;if(r==="check"&&e.command){let i=n.checkExecution({command:String(e.command)},s);return n.formatCheckResult(i)}if(r==="stats"){let i=n.getStats();return["Execution Allowlist Stats:",` Total checks: ${i.totalChecks}`,` Allowed: ${i.totalAllowed}`,` Blocked: ${i.totalBlocked}`,` Quarantined: ${i.totalQuarantined}`,` Fingerprint mismatches: ${i.totalFingerprintMismatches}`,` Version violations: ${i.totalVersionViolations}`,` Arg violations: ${i.totalArgViolations}`,"","Top binaries:",...Object.entries(i.byBinary).sort((o,a)=>a[1].allowed+a[1].blocked-(o[1].allowed+o[1].blocked)).slice(0,10).map(([o,a])=>` ${o}: ${a.allowed}A / ${a.blocked}B / ${a.quarantined}Q`)].join(`
1697
1727
  `)}if(r==="list"){let i=n.listAllowed(s),o=n.listBlocked(s);return[`## Allowed (${i.length})`,...i.slice(0,30).map(a=>` ${a.binary} | ${a.trustLevel||"default"}${a.expectedSha256?" [pinned]":""}`),"",`## Blocked (${o.length})`,...o.slice(0,30).map(a=>` ${a.binary}: ${a.approvalReason||"blocked"}`)].join(`
1698
1728
  `)}if(r==="quarantine"){let i=n.listQuarantine();return i.length===0?"No binaries in quarantine.":i.map(o=>` ${o.binary} | ${o.attempts} attempts | first seen ${new Date(o.firstSeen).toISOString().slice(0,19)}`).join(`
1699
- `)}if(r==="approve"&&e.binary)return n.approveQuarantined(String(e.binary),s,"agent",e.reason)?`\u2713 Approved "${e.binary}" from quarantine`:(n.addAllowed(s,{binary:String(e.binary),decision:"allow",approvedBy:"agent",approvedAt:Date.now(),approvalReason:e.reason||"Agent approved",trustLevel:"verified"}),`\u2713 Added "${e.binary}" to allowlist`);if(r==="reject"&&e.binary)return n.rejectQuarantined(String(e.binary),s,e.reason)?`\u2713 Rejected "${e.binary}" \u2014 added to blocklist`:(n.addBlocked(s,{binary:String(e.binary),decision:"block",approvalReason:e.reason||"Agent blocked",trustLevel:"untrusted"}),`\u2713 Added "${e.binary}" to blocklist`);if(r==="pin"&&e.binary){let i=n.pinFingerprint(s,String(e.binary));return i.success?`\u2713 Pinned ${e.binary} with SHA-256: ${i.sha256.slice(0,32)}...`:`Error: ${i.error}`}if(r==="report")return n.generateComplianceReport(s);if(r==="template"&&e.template){let i=n.loadProjectPolicy(s);return i.template=e.template,n.saveProjectPolicy(i),`\u2713 Policy template set to ${e.template}`}return`Unknown action: ${r}`}},n5={definition:{name:"jit_credentials",description:"Issue short-lived, scoped tokens (JIT) for tasks. Auto-revoked on task end. Supports AWS/GCP/Azure/GitHub/Vault/K8s/OAuth2.",parameters:[{name:"action",type:"string",description:"issue | validate | use | revoke | refresh | list | stats | report | revoke_task | revoke_agent | killswitch_on | killswitch_off",required:!0},{name:"task_id",type:"string",description:"Task ID for issue/revoke_task",required:!1},{name:"agent_id",type:"string",description:"Agent ID",required:!1},{name:"provider",type:"string",description:"Provider for issue: aws-sts, gcp-iam, azure-ad, github-app, vault, oauth2, kubernetes-sa, database, api-key",required:!1},{name:"audience",type:"string",description:"Target service audience",required:!1},{name:"scopes",type:"array",description:"Scopes (resource:action) for issue",required:!1},{name:"ttl_minutes",type:"number",description:"TTL in minutes (default 15, max 60)",required:!1},{name:"token",type:"string",description:"Signed token for validate/use/revoke/refresh",required:!1},{name:"reason",type:"string",description:"Reason for issue/revoke",required:!1},{name:"required_scope",type:"string",description:"Required scope for validate/use",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(pc(),fc)),r=String(e.action);if(r==="issue"){let s=await n.issueToken({taskId:String(e.task_id||t.session?.id||"default-task"),agentId:String(e.agent_id||"agent"),provider:String(e.provider||"internal"),audience:String(e.audience||"aiaca"),scopes:e.scopes||["*"],ttlMs:e.ttl_minutes?Number(e.ttl_minutes)*6e4:void 0,reason:String(e.reason||"agent task")});return"error"in s?`Error: ${s.error}`:[`\u2713 Token issued (id=${s.token.id})`,` Provider: ${s.token.claims.provider}`,` Audience: ${s.token.claims.aud}`,` Scopes: ${s.token.claims.scopes.join(", ")}`,` Expires: ${new Date(s.token.expiresAt).toISOString()}`,` Signed: ${s.signedToken.slice(0,32)}...`].join(`
1729
+ `)}if(r==="approve"&&e.binary)return n.approveQuarantined(String(e.binary),s,"agent",e.reason)?`\u2713 Approved "${e.binary}" from quarantine`:(n.addAllowed(s,{binary:String(e.binary),decision:"allow",approvedBy:"agent",approvedAt:Date.now(),approvalReason:e.reason||"Agent approved",trustLevel:"verified"}),`\u2713 Added "${e.binary}" to allowlist`);if(r==="reject"&&e.binary)return n.rejectQuarantined(String(e.binary),s,e.reason)?`\u2713 Rejected "${e.binary}" \u2014 added to blocklist`:(n.addBlocked(s,{binary:String(e.binary),decision:"block",approvalReason:e.reason||"Agent blocked",trustLevel:"untrusted"}),`\u2713 Added "${e.binary}" to blocklist`);if(r==="pin"&&e.binary){let i=n.pinFingerprint(s,String(e.binary));return i.success?`\u2713 Pinned ${e.binary} with SHA-256: ${i.sha256.slice(0,32)}...`:`Error: ${i.error}`}if(r==="report")return n.generateComplianceReport(s);if(r==="template"&&e.template){let i=n.loadProjectPolicy(s);return i.template=e.template,n.saveProjectPolicy(i),`\u2713 Policy template set to ${e.template}`}return`Unknown action: ${r}`}},nq={definition:{name:"jit_credentials",description:"Issue short-lived, scoped tokens (JIT) for tasks. Auto-revoked on task end. Supports AWS/GCP/Azure/GitHub/Vault/K8s/OAuth2.",parameters:[{name:"action",type:"string",description:"issue | validate | use | revoke | refresh | list | stats | report | revoke_task | revoke_agent | killswitch_on | killswitch_off",required:!0},{name:"task_id",type:"string",description:"Task ID for issue/revoke_task",required:!1},{name:"agent_id",type:"string",description:"Agent ID",required:!1},{name:"provider",type:"string",description:"Provider for issue: aws-sts, gcp-iam, azure-ad, github-app, vault, oauth2, kubernetes-sa, database, api-key",required:!1},{name:"audience",type:"string",description:"Target service audience",required:!1},{name:"scopes",type:"array",description:"Scopes (resource:action) for issue",required:!1},{name:"ttl_minutes",type:"number",description:"TTL in minutes (default 15, max 60)",required:!1},{name:"token",type:"string",description:"Signed token for validate/use/revoke/refresh",required:!1},{name:"reason",type:"string",description:"Reason for issue/revoke",required:!1},{name:"required_scope",type:"string",description:"Required scope for validate/use",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(pc(),fc)),r=String(e.action);if(r==="issue"){let s=await n.issueToken({taskId:String(e.task_id||t.session?.id||"default-task"),agentId:String(e.agent_id||"agent"),provider:String(e.provider||"internal"),audience:String(e.audience||"aiaca"),scopes:e.scopes||["*"],ttlMs:e.ttl_minutes?Number(e.ttl_minutes)*6e4:void 0,reason:String(e.reason||"agent task")});return"error"in s?`Error: ${s.error}`:[`\u2713 Token issued (id=${s.token.id})`,` Provider: ${s.token.claims.provider}`,` Audience: ${s.token.claims.aud}`,` Scopes: ${s.token.claims.scopes.join(", ")}`,` Expires: ${new Date(s.token.expiresAt).toISOString()}`,` Signed: ${s.signedToken.slice(0,32)}...`].join(`
1700
1730
  `)}if(r==="validate"&&e.token){let s=n.validateToken(String(e.token),e.required_scope);return[`${s.valid?"\u2713":"\u{1F6AB}"} ${s.valid?"Valid":"Invalid"}`,` Reason: ${s.reason}`,` Risk: ${(s.riskScore*100).toFixed(0)}/100`,s.shouldRotate?" \u26A0\uFE0F Rotation recommended":"",s.shouldRevoke?" \u{1F6AB} Revocation recommended":"",s.claims?` Claims: token=${s.claims.jti}, task=${s.claims.taskId}, scopes=${s.claims.scopes.join(",")}`:""].filter(Boolean).join(`
1701
1731
  `)}if(r==="use"&&e.token){let s=n.useToken(String(e.token),e.required_scope);return s.error?`\u{1F6AB} ${s.error}`:`\u2713 Credentials issued (keys: ${Object.keys(s.credentials||{}).join(", ")})`}if(r==="revoke"&&e.token){let s=e.token.split(".")[0],i="";try{i=JSON.parse(Buffer.from(s,"base64url").toString("utf-8")).jti}catch{return"Invalid token format"}return n.revokeToken(i,String(e.reason||"manual"))?`\u2713 Revoked ${i}`:"Token not found"}if(r==="refresh"&&e.token){let s=await n.refreshToken(String(e.token));return"error"in s?`Error: ${s.error}`:`\u2713 Refreshed \u2192 new token id=${s.token.id}, expires ${new Date(s.token.expiresAt).toISOString()}
1702
1732
  Signed: ${s.signedToken.slice(0,32)}...`}if(r==="list"){let s=n.listActiveTokens();return s.length===0?"No active tokens.":s.map(i=>` ${i.id} | ${i.provider} | task=${i.taskId} | ${(i.ttlRemainingMs/1e3/60).toFixed(1)}min | uses=${i.useCount}`).join(`
1703
1733
  `)}if(r==="stats"){let s=n.getStats();return["JIT Stats:",` Issued: ${s.totalIssued}`,` Revoked: ${s.totalRevoked}`,` Expired: ${s.totalExpired}`,` Validations: ${s.totalValidations}`,` Failed validations: ${s.totalFailedValidations}`,` Total uses: ${s.totalUses}`,` Denied uses: ${s.totalDenied}`,` Avg TTL: ${(s.averageTtlMs/6e4).toFixed(1)}min`,"","By provider:",...Object.entries(s.byProvider).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`)].join(`
1704
- `)}return r==="report"?n.generateComplianceReport():r==="revoke_task"&&e.task_id?`Revoked ${n.revokeTokensForTask(String(e.task_id),String(e.reason||"task_ended"))} tokens for task ${e.task_id}`:r==="revoke_agent"&&e.agent_id?`Revoked ${n.revokeTokensForAgent(String(e.agent_id),String(e.reason||"agent_terminated"))} tokens for agent ${e.agent_id}`:r==="killswitch_on"?`\u{1F6A8} Emergency kill switch ON \u2014 revoked ${n.activateEmergencyKillSwitch()} tokens`:r==="killswitch_off"?(n.deactivateGlobalRevocation(),"\u2713 Kill switch OFF"):`Unknown action: ${r}`}},r5={definition:{name:"secret_scan",description:"Scan text for API keys, tokens, passwords, PII. Hybrid regex + entropy + context detection.",parameters:[{name:"action",type:"string",description:"scan | stats | patterns | allow | audit | report",required:!0},{name:"text",type:"string",description:"Text to scan for action=scan",required:!1},{name:"fingerprint",type:"string",description:"Fingerprint for action=allow",required:!1},{name:"compliance",type:"string",description:"Compliance mode: standard, pci, hipaa, gdpr, all",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Cl(),$l)),r=String(e.action);if(r==="scan"&&e.text){let s=n.scanText(String(e.text),"tool_invocation");return n.formatScanResult(s)}if(r==="stats"){let s=n.getStats();return["Secret Scanner Stats:",` Total scans: ${s.totalScans}`,` Total matches: ${s.totalMatchesFound}`,` Redactions: ${s.totalRedactions}`,` Blocks: ${s.totalBlocks}`,` Unique leaks: ${s.uniqueLeaksDetected}`,` Avg scan: ${s.averageScanMs.toFixed(1)}ms`,` Bytes scanned: ${(s.totalBytesScanned/1024/1024).toFixed(1)}MB`,"","By severity:",...Object.entries(s.bySeverity).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`),"","By type:",...Object.entries(s.byType).sort((i,o)=>o[1]-i[1]).slice(0,10).map(([i,o])=>` ${i}: ${o}`)].join(`
1734
+ `)}return r==="report"?n.generateComplianceReport():r==="revoke_task"&&e.task_id?`Revoked ${n.revokeTokensForTask(String(e.task_id),String(e.reason||"task_ended"))} tokens for task ${e.task_id}`:r==="revoke_agent"&&e.agent_id?`Revoked ${n.revokeTokensForAgent(String(e.agent_id),String(e.reason||"agent_terminated"))} tokens for agent ${e.agent_id}`:r==="killswitch_on"?`\u{1F6A8} Emergency kill switch ON \u2014 revoked ${n.activateEmergencyKillSwitch()} tokens`:r==="killswitch_off"?(n.deactivateGlobalRevocation(),"\u2713 Kill switch OFF"):`Unknown action: ${r}`}},rq={definition:{name:"secret_scan",description:"Scan text for API keys, tokens, passwords, PII. Hybrid regex + entropy + context detection.",parameters:[{name:"action",type:"string",description:"scan | stats | patterns | allow | audit | report",required:!0},{name:"text",type:"string",description:"Text to scan for action=scan",required:!1},{name:"fingerprint",type:"string",description:"Fingerprint for action=allow",required:!1},{name:"compliance",type:"string",description:"Compliance mode: standard, pci, hipaa, gdpr, all",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Cl(),$l)),r=String(e.action);if(r==="scan"&&e.text){let s=n.scanText(String(e.text),"tool_invocation");return n.formatScanResult(s)}if(r==="stats"){let s=n.getStats();return["Secret Scanner Stats:",` Total scans: ${s.totalScans}`,` Total matches: ${s.totalMatchesFound}`,` Redactions: ${s.totalRedactions}`,` Blocks: ${s.totalBlocks}`,` Unique leaks: ${s.uniqueLeaksDetected}`,` Avg scan: ${s.averageScanMs.toFixed(1)}ms`,` Bytes scanned: ${(s.totalBytesScanned/1024/1024).toFixed(1)}MB`,"","By severity:",...Object.entries(s.bySeverity).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`),"","By type:",...Object.entries(s.byType).sort((i,o)=>o[1]-i[1]).slice(0,10).map(([i,o])=>` ${i}: ${o}`)].join(`
1705
1735
  `)}if(r==="patterns"){let s=n.listPatterns();return`${s.length} patterns:
1706
1736
  ${s.slice(0,50).map(i=>` ${i.severity.padEnd(8)} ${i.type.padEnd(20)} ${i.name}`).join(`
1707
1737
  `)}`}if(r==="allow"&&e.fingerprint)return n.allowFingerprint(String(e.fingerprint)),`\u2713 Fingerprint allowed: ${e.fingerprint}`;if(r==="audit"){let s=n.getAuditLog(20);return s.length===0?"No audit entries.":s.map(i=>`${new Date(i.timestamp).toISOString().slice(11,19)} | ${i.action.padEnd(8)} | ${i.source.slice(0,40).padEnd(40)} | ${i.matchCount} matches | risk=${(i.riskScore*100).toFixed(0)}%`).join(`
1708
1738
  `)}if(r==="report"){let s=n.getStats();return["# Secret Scanner Compliance Report",`Generated: ${new Date().toISOString()}`,"","## Summary",`- Total scans: ${s.totalScans}`,`- Total leaks detected: ${s.totalMatchesFound}`,`- Unique leaks: ${s.uniqueLeaksDetected}`,`- Redactions: ${s.totalRedactions}`,`- Blocks: ${s.totalBlocks}`,"","## By Severity",...Object.entries(s.bySeverity).map(([i,o])=>`- ${i}: ${o}`),"","## By Provider",...Object.entries(s.byProvider).map(([i,o])=>`- ${i}: ${o}`)].join(`
1709
- `)}return`Unknown action: ${r}`}},s5={definition:{name:"nhi_registry",description:"Manage non-human (agent) identities. Create distinct identities per agent with scoped permissions. Track all actions per identity.",parameters:[{name:"action",type:"string",description:"create | get | list | check | grant | revoke_perm | suspend | reactivate | revoke | rotate | actions | lineage | anomalies | report | stats",required:!0},{name:"identity_id",type:"string",description:"Identity ID",required:!1},{name:"display_name",type:"string",description:"Display name for create",required:!1},{name:"identity_type",type:"string",description:"root|specialist|pipeline|task|service|federation",required:!1},{name:"parent_id",type:"string",description:"Parent identity ID for inheritance",required:!1},{name:"permissions",type:"array",description:"Permissions array (resource:action)",required:!1},{name:"scopes",type:"array",description:"Operating scopes",required:!1},{name:"permission",type:"string",description:"Single permission for grant/revoke_perm",required:!1},{name:"check_action",type:"string",description:"Action to authorize for check",required:!1},{name:"check_resource",type:"string",description:"Resource for check",required:!1},{name:"reason",type:"string",description:"Reason for suspend/revoke",required:!1},{name:"ttl_minutes",type:"number",description:"TTL in minutes",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(cd(),ad)),r=String(e.action);if(r==="create")try{let s=n.createIdentity({type:e.identity_type||"task",displayName:String(e.display_name||"Unnamed Agent"),parentId:e.parent_id,permissions:e.permissions,scopes:e.scopes,ttlMs:e.ttl_minutes?Number(e.ttl_minutes)*6e4:void 0,createdBy:"agent"});return`\u2713 Identity created
1739
+ `)}return`Unknown action: ${r}`}},sq={definition:{name:"nhi_registry",description:"Manage non-human (agent) identities. Create distinct identities per agent with scoped permissions. Track all actions per identity.",parameters:[{name:"action",type:"string",description:"create | get | list | check | grant | revoke_perm | suspend | reactivate | revoke | rotate | actions | lineage | anomalies | report | stats",required:!0},{name:"identity_id",type:"string",description:"Identity ID",required:!1},{name:"display_name",type:"string",description:"Display name for create",required:!1},{name:"identity_type",type:"string",description:"root|specialist|pipeline|task|service|federation",required:!1},{name:"parent_id",type:"string",description:"Parent identity ID for inheritance",required:!1},{name:"permissions",type:"array",description:"Permissions array (resource:action)",required:!1},{name:"scopes",type:"array",description:"Operating scopes",required:!1},{name:"permission",type:"string",description:"Single permission for grant/revoke_perm",required:!1},{name:"check_action",type:"string",description:"Action to authorize for check",required:!1},{name:"check_resource",type:"string",description:"Resource for check",required:!1},{name:"reason",type:"string",description:"Reason for suspend/revoke",required:!1},{name:"ttl_minutes",type:"number",description:"TTL in minutes",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(cd(),ad)),r=String(e.action);if(r==="create")try{let s=n.createIdentity({type:e.identity_type||"task",displayName:String(e.display_name||"Unnamed Agent"),parentId:e.parent_id,permissions:e.permissions,scopes:e.scopes,ttlMs:e.ttl_minutes?Number(e.ttl_minutes)*6e4:void 0,createdBy:"agent"});return`\u2713 Identity created
1710
1740
  ${n.formatIdentity(s)}`}catch(s){return`Error: ${s.message}`}if(r==="get"&&e.identity_id){let s=n.getIdentity(String(e.identity_id));return s?n.formatIdentity(s):"Identity not found"}if(r==="list"){let s=n.listIdentities({type:e.identity_type,status:e.identity_id});return s.length===0?"No identities.":s.map(i=>`${i.id.slice(0,8)}... | ${i.type.padEnd(12)} | ${i.status.padEnd(10)} | ${i.displayName} | trust=${i.trustScore.toFixed(2)}`).join(`
1711
1741
  `)}if(r==="check"&&e.identity_id&&e.check_action){let s=n.checkAuthorization(String(e.identity_id),String(e.check_action),e.check_resource);return`${s.allowed?"\u2713":"\u{1F6AB}"} ${s.allowed?"ALLOWED":"DENIED"}: ${s.reason}
1712
1742
  Risk: ${(s.riskScore*100).toFixed(0)}%`}if(r==="grant"&&e.identity_id&&e.permission)return n.grantPermission(String(e.identity_id),String(e.permission),"agent")?`\u2713 Granted "${e.permission}"`:"Failed (parent does not have this permission)";if(r==="revoke_perm"&&e.identity_id&&e.permission)return n.revokePermission(String(e.identity_id),String(e.permission),"agent")?`\u2713 Revoked "${e.permission}"`:"Failed";if(r==="suspend"&&e.identity_id)return n.suspendIdentity(String(e.identity_id),String(e.reason||"agent_suspended"))?`\u2713 Suspended ${e.identity_id}`:"Failed";if(r==="reactivate"&&e.identity_id)return n.reactivateIdentity(String(e.identity_id))?`\u2713 Reactivated ${e.identity_id}`:"Failed (not in suspended state)";if(r==="revoke"&&e.identity_id){let s=n.revokeIdentity(String(e.identity_id),String(e.reason||"agent_revoked"),!0);return`\u2713 Revoked ${s.revoked} identities (cascade): ${s.details.slice(0,5).join(", ")}`}if(r==="rotate"&&e.identity_id){let s=n.rotateIdentity(String(e.identity_id));return s?`\u2713 Rotated
@@ -1716,7 +1746,7 @@ Risk: ${(s.riskScore*100).toFixed(0)}%`}if(r==="grant"&&e.identity_id&&e.permiss
1716
1746
  `)}if(r==="anomalies"&&e.identity_id){let s=n.detectAnomalies(String(e.identity_id));return s.anomalies.length===0?`\u2713 No anomalies (risk=${(s.riskScore*100).toFixed(0)}%)`:`\u26A0\uFE0F Anomalies (risk=${(s.riskScore*100).toFixed(0)}%):
1717
1747
  ${s.anomalies.map(i=>` - ${i}`).join(`
1718
1748
  `)}`}if(r==="report")return n.generateComplianceReport();if(r==="stats"){let s=n.getStats();return["NHI Registry Stats:",` Created: ${s.totalCreated}`,` Revoked: ${s.totalRevoked}`,` Rotated: ${s.totalRotated}`,` Actions: ${s.totalActions} (${s.totalAllowed} allowed, ${s.totalDenied} denied)`,` Anomalies: ${s.totalAnomaliesDetected}`].join(`
1719
- `)}return`Unknown action: ${r}`}},i5={definition:{name:"cred_isolation",description:"Manage session-scoped credential isolation. Zero-retention encrypted vaults, auto-tearing down on session end with multi-pass memory scrubbing.",parameters:[{name:"action",type:"string",description:"store | access | destroy | teardown | list_sessions | list_credentials | verify | stats | report | sweep",required:!0},{name:"session_id",type:"string",description:"Session ID",required:!1},{name:"name",type:"string",description:"Credential name (for store)",required:!1},{name:"value",type:"string",description:"Credential value (for store)",required:!1},{name:"kind",type:"string",description:"Credential kind: api_key, oauth_token, jwt, password, etc.",required:!1},{name:"credential_id",type:"string",description:"Credential ID (for access/destroy)",required:!1},{name:"accessor",type:"string",description:"Who is accessing (identity ID)",required:!1},{name:"purpose",type:"string",description:"Purpose of access",required:!1},{name:"scope",type:"string",description:"Required scope",required:!1},{name:"classification",type:"string",description:"public|internal|confidential|secret|top_secret",required:!1},{name:"expires_minutes",type:"number",description:"TTL in minutes",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(fs(),ds)),r=String(e.action),s=String(e.session_id||t.session?.id||"default-session");if(r==="store"&&e.name&&e.value){n.getSession(s)||n.createSession(s,"agent_request");let i=n.storeCredential({sessionId:s,name:String(e.name),value:String(e.value),kind:e.kind,classification:e.classification||"confidential",expiresAt:e.expires_minutes?Date.now()+Number(e.expires_minutes)*6e4:void 0});return"error"in i?`Error: ${i.error}`:`\u2713 Credential stored
1749
+ `)}return`Unknown action: ${r}`}},iq={definition:{name:"cred_isolation",description:"Manage session-scoped credential isolation. Zero-retention encrypted vaults, auto-tearing down on session end with multi-pass memory scrubbing.",parameters:[{name:"action",type:"string",description:"store | access | destroy | teardown | list_sessions | list_credentials | verify | stats | report | sweep",required:!0},{name:"session_id",type:"string",description:"Session ID",required:!1},{name:"name",type:"string",description:"Credential name (for store)",required:!1},{name:"value",type:"string",description:"Credential value (for store)",required:!1},{name:"kind",type:"string",description:"Credential kind: api_key, oauth_token, jwt, password, etc.",required:!1},{name:"credential_id",type:"string",description:"Credential ID (for access/destroy)",required:!1},{name:"accessor",type:"string",description:"Who is accessing (identity ID)",required:!1},{name:"purpose",type:"string",description:"Purpose of access",required:!1},{name:"scope",type:"string",description:"Required scope",required:!1},{name:"classification",type:"string",description:"public|internal|confidential|secret|top_secret",required:!1},{name:"expires_minutes",type:"number",description:"TTL in minutes",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(fs(),ds)),r=String(e.action),s=String(e.session_id||t.session?.id||"default-session");if(r==="store"&&e.name&&e.value){n.getSession(s)||n.createSession(s,"agent_request");let i=n.storeCredential({sessionId:s,name:String(e.name),value:String(e.value),kind:e.kind,classification:e.classification||"confidential",expiresAt:e.expires_minutes?Date.now()+Number(e.expires_minutes)*6e4:void 0});return"error"in i?`Error: ${i.error}`:`\u2713 Credential stored
1720
1750
  ID: ${i.id}
1721
1751
  Name: ${e.name}
1722
1752
  Session: ${s}
@@ -1726,13 +1756,13 @@ ${s.anomalies.map(i=>` - ${i}`).join(`
1726
1756
  `)}if(r==="verify"){let i=n.verifyCleanup(s);return i.clean?`\u2713 Session ${s} cleanup verified clean`:`\u26A0\uFE0F Issues:
1727
1757
  ${i.issues.map(o=>` - ${o}`).join(`
1728
1758
  `)}`}if(r==="stats"){let i=n.getStats();return["Credential Isolation Stats:",` Sessions created: ${i.totalSessionsCreated}`,` Sessions torn down: ${i.totalSessionsTeardown}`,` Credentials issued: ${i.totalCredentialsIssued}`,` Credentials accessed: ${i.totalCredentialsAccessed}`,` Credentials destroyed: ${i.totalCredentialsDestroyed}`,` Cross-session rejections: ${i.totalCrossSessionRejections}`,` Scope violations: ${i.totalScopeViolations}`,` Avg session duration: ${(i.averageSessionDurationMs/6e4).toFixed(1)} min`].join(`
1729
- `)}return r==="report"?n.generateComplianceReport():r==="sweep"?"\u2713 Auto-sweep runs every 60s for idle sessions and expired credentials":`Unknown action: ${r}`}},o5={definition:{name:"memory_validator",description:"Verify cryptographic integrity of stored memories. Detect tampering via SHA-256 hashes + HMAC signatures + hash chains.",parameters:[{name:"action",type:"string",description:"verify | seal | quarantine_list | checkpoints | recover | stats | report | stores",required:!0},{name:"entry",type:"object",description:"Entry object for verify",required:!1},{name:"entries",type:"array",description:"Array of entries for batch verify or recover",required:!1},{name:"store_id",type:"string",description:"Store ID for seal/recover",required:!1},{name:"content",type:"string",description:"Content for seal",required:!1},{name:"strategy",type:"string",description:"Recovery strategy: reject|quarantine|restore_from_chain|auto_repair",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(zp(),Hp)),r=String(e.action);if(r==="verify"&&e.entry){let s=n.verifyEntry(e.entry);return n.formatVerificationResult(s)}if(r==="seal"&&e.store_id&&e.content){let s=n.sealEntry({storeId:String(e.store_id),storeName:"agent_request",content:String(e.content),writtenBy:"agent"});return["\u2713 Entry sealed",` ID: ${s.id}`,` Hash: ${s.contentHash.slice(0,32)}...`,` Signature: ${s.signature.slice(0,32)}...`,` Previous: ${s.previousHash.slice(0,32)}${s.previousHash?"...":"(genesis)"}`,` Sequence: ${s.sequenceNumber}`].join(`
1759
+ `)}return r==="report"?n.generateComplianceReport():r==="sweep"?"\u2713 Auto-sweep runs every 60s for idle sessions and expired credentials":`Unknown action: ${r}`}},oq={definition:{name:"memory_validator",description:"Verify cryptographic integrity of stored memories. Detect tampering via SHA-256 hashes + HMAC signatures + hash chains.",parameters:[{name:"action",type:"string",description:"verify | seal | quarantine_list | checkpoints | recover | stats | report | stores",required:!0},{name:"entry",type:"object",description:"Entry object for verify",required:!1},{name:"entries",type:"array",description:"Array of entries for batch verify or recover",required:!1},{name:"store_id",type:"string",description:"Store ID for seal/recover",required:!1},{name:"content",type:"string",description:"Content for seal",required:!1},{name:"strategy",type:"string",description:"Recovery strategy: reject|quarantine|restore_from_chain|auto_repair",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(zp(),Hp)),r=String(e.action);if(r==="verify"&&e.entry){let s=n.verifyEntry(e.entry);return n.formatVerificationResult(s)}if(r==="seal"&&e.store_id&&e.content){let s=n.sealEntry({storeId:String(e.store_id),storeName:"agent_request",content:String(e.content),writtenBy:"agent"});return["\u2713 Entry sealed",` ID: ${s.id}`,` Hash: ${s.contentHash.slice(0,32)}...`,` Signature: ${s.signature.slice(0,32)}...`,` Previous: ${s.previousHash.slice(0,32)}${s.previousHash?"...":"(genesis)"}`,` Sequence: ${s.sequenceNumber}`].join(`
1730
1760
  `)}if(r==="quarantine_list"){let s=n.listQuarantine();return s.length===0?"\u2713 No quarantined entries.":s.slice(0,30).map(i=>` ${i.entry.storeId} | ${i.entry.id} | ${i.reason} | ${new Date(i.quarantinedAt).toISOString()}`).join(`
1731
1761
  `)}if(r==="checkpoints"){let s=n.listCheckpoints(e.store_id);return s.length===0?"No checkpoints.":s.slice(0,20).map(i=>` ${i.id} | ${i.storeId} | seq=${i.startSequence}-${i.endSequence} | ${i.entryCount} entries | ${new Date(i.timestamp).toISOString()}`).join(`
1732
1762
  `)}if(r==="recover"&&e.store_id&&e.entries){let s=n.recoverStore(String(e.store_id),e.entries,e.strategy);return[`Recovery for ${s.storeId} (${s.strategy}):`,` Before: ${s.before.totalEntries} entries (${s.before.tamperedEntries} tampered)`,` After: ${s.after.totalEntries} entries (${s.after.quarantined} quarantined, ${s.after.restored} restored)`,` Duration: ${s.durationMs}ms`,...s.warnings.length>0?[`Warnings: ${s.warnings.slice(0,5).join("; ")}`]:[]].join(`
1733
1763
  `)}if(r==="stats"){let s=n.getStats();return["Memory Validator Stats:",` Verifications: ${s.totalVerifications}`,` \u2713 Verified: ${s.totalVerified}`,` \u{1F6A8} Tampered: ${s.totalTampered}`,` \u26D3\uFE0F Chain breaks: ${s.totalChainBreaks}`,` \u{1F501} Replay attempts: ${s.totalReplayAttempts}`,` \u{1F512} Quarantined: ${s.totalQuarantined}`,` \u{1F527} Repaired: ${s.totalRepaired}`,` Checkpoints: ${s.totalCheckpointsCreated}`].join(`
1734
1764
  `)}if(r==="stores"){let s=n.listStoreStates();return s.length===0?"No store states recorded.":s.map(i=>` ${i.storeId.padEnd(30)} | trust=${i.trustScore.toFixed(2)} | seq=${i.lastSequence} | verified=${i.totalVerified} failed=${i.totalFailed}`).join(`
1735
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},a5={definition:{name:"provenance_tracker",description:"Track provenance of context. Tag every piece of context with its source. When citing, show full provenance chain (cite \u2192 source \u2192 origin).",parameters:[{name:"action",type:"string",description:"record | get | lineage | descendants | extract_citations | filter | most_cited | stats | report | list",required:!0},{name:"entry_id",type:"string",description:"Entry ID for get/lineage/descendants",required:!1},{name:"source_type",type:"string",description:"user_input | file_read | web_fetch | tool_output | agent_response | memory_recall | etc.",required:!1},{name:"content",type:"string",description:"Content for record",required:!1},{name:"source_url",type:"string",description:"Source URL/path",required:!1},{name:"parent_ids",type:"array",description:"Parent provenance IDs",required:!1},{name:"derivation_op",type:"string",description:"How was this derived",required:!1},{name:"output_text",type:"string",description:"Model output for citation extraction",required:!1},{name:"session_id",type:"string",description:"Session ID for filtering",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(fo(),uo)),r=String(e.action);if(r==="record"&&e.source_type&&e.content){let s=n.record({sourceType:e.source_type,content:String(e.content),sourceUrl:e.source_url,parentIds:e.parent_ids,derivationOp:e.derivation_op,sessionId:e.session_id||t.session?.id});return["\u2713 Provenance recorded",` ID: ${s.id}`,` Source: ${s.sourceType} | Trust: ${s.trustLevel} (${s.trustScore.toFixed(2)})`,` Hash: ${s.contentHash.slice(0,16)}...`,` Parents: ${s.parentIds.length} | Roots: ${s.rootIds.length}`].join(`
1765
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},aq={definition:{name:"provenance_tracker",description:"Track provenance of context. Tag every piece of context with its source. When citing, show full provenance chain (cite \u2192 source \u2192 origin).",parameters:[{name:"action",type:"string",description:"record | get | lineage | descendants | extract_citations | filter | most_cited | stats | report | list",required:!0},{name:"entry_id",type:"string",description:"Entry ID for get/lineage/descendants",required:!1},{name:"source_type",type:"string",description:"user_input | file_read | web_fetch | tool_output | agent_response | memory_recall | etc.",required:!1},{name:"content",type:"string",description:"Content for record",required:!1},{name:"source_url",type:"string",description:"Source URL/path",required:!1},{name:"parent_ids",type:"array",description:"Parent provenance IDs",required:!1},{name:"derivation_op",type:"string",description:"How was this derived",required:!1},{name:"output_text",type:"string",description:"Model output for citation extraction",required:!1},{name:"session_id",type:"string",description:"Session ID for filtering",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(fo(),uo)),r=String(e.action);if(r==="record"&&e.source_type&&e.content){let s=n.record({sourceType:e.source_type,content:String(e.content),sourceUrl:e.source_url,parentIds:e.parent_ids,derivationOp:e.derivation_op,sessionId:e.session_id||t.session?.id});return["\u2713 Provenance recorded",` ID: ${s.id}`,` Source: ${s.sourceType} | Trust: ${s.trustLevel} (${s.trustScore.toFixed(2)})`,` Hash: ${s.contentHash.slice(0,16)}...`,` Parents: ${s.parentIds.length} | Roots: ${s.rootIds.length}`].join(`
1736
1766
  `)}if(r==="get"&&e.entry_id){let s=n.getEntry(String(e.entry_id));return s?n.formatEntry(s):"Entry not found"}if(r==="lineage"&&e.entry_id){let s=n.getLineage(String(e.entry_id));if(!s)return"Entry not found";let i=(o,a=0)=>{let c=[`${" ".repeat(a)}- ${o.entry.sourceType} (${o.entry.trustLevel}, trust=${o.entry.trustScore.toFixed(2)}) | "${o.entry.contentPreview.slice(0,50)}..."`];for(let l of o.parents)c.push(...i(l,a+1));return c};return i(s).join(`
1737
1767
  `)}if(r==="descendants"&&e.entry_id){let s=n.getDescendants(String(e.entry_id));return s.length===0?"No descendants":s.map(i=>` ${i.id} | ${i.sourceType} | "${i.contentPreview.slice(0,50)}..."`).join(`
1738
1768
  `)}if(r==="extract_citations"&&e.output_text){let s=n.extractCitations(String(e.output_text),e.session_id);return s.length===0?"No citations matched":s.map(i=>[`Citation: "${i.text.slice(0,80)}..."`,` Trust: ${i.trustScore.toFixed(2)}`,` Provenance chain (${i.provenanceChain.length} hops):`,n.formatProvenanceChain(i.provenanceChain).split(`
@@ -1744,18 +1774,18 @@ ${i.issues.map(o=>` - ${o}`).join(`
1744
1774
  `)}if(r==="most_cited"){let s=n.getMostCited(15);return s.length===0?"No citations yet":s.map(i=>` ${i.id} | ${i.sourceType.padEnd(15)} | ${i.citationCount} citations | trust=${i.trustScore.toFixed(2)} | "${i.contentPreview.slice(0,50)}..."`).join(`
1745
1775
  `)}if(r==="stats"){let s=n.getStats();return["Provenance Tracker Stats:",` Total entries: ${s.totalEntries}`,` Total citations: ${s.totalCitations}`,` Untrusted rejected: ${s.totalUntrustedRejected}`,` Signatures verified: ${s.totalSignaturesVerified}`,` Signature failures: ${s.totalSignatureFailures}`,"","By source type:",...Object.entries(s.bySourceType).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i.padEnd(20)} ${o}`),"","By trust level:",...Object.entries(s.byTrustLevel).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i.padEnd(15)} ${o}`)].join(`
1746
1776
  `)}if(r==="list"){let s=n.listEntries({sourceType:e.source_type,sessionId:e.session_id||t.session?.id,limit:30});return s.length===0?"No entries":s.map(i=>` ${i.id} | ${i.sourceType.padEnd(15)} | ${i.trustLevel.padEnd(11)} | trust=${i.trustScore.toFixed(2)} | ${i.contentLength} chars`).join(`
1747
- `)}return r==="report"?n.generateComplianceReport(e.session_id):`Unknown action: ${r}`}},c5={definition:{name:"memory_audit_log",description:"Append-only cryptographic ledger of all memory writes. Hash-chained, signed entries. SOC2/HIPAA compliant.",parameters:[{name:"action",type:"string",description:"search | recent | verify | replay | archives | rotate | compress | cleanup | stats | report",required:!0},{name:"source",type:"string",description:"Filter by source for search",required:!1},{name:"operation",type:"string",description:"Filter by operation",required:!1},{name:"session_id",type:"string",description:"Filter by session",required:!1},{name:"agent_id",type:"string",description:"Filter by agent",required:!1},{name:"file_path",type:"string",description:"Filter by file path",required:!1},{name:"limit",type:"number",description:"Max results (default 50)",required:!1},{name:"search_archives",type:"boolean",description:"Search compressed archives too",required:!1},{name:"start_time",type:"number",description:"Start time (epoch ms) for replay",required:!1},{name:"end_time",type:"number",description:"End time (epoch ms) for replay",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(su(),ru)),r=String(e.action);if(r==="search"){let s=n.searchEntries({source:e.source,operation:e.operation,sessionId:e.session_id,agentId:e.agent_id,filePath:e.file_path,limit:e.limit||50,searchArchives:!!e.search_archives});return s.length===0?"No matching entries.":s.map(i=>`#${i.sequenceNumber} | ${new Date(i.timestamp).toISOString()} | ${i.source}/${i.operation} | ${i.filePath||i.storeId||""} | ${i.contentLength}c${i.isSuspicious?" \u{1F6A8}":""}`).join(`
1777
+ `)}return r==="report"?n.generateComplianceReport(e.session_id):`Unknown action: ${r}`}},cq={definition:{name:"memory_audit_log",description:"Append-only cryptographic ledger of all memory writes. Hash-chained, signed entries. SOC2/HIPAA compliant.",parameters:[{name:"action",type:"string",description:"search | recent | verify | replay | archives | rotate | compress | cleanup | stats | report",required:!0},{name:"source",type:"string",description:"Filter by source for search",required:!1},{name:"operation",type:"string",description:"Filter by operation",required:!1},{name:"session_id",type:"string",description:"Filter by session",required:!1},{name:"agent_id",type:"string",description:"Filter by agent",required:!1},{name:"file_path",type:"string",description:"Filter by file path",required:!1},{name:"limit",type:"number",description:"Max results (default 50)",required:!1},{name:"search_archives",type:"boolean",description:"Search compressed archives too",required:!1},{name:"start_time",type:"number",description:"Start time (epoch ms) for replay",required:!1},{name:"end_time",type:"number",description:"End time (epoch ms) for replay",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(su(),ru)),r=String(e.action);if(r==="search"){let s=n.searchEntries({source:e.source,operation:e.operation,sessionId:e.session_id,agentId:e.agent_id,filePath:e.file_path,limit:e.limit||50,searchArchives:!!e.search_archives});return s.length===0?"No matching entries.":s.map(i=>`#${i.sequenceNumber} | ${new Date(i.timestamp).toISOString()} | ${i.source}/${i.operation} | ${i.filePath||i.storeId||""} | ${i.contentLength}c${i.isSuspicious?" \u{1F6A8}":""}`).join(`
1748
1778
  `)}if(r==="recent")return n.searchEntries({limit:e.limit||30}).map(i=>n.formatEntry(i)).join(`
1749
1779
 
1750
1780
  `);if(r==="verify"){let s=await n.verifyChain();return["Chain verification:",` ${s.valid?"\u2713 VALID":"\u{1F6A8} INVALID"}`,` Total entries: ${s.totalEntries}`,` Valid entries: ${s.validEntries}`,` Broken links: ${s.brokenLinks.length}`,` Signature failures: ${s.signatureFailures.length}`,...s.brokenLinks.length>0?["","Broken links:",...s.brokenLinks.slice(0,5).map(i=>` seq ${i.sequenceNumber}: ${i.reason}`)]:[]].join(`
1751
1781
  `)}if(r==="replay"){let s=await n.forensicReplay({startTime:e.start_time,endTime:e.end_time});return["Forensic Replay:",` Total entries: ${s.totalEntries}`,` Time range: ${new Date(s.timeRange.start).toISOString()} \u2192 ${new Date(s.timeRange.end).toISOString()}`,` Chain valid: ${s.chainValid?"\u2713":"\u{1F6A8} NO"}`,` Files affected: ${s.uniqueFiles.length}`,` Agents involved: ${s.uniqueAgents.length}`,"","By source:",...Object.entries(s.bySource).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`)].join(`
1752
1782
  `)}if(r==="archives"){let s=n.listArchives();return s.length===0?"No archives.":s.slice(0,30).map(i=>` ${i.name} | ${(i.size/1024).toFixed(1)}KB${i.compressed?" (gzip)":""} | ${new Date(i.mtime).toISOString()}`).join(`
1753
1783
  `)}if(r==="rotate")return await n.manualRotate(),"\u2713 Log rotated";if(r==="compress")return`\u2713 Compressed ${(await n.manualCompress()).compressed} archives`;if(r==="cleanup")return`\u2713 Deleted ${n.manualCleanup().deleted} expired archives`;if(r==="stats"){let s=n.getStats(),i=n.getState();return["Memory Audit Log Stats:",` Total entries: ${s.totalEntries}`,` Current sequence: ${i.sequenceNumber}`,` Rotations: ${s.totalRotations}`,` Compressions: ${s.totalCompressions}`,` Suspicious writes: ${s.totalSuspicious}`,` Anomalies: ${s.totalAnomalies}`,` Chain breaks: ${s.totalChainBreaks}`,"","By source:",...Object.entries(s.bySource).sort((o,a)=>a[1]-o[1]).slice(0,10).map(([o,a])=>` ${o}: ${a}`)].join(`
1754
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},l5={definition:{name:"data_purge",description:"Zero-fill all in-memory sensitive data (conversation, credentials, tools, etc.) on session end. Anti-recovery protection.",parameters:[{name:"action",type:"string",description:"purge | stats | handlers | audit | report | activity | verify",required:!0},{name:"depth",type:"string",description:"Purge depth: light | standard | paranoid",required:!1},{name:"trigger",type:"string",description:"Trigger: manual | explicit_exit",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Wu(),Ju)),r=String(e.action);if(r==="purge"){let s=await n.purge(e.trigger||"manual",e.depth||n.getConfig().defaultDepth);return n.formatPurgeResult(s)}if(r==="stats"){let s=n.getStats();return["Purge Stats:",` Total purges: ${s.totalPurges}`,` Total items cleaned: ${s.totalItemsCleaned}`,` Total bytes scrubbed: ${(s.totalBytesScrubbed/1024).toFixed(1)}KB`,` Verification failures: ${s.totalVerificationFailures}`,` Avg duration: ${s.averageDurationMs.toFixed(1)}ms`,` Last purge: ${s.lastPurgeAt?new Date(s.lastPurgeAt).toISOString():"never"}`,"","By trigger:",...Object.entries(s.byTrigger).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`)].join(`
1784
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},lq={definition:{name:"data_purge",description:"Zero-fill all in-memory sensitive data (conversation, credentials, tools, etc.) on session end. Anti-recovery protection.",parameters:[{name:"action",type:"string",description:"purge | stats | handlers | audit | report | activity | verify",required:!0},{name:"depth",type:"string",description:"Purge depth: light | standard | paranoid",required:!1},{name:"trigger",type:"string",description:"Trigger: manual | explicit_exit",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Wu(),Ju)),r=String(e.action);if(r==="purge"){let s=await n.purge(e.trigger||"manual",e.depth||n.getConfig().defaultDepth);return n.formatPurgeResult(s)}if(r==="stats"){let s=n.getStats();return["Purge Stats:",` Total purges: ${s.totalPurges}`,` Total items cleaned: ${s.totalItemsCleaned}`,` Total bytes scrubbed: ${(s.totalBytesScrubbed/1024).toFixed(1)}KB`,` Verification failures: ${s.totalVerificationFailures}`,` Avg duration: ${s.averageDurationMs.toFixed(1)}ms`,` Last purge: ${s.lastPurgeAt?new Date(s.lastPurgeAt).toISOString():"never"}`,"","By trigger:",...Object.entries(s.byTrigger).sort((i,o)=>o[1]-i[1]).map(([i,o])=>` ${i}: ${o}`)].join(`
1755
1785
  `)}if(r==="handlers")return n.listRegistrations().sort((i,o)=>(o.priority||0)-(i.priority||0)).map(i=>` [P${i.priority||0}] ${i.target.padEnd(25)} ${i.description||""}`).join(`
1756
1786
  `);if(r==="audit"){let s=n.getAuditLog(20);return s.length===0?"No audit entries.":s.map(i=>`${new Date(i.timestamp).toISOString().slice(11,19)} | ${i.trigger.padEnd(15)} | ${i.depth.padEnd(10)} | ${i.totalItems} items | ${i.durationMs}ms${i.success?" \u2713":" \u26A0\uFE0F"}`).join(`
1757
1787
  `)}if(r==="activity")return n.recordActivity(),"\u2713 Activity recorded (resets idle timer)";if(r==="report")return n.generateComplianceReport();if(r==="verify"){let s=await n.purge("manual","light");return["Verification result:",` Passes: ${s.verificationPasses?"\u2713":"\u26A0\uFE0F"}`,...s.warnings.length>0?["Warnings:",...s.warnings.map(i=>` - ${i}`)]:["No warnings."]].join(`
1758
- `)}return`Unknown action: ${r}`}},u5={definition:{name:"plugin_signature",description:"Manage plugin/MCP cryptographic signatures. Pin trusted publisher keys, verify plugins, revoke compromised keys, run runtime attestation.",parameters:[{name:"action",type:"string",description:"verify | pin_key | revoke_key | list_keys | list_installed | sign_manifest | generate_keypair | attestation | stats | report",required:!0},{name:"plugin_path",type:"string",description:"Plugin directory for verify",required:!1},{name:"publisher_id",type:"string",description:"Publisher ID for pin/revoke",required:!1},{name:"publisher_name",type:"string",description:"Publisher display name",required:!1},{name:"public_key",type:"string",description:"Public key PEM",required:!1},{name:"algorithm",type:"string",description:"ed25519 | rsa-sha256 | ecdsa-p256-sha256",required:!1},{name:"trust_level",type:"string",description:"root | official | verified | community",required:!1},{name:"reason",type:"string",description:"Reason for revoke",required:!1},{name:"manifest",type:"object",description:"Manifest for sign",required:!1},{name:"private_key",type:"string",description:"Private key PEM for sign",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Sb(),vb)),r=String(e.action);if(r==="verify"&&e.plugin_path){let s=n.verifyPlugin(String(e.plugin_path));return n.formatVerificationResult(s)}if(r==="pin_key"&&e.publisher_id&&e.public_key){let s=n.pinPublicKey({publisherId:String(e.publisher_id),publisherName:String(e.publisher_name||e.publisher_id),publicKeyPem:String(e.public_key),algorithm:e.algorithm||"ed25519",trustLevel:e.trust_level||"community"});return["\u2713 Public key pinned",` Publisher: ${s.publisherName} (${s.publisherId})`,` Fingerprint: ${s.fingerprint.slice(0,32)}...`,` Algorithm: ${s.algorithm}`,` Trust: ${s.trustLevel}`].join(`
1788
+ `)}return`Unknown action: ${r}`}},uq={definition:{name:"plugin_signature",description:"Manage plugin/MCP cryptographic signatures. Pin trusted publisher keys, verify plugins, revoke compromised keys, run runtime attestation.",parameters:[{name:"action",type:"string",description:"verify | pin_key | revoke_key | list_keys | list_installed | sign_manifest | generate_keypair | attestation | stats | report",required:!0},{name:"plugin_path",type:"string",description:"Plugin directory for verify",required:!1},{name:"publisher_id",type:"string",description:"Publisher ID for pin/revoke",required:!1},{name:"publisher_name",type:"string",description:"Publisher display name",required:!1},{name:"public_key",type:"string",description:"Public key PEM",required:!1},{name:"algorithm",type:"string",description:"ed25519 | rsa-sha256 | ecdsa-p256-sha256",required:!1},{name:"trust_level",type:"string",description:"root | official | verified | community",required:!1},{name:"reason",type:"string",description:"Reason for revoke",required:!1},{name:"manifest",type:"object",description:"Manifest for sign",required:!1},{name:"private_key",type:"string",description:"Private key PEM for sign",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Sb(),vb)),r=String(e.action);if(r==="verify"&&e.plugin_path){let s=n.verifyPlugin(String(e.plugin_path));return n.formatVerificationResult(s)}if(r==="pin_key"&&e.publisher_id&&e.public_key){let s=n.pinPublicKey({publisherId:String(e.publisher_id),publisherName:String(e.publisher_name||e.publisher_id),publicKeyPem:String(e.public_key),algorithm:e.algorithm||"ed25519",trustLevel:e.trust_level||"community"});return["\u2713 Public key pinned",` Publisher: ${s.publisherName} (${s.publisherId})`,` Fingerprint: ${s.fingerprint.slice(0,32)}...`,` Algorithm: ${s.algorithm}`,` Trust: ${s.trustLevel}`].join(`
1759
1789
  `)}if(r==="revoke_key"&&e.publisher_id)return n.revokeKey(String(e.publisher_id),String(e.reason||"manual revoke"))?`\u2713 Revoked publisher ${e.publisher_id}`:"Publisher not found";if(r==="list_keys"){let s=n.listPinnedKeys();return s.length===0?"No pinned keys.":s.map(i=>` ${i.revoked?"\u{1F534} REVOKED":i.trustLevel==="root"?"\u{1F7E2} root":i.trustLevel==="official"?"\u{1F535} official":i.trustLevel==="verified"?"\u{1F7E1} verified":"\u26AA community"} ${i.publisherName.padEnd(25)} | ${i.algorithm.padEnd(20)} | fp=${i.fingerprint.slice(0,16)}...`).join(`
1760
1790
  `)}if(r==="list_installed"){let s=n.listInstallations();return s.length===0?"No installed plugins.":s.map(i=>` ${i.status==="verified"?"\u{1F7E2}":i.status==="revoked"?"\u{1F534}":i.status==="tampered"?"\u{1F6A8}":"\u{1F7E1}"} ${i.manifest.name.padEnd(20)} v${i.manifest.version.padEnd(10)} | ${i.status} | by ${i.manifest.publisherId}`).join(`
1761
1791
  `)}if(r==="generate_keypair"){let s=e.algorithm||"ed25519",i=n.generateKeyPair(s);return[`Generated ${s} keypair`,"","Public key:",i.publicKey,"Private key:","[redacted - returned in tool args directly to caller]","",`Fingerprint: ${n.fingerprint(i.publicKey).slice(0,32)}...`].join(`
@@ -1763,7 +1793,7 @@ ${i.issues.map(o=>` - ${o}`).join(`
1763
1793
  Signature: ${n.signManifest(e.manifest,String(e.private_key),s).slice(0,64)}...
1764
1794
  Algorithm: ${s}`}catch(i){return`Error signing: ${i.message}`}}if(r==="attestation"){let s=await n.runAttestation();return["Runtime attestation:",` Checked: ${s.checked}`,` Failed: ${s.failed}`,...s.failures.length>0?["Failures:",...s.failures.slice(0,10).map(i=>` - ${i}`)]:["All passed."]].join(`
1765
1795
  `)}if(r==="stats"){let s=n.getStats();return["Plugin Signature Stats:",` Verifications: ${s.totalVerifications}`,` Verified: ${s.totalVerified}`,` Rejected: ${s.totalRejected}`,` Quarantined: ${s.totalQuarantined}`,` Revoked: ${s.totalRevoked}`,` Unsigned: ${s.totalUnsigned}`,` Tampered: ${s.totalTampered}`].join(`
1766
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},d5={definition:{name:"mcp_allowlist",description:"Manage MCP server allowlist and TLS certificate pinning. Reject connections to unknown servers or with changed certs.",parameters:[{name:"action",type:"string",description:"list | add | remove | reject | verify | probe | rotate | endpoint | recent | stats | report",required:!0},{name:"url",type:"string",description:"MCP server URL",required:!1},{name:"command",type:"string",description:"MCP server command",required:!1},{name:"connection_type",type:"string",description:"stdio | http | https | ws | wss",required:!1},{name:"pinned_fingerprints",type:"array",description:"SHA-256 fingerprints (hex) for pinning",required:!1},{name:"trust_level",type:"string",description:"official | verified | community",required:!1},{name:"description",type:"string",description:"Description for endpoint",required:!1},{name:"allow_subdomains",type:"boolean",description:"Allow subdomain matches",required:!1},{name:"endpoint_id",type:"string",description:"Endpoint ID for remove/reject/rotate",required:!1},{name:"reason",type:"string",description:"Reason for reject",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Tb(),Ab)),r=String(e.action);if(r==="list"){let s=n.listEndpoints();return s.length===0?"No allowed endpoints.":s.map(i=>n.formatEndpoint(i)).join(`
1796
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},dq={definition:{name:"mcp_allowlist",description:"Manage MCP server allowlist and TLS certificate pinning. Reject connections to unknown servers or with changed certs.",parameters:[{name:"action",type:"string",description:"list | add | remove | reject | verify | probe | rotate | endpoint | recent | stats | report",required:!0},{name:"url",type:"string",description:"MCP server URL",required:!1},{name:"command",type:"string",description:"MCP server command",required:!1},{name:"connection_type",type:"string",description:"stdio | http | https | ws | wss",required:!1},{name:"pinned_fingerprints",type:"array",description:"SHA-256 fingerprints (hex) for pinning",required:!1},{name:"trust_level",type:"string",description:"official | verified | community",required:!1},{name:"description",type:"string",description:"Description for endpoint",required:!1},{name:"allow_subdomains",type:"boolean",description:"Allow subdomain matches",required:!1},{name:"endpoint_id",type:"string",description:"Endpoint ID for remove/reject/rotate",required:!1},{name:"reason",type:"string",description:"Reason for reject",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Tb(),Ab)),r=String(e.action);if(r==="list"){let s=n.listEndpoints();return s.length===0?"No allowed endpoints.":s.map(i=>n.formatEndpoint(i)).join(`
1767
1797
 
1768
1798
  `)}if(r==="add"&&(e.url||e.command)){let s=e.pinned_fingerprints||[];if(e.url&&s.length===0){let o=await n.probeCertificate(String(e.url));o&&(s=[o.fingerprint])}let i=n.addEndpoint({url:e.url,command:e.command,type:e.connection_type||(e.url?"https":"stdio"),pinnedFingerprints:s,trustLevel:e.trust_level||"community",description:e.description,allowSubdomains:!!e.allow_subdomains,approvedBy:"agent"});return`\u2713 Endpoint added
1769
1799
  ${n.formatEndpoint(i)}`}if(r==="remove"&&e.endpoint_id)return n.removeEndpoint(String(e.endpoint_id))?`\u2713 Removed ${e.endpoint_id}`:"Not found";if(r==="reject"&&e.endpoint_id)return n.rejectEndpoint(String(e.endpoint_id),String(e.reason||"manual reject"))?`\u2713 Rejected ${e.endpoint_id}`:"Not found";if(r==="verify"&&(e.url||e.command)){let s=await n.verifyConnection({url:e.url,command:e.command,type:e.connection_type||"stdio"});return[`${s.decision==="allow"?"\u2713":s.decision==="reject"?"\u{1F6AB}":s.decision==="quarantine"?"\u{1F512}":"\u23F3"} ${s.decision.toUpperCase()}`,`Reason: ${s.reason}`,`Risk: ${(s.riskScore*100).toFixed(0)}/100`,...s.anomalies.length>0?[`Anomalies: ${s.anomalies.join(", ")}`]:[]].join(`
@@ -1772,15 +1802,15 @@ ${n.formatEndpoint(i)}`}if(r==="remove"&&e.endpoint_id)return n.removeEndpoint(S
1772
1802
  Old: ${(s.oldFp||"").slice(0,32)}...
1773
1803
  New: ${(s.newFp||"").slice(0,32)}...`:`Failed: ${s.reason}`}if(r==="endpoint"&&e.endpoint_id){let s=n.getEndpoint(String(e.endpoint_id));return s?n.formatEndpoint(s):"Not found"}if(r==="recent"){let s=n.getRecentAttempts(20);return s.length===0?"No recent attempts.":s.map(i=>` ${new Date(i.timestamp).toISOString().slice(11,19)} | ${i.decision.padEnd(11)} | ${i.url||i.command} | ${i.reason}`).join(`
1774
1804
  `)}if(r==="stats"){let s=n.getStats();return["MCP Allowlist Stats:",` Total attempts: ${s.totalConnectionAttempts}`,` Allowed: ${s.totalAllowed}`,` Rejected: ${s.totalRejected}`,` Quarantined: ${s.totalQuarantined}`,` Cert rotations: ${s.totalCertRotations}`,` Anomalies: ${s.totalAnomalies}`].join(`
1775
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},f5={definition:{name:"dep_audit",description:"Lock dependencies to exact versions with SHA-256 hashes. Audit for malicious packages, CVEs, typosquats. Reproducible builds.",parameters:[{name:"action",type:"string",description:"audit | lock | verify | mark_malicious | report | stats",required:!0},{name:"project_path",type:"string",description:"Project path (default: cwd)",required:!1},{name:"package_name",type:"string",description:"Package name for mark_malicious",required:!1},{name:"package_version",type:"string",description:"Package version for mark_malicious",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(xh(),kh)),r=String(e.action),s=e.project_path||t.cwd;if(r==="audit"){let i=await n.auditDependencies(s);return n.formatAuditResult(i)}if(r==="lock"){let i=await n.generateLockfile(s);return i?["\u2713 Lockfile generated",` Project: ${i.projectName}`,` Ecosystem: ${i.ecosystem}`,` Dependencies: ${Object.keys(i.dependencies).length}`,` Lockfile hash: ${i.lockfileHash.slice(0,32)}...`].join(`
1805
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},fq={definition:{name:"dep_audit",description:"Lock dependencies to exact versions with SHA-256 hashes. Audit for malicious packages, CVEs, typosquats. Reproducible builds.",parameters:[{name:"action",type:"string",description:"audit | lock | verify | mark_malicious | report | stats",required:!0},{name:"project_path",type:"string",description:"Project path (default: cwd)",required:!1},{name:"package_name",type:"string",description:"Package name for mark_malicious",required:!1},{name:"package_version",type:"string",description:"Package version for mark_malicious",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(xh(),kh)),r=String(e.action),s=e.project_path||t.cwd;if(r==="audit"){let i=await n.auditDependencies(s);return n.formatAuditResult(i)}if(r==="lock"){let i=await n.generateLockfile(s);return i?["\u2713 Lockfile generated",` Project: ${i.projectName}`,` Ecosystem: ${i.ecosystem}`,` Dependencies: ${Object.keys(i.dependencies).length}`,` Lockfile hash: ${i.lockfileHash.slice(0,32)}...`].join(`
1776
1806
  `):"Could not detect ecosystem or generate lockfile"}if(r==="verify"){let i=n.verifyLockfileMatchesInstall(s);return["Lockfile verification:",` Matches: ${i.matches?"\u2713":"\u{1F6A8} MISMATCH"}`,` Expected: ${i.expectedHash?.slice(0,16)}...`,` Actual: ${i.actualHash?.slice(0,16)}...`,...i.missingFromLock.length>0?[` Missing from lock: ${i.missingFromLock.length}`]:[],...i.extraInLock.length>0?[` Extra in lock: ${i.extraInLock.length}`]:[]].join(`
1777
1807
  `)}if(r==="mark_malicious"&&e.package_name)return n.addMalicious(String(e.package_name),e.package_version),`\u2713 Marked ${e.package_name}${e.package_version?"@"+e.package_version:""} as known-malicious`;if(r==="stats"){let i=n.getStats();return["Dependency Audit Stats:",` Total audits: ${i.totalAudits}`,` Packages scanned: ${i.totalPackagesScanned}`,` Vulnerabilities: ${i.totalVulnerabilities}`,` Malicious: ${i.totalMalicious}`,` Typosquats: ${i.totalTyposquats}`,` Unlocked: ${i.totalUnlocked}`,` Lockfiles generated: ${i.totalLockfilesGenerated}`].join(`
1778
- `)}return r==="report"?n.generateComplianceReport(s):`Unknown action: ${r}`}},p5={definition:{name:"plugin_sandbox",description:"Run plugins in isolated sandboxes with capability-based permissions. Hard memory/CPU limits, auto-restart, quarantine on misbehavior.",parameters:[{name:"action",type:"string",description:"start | stop | restart | call | grant | revoke | list | quarantine | health | stats | report",required:!0},{name:"plugin_id",type:"string",description:"Plugin ID",required:!1},{name:"manifest",type:"object",description:"Plugin manifest for start",required:!1},{name:"method",type:"string",description:"Method to call",required:!1},{name:"params",type:"object",description:"Method params",required:!1},{name:"capability",type:"string",description:"Capability for grant/revoke",required:!1},{name:"reason",type:"string",description:"Reason for quarantine",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(gb(),mb)),r=String(e.action);if(r==="start"&&e.manifest)try{let s=await n.startPlugin(e.manifest);return["\u2713 Plugin started",n.formatPlugin(s)].join(`
1808
+ `)}return r==="report"?n.generateComplianceReport(s):`Unknown action: ${r}`}},pq={definition:{name:"plugin_sandbox",description:"Run plugins in isolated sandboxes with capability-based permissions. Hard memory/CPU limits, auto-restart, quarantine on misbehavior.",parameters:[{name:"action",type:"string",description:"start | stop | restart | call | grant | revoke | list | quarantine | health | stats | report",required:!0},{name:"plugin_id",type:"string",description:"Plugin ID",required:!1},{name:"manifest",type:"object",description:"Plugin manifest for start",required:!1},{name:"method",type:"string",description:"Method to call",required:!1},{name:"params",type:"object",description:"Method params",required:!1},{name:"capability",type:"string",description:"Capability for grant/revoke",required:!1},{name:"reason",type:"string",description:"Reason for quarantine",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(gb(),mb)),r=String(e.action);if(r==="start"&&e.manifest)try{let s=await n.startPlugin(e.manifest);return["\u2713 Plugin started",n.formatPlugin(s)].join(`
1779
1809
  `)}catch(s){return`Error: ${s.message}`}if(r==="stop"&&e.plugin_id)return await n.stopPlugin(String(e.plugin_id))?`\u2713 Stopped ${e.plugin_id}`:"Not found";if(r==="restart"&&e.plugin_id)return await n.restartPlugin(String(e.plugin_id))?`\u2713 Restarted ${e.plugin_id}`:"Not found";if(r==="call"&&e.plugin_id&&e.method){let s=await n.callPlugin({pluginId:String(e.plugin_id),method:String(e.method),params:e.params});return[`${s.success?"\u2713":"\u{1F6AB}"} ${s.success?"Success":"Failed"}`,`Duration: ${s.durationMs}ms`,s.success?`Result: ${JSON.stringify(s.result).slice(0,200)}`:`Error: ${s.error}`,...s.capabilitiesUsed.length>0?[`Capabilities used: ${s.capabilitiesUsed.join(", ")}`]:[]].join(`
1780
1810
  `)}if(r==="grant"&&e.plugin_id&&e.capability)return n.grantCapability(String(e.plugin_id),e.capability,"agent")?`\u2713 Granted "${e.capability}" to ${e.plugin_id}`:"Failed (forbidden capability?)";if(r==="revoke"&&e.plugin_id&&e.capability)return n.revokeCapability(String(e.plugin_id),e.capability)?`\u2713 Revoked "${e.capability}" from ${e.plugin_id}`:"Not found";if(r==="list"){let s=n.listPlugins();return s.length===0?"No plugins running.":s.map(i=>n.formatPlugin(i)).join(`
1781
1811
 
1782
1812
  `)}if(r==="quarantine"&&e.plugin_id)return n.quarantinePlugin(String(e.plugin_id),String(e.reason||"manual"))?`\u{1F512} Quarantined ${e.plugin_id}`:"Not found";if(r==="stats"){let s=n.getStats();return["Plugin Sandbox Stats:",` Total starts: ${s.totalStarted}`,` Total requests: ${s.totalRequests}`,` Total crashes: ${s.totalCrashes}`,` Total quarantined: ${s.totalQuarantined}`,` Total restarts: ${s.totalRestarts}`,` Capability denials: ${s.totalCapabilityDenials}`].join(`
1783
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},m5={definition:{name:"audit_trail",description:"Tamper-evident append-only audit log. Hash-chained entries, signed, exportable for compliance.",parameters:[{name:"action",type:"string",description:"log | search | recent | verify | replay | checkpoints | export | rotate | archives | stats | report",required:!0},{name:"category",type:"string",description:"Event category",required:!1},{name:"severity",type:"string",description:"info | low | medium | high | critical",required:!1},{name:"description",type:"string",description:"Event description for log",required:!1},{name:"resource",type:"string",description:"Resource for log/filter",required:!1},{name:"actor",type:"string",description:"Actor",required:!1},{name:"session_id",type:"string",description:"Session ID",required:!1},{name:"limit",type:"number",description:"Max results",required:!1},{name:"search_archives",type:"boolean",description:"Include compressed archives",required:!1},{name:"format",type:"string",description:"Export format: jsonl | csv | markdown | ndjson",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(gd(),md)),r=String(e.action);if(r==="log"&&e.category&&e.description){let s=n.logEvent({category:e.category,severity:e.severity||"info",actor:e.actor||t.session?.id||"agent",sessionId:e.session_id||t.session?.id,resource:e.resource,description:String(e.description)});return`\u2713 Logged event #${s.sequenceNumber} (${s.id})`}if(r==="search"){let s=n.search({category:e.category,severity:e.severity,actor:e.actor,resource:e.resource,sessionId:e.session_id,limit:e.limit||50,searchArchives:!!e.search_archives});return s.length===0?"No matching events.":s.map(i=>`#${i.sequenceNumber} | ${new Date(i.timestamp).toISOString().slice(0,19)} | ${i.severity.padEnd(8)} | ${i.category.padEnd(20)} | ${i.actor.padEnd(15)} | ${i.description.slice(0,60)}`).join(`
1813
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},mq={definition:{name:"audit_trail",description:"Tamper-evident append-only audit log. Hash-chained entries, signed, exportable for compliance.",parameters:[{name:"action",type:"string",description:"log | search | recent | verify | replay | checkpoints | export | rotate | archives | stats | report",required:!0},{name:"category",type:"string",description:"Event category",required:!1},{name:"severity",type:"string",description:"info | low | medium | high | critical",required:!1},{name:"description",type:"string",description:"Event description for log",required:!1},{name:"resource",type:"string",description:"Resource for log/filter",required:!1},{name:"actor",type:"string",description:"Actor",required:!1},{name:"session_id",type:"string",description:"Session ID",required:!1},{name:"limit",type:"number",description:"Max results",required:!1},{name:"search_archives",type:"boolean",description:"Include compressed archives",required:!1},{name:"format",type:"string",description:"Export format: jsonl | csv | markdown | ndjson",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(gd(),md)),r=String(e.action);if(r==="log"&&e.category&&e.description){let s=n.logEvent({category:e.category,severity:e.severity||"info",actor:e.actor||t.session?.id||"agent",sessionId:e.session_id||t.session?.id,resource:e.resource,description:String(e.description)});return`\u2713 Logged event #${s.sequenceNumber} (${s.id})`}if(r==="search"){let s=n.search({category:e.category,severity:e.severity,actor:e.actor,resource:e.resource,sessionId:e.session_id,limit:e.limit||50,searchArchives:!!e.search_archives});return s.length===0?"No matching events.":s.map(i=>`#${i.sequenceNumber} | ${new Date(i.timestamp).toISOString().slice(0,19)} | ${i.severity.padEnd(8)} | ${i.category.padEnd(20)} | ${i.actor.padEnd(15)} | ${i.description.slice(0,60)}`).join(`
1784
1814
  `)}if(r==="recent")return n.search({limit:e.limit||30}).map(i=>n.formatEvent(i)).join(`
1785
1815
 
1786
1816
  `);if(r==="verify"){let s=await n.verifyChain();return["Chain verification:",` ${s.valid?"\u2713 VALID":"\u{1F6A8} INVALID"}`,` Total entries: ${s.totalEntries}`,` Valid: ${s.validEntries}`,` Broken links: ${s.brokenLinks.length}`,` Signature failures: ${s.signatureFailures}`,` Duration: ${s.durationMs}ms`].join(`
@@ -1790,60 +1820,60 @@ ${n.formatEndpoint(i)}`}if(r==="remove"&&e.endpoint_id)return n.removeEndpoint(S
1790
1820
  Path: ${i.path}
1791
1821
  Format: ${s}`}if(r==="rotate")return await n.manualRotate(),"\u2713 Log rotated";if(r==="archives"){let s=n.listArchives();return s.length===0?"No archives.":s.slice(0,30).map(i=>` ${i.name} | ${(i.size/1024).toFixed(1)}KB${i.compressed?" (gzip)":""}`).join(`
1792
1822
  `)}if(r==="stats"){let s=n.getStats(),i=n.getState();return["Audit Trail Stats:",` Total events: ${s.totalEvents}`,` Current sequence: ${i.sequenceNumber}`,` Rotations: ${s.totalRotations}`,` Compressions: ${s.totalCompressions}`,` Checkpoints: ${s.totalCheckpoints}`,` Anomalies: ${s.totalAnomalies}`,` Chain breaks: ${s.totalChainBreaks}`,` Verifications: ${s.totalVerifications}`,` Exports: ${s.totalExports}`].join(`
1793
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},g5={definition:{name:"action_reversibility",description:"Classify actions as reversible/irreversible/destructive. Block destructive ops; require confirmation for irreversible ops.",parameters:[{name:"action",type:"string",description:"classify | decide | rules | confirm | stats | report",required:!0},{name:"tool_name",type:"string",description:"Tool name to classify",required:!1},{name:"input",type:"object",description:"Tool input args",required:!1},{name:"trust_score",type:"number",description:"Agent trust score for bypass",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(mv(),pv)),r=String(e.action);if(r==="classify"&&e.tool_name){let s=n.classify(String(e.tool_name),e.input||{});return n.formatClassification(s)}if(r==="decide"&&e.tool_name){let s=n.decide(String(e.tool_name),e.input||{},{trustScore:e.trust_score});return[`${s.allowed&&!s.needsConfirmation?"\u2713":s.needsConfirmation?"\u23F3":"\u{1F6AB}"} ${s.allowed?"Allowed":s.needsConfirmation?"Needs confirmation":"Blocked"}`,`Reason: ${s.reason}`,"",n.formatClassification(s.classification)].join(`
1823
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},gq={definition:{name:"action_reversibility",description:"Classify actions as reversible/irreversible/destructive. Block destructive ops; require confirmation for irreversible ops.",parameters:[{name:"action",type:"string",description:"classify | decide | rules | confirm | stats | report",required:!0},{name:"tool_name",type:"string",description:"Tool name to classify",required:!1},{name:"input",type:"object",description:"Tool input args",required:!1},{name:"trust_score",type:"number",description:"Agent trust score for bypass",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(mv(),pv)),r=String(e.action);if(r==="classify"&&e.tool_name){let s=n.classify(String(e.tool_name),e.input||{});return n.formatClassification(s)}if(r==="decide"&&e.tool_name){let s=n.decide(String(e.tool_name),e.input||{},{trustScore:e.trust_score});return[`${s.allowed&&!s.needsConfirmation?"\u2713":s.needsConfirmation?"\u23F3":"\u{1F6AB}"} ${s.allowed?"Allowed":s.needsConfirmation?"Needs confirmation":"Blocked"}`,`Reason: ${s.reason}`,"",n.formatClassification(s.classification)].join(`
1794
1824
  `)}if(r==="rules")return n.listRules().map(i=>` [P${i.priority}] ${i.id.padEnd(25)} | ${i.reversibility.padEnd(13)} | ${i.description}`).join(`
1795
1825
  `);if(r==="confirm"&&e.tool_name&&e.input)return n.recordConfirmation(String(e.tool_name),e.input),"\u2713 Confirmation cached";if(r==="stats"){let s=n.getStats();return["Reversibility Classifier Stats:",` Total classifications: ${s.totalClassifications}`,` \u{1F7E2} Reversible: ${s.totalReversible}`,` \u{1F7E1} Conditional: ${s.totalConditional}`,` \u{1F7E0} Irreversible: ${s.totalIrreversible}`,` \u{1F534} Destructive: ${s.totalDestructive}`,"","Confirmation:",` Requested: ${s.totalConfirmationRequested}`,` Granted: ${s.totalConfirmationGranted}`,` Denied: ${s.totalConfirmationDenied}`,` Auto-bypassed: ${s.totalAutoBypassed}`,` Rejected: ${s.totalRejected}`].join(`
1796
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},h5={definition:{name:"rate_anomaly",description:"Track tool call frequency, detect anomalous bursts (file writes, deletes, network), throttle on hijack indicators.",parameters:[{name:"action",type:"string",description:"sessions | session <id> | unblock <id> | block <id> <reason> | recover | baselines | stats | report",required:!0},{name:"session_id",type:"string",description:"Session ID",required:!1},{name:"reason",type:"string",description:"Reason for block",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Rc(),_c)),r=String(e.action);if(r==="sessions"){let s=n.listSessions();return s.length===0?"No tracked sessions.":s.map(i=>` ${i.status==="allow"?"\u{1F7E2}":i.status==="throttle"?"\u{1F7E1}":"\u{1F534}"} ${i.sessionId.slice(0,16)}... | ${i.totalCalls} calls | ${i.recentAnomalies} recent anomalies | ${(i.uptime/6e4).toFixed(1)} min`).join(`
1826
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},hq={definition:{name:"rate_anomaly",description:"Track tool call frequency, detect anomalous bursts (file writes, deletes, network), throttle on hijack indicators.",parameters:[{name:"action",type:"string",description:"sessions | session <id> | unblock <id> | block <id> <reason> | recover | baselines | stats | report",required:!0},{name:"session_id",type:"string",description:"Session ID",required:!1},{name:"reason",type:"string",description:"Reason for block",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Rc(),_c)),r=String(e.action);if(r==="sessions"){let s=n.listSessions();return s.length===0?"No tracked sessions.":s.map(i=>` ${i.status==="allow"?"\u{1F7E2}":i.status==="throttle"?"\u{1F7E1}":"\u{1F534}"} ${i.sessionId.slice(0,16)}... | ${i.totalCalls} calls | ${i.recentAnomalies} recent anomalies | ${(i.uptime/6e4).toFixed(1)} min`).join(`
1797
1827
  `)}if(r==="session"&&e.session_id){let s=n.getSessionDetail(String(e.session_id));if(!s)return"Session not found";let i=[];i.push(`Session: ${s.sessionId}`),i.push(` Status: ${s.throttleAction}`),i.push(` Started: ${new Date(s.startedAt).toISOString()}`),i.push(` Last activity: ${new Date(s.lastActivityAt).toISOString()}`);let o=Array.from(s.toolCallCounts.values()).reduce((a,c)=>a+c,0);if(i.push(` Total calls: ${o}`),i.push(` File writes (last min): ${s.fileWrites.filter(a=>Date.now()-a<6e4).length}`),i.push(` File deletes (last min): ${s.fileDeletes.filter(a=>Date.now()-a<6e4).length}`),i.push(` Network calls (last min): ${s.networkCalls.filter(a=>Date.now()-a<6e4).length}`),i.push(` Destructive (last min): ${s.destructiveActions.filter(a=>Date.now()-a<6e4).length}`),i.push(` Recent anomalies: ${s.recentAnomalies.length}`),s.recentAnomalies.length>0)for(let a of s.recentAnomalies.slice(-5))i.push(` - ${a.type}: ${a.message}`);return i.join(`
1798
1828
  `)}if(r==="unblock"&&e.session_id)return n.unblockSession(String(e.session_id))?`\u2713 Unblocked ${e.session_id}`:"Not found";if(r==="block"&&e.session_id)return n.blockSession(String(e.session_id),String(e.reason||"manual"))?`\u{1F6AB} Blocked ${e.session_id}`:"Not found";if(r==="recover")return`Recovered ${n.autoRecover().recovered} paused session(s)`;if(r==="baselines"){let s=n.getBaselines();return s.length===0?"No baselines learned yet.":s.slice(0,10).map(i=>{let o=Object.entries(i.toolRates).sort((a,c)=>c[1].samples-a[1].samples).slice(0,3).map(([a,c])=>`${a}=${c.mean.toFixed(1)}\xB1${c.stddev.toFixed(1)}`).join(", ");return` ${i.agentId} | ${i.totalCalls} calls | ${o}`}).join(`
1799
1829
  `)}if(r==="stats"){let s=n.getStats();return["Rate Anomaly Stats:",` Total calls: ${s.totalCalls}`,` Anomalies: ${s.totalAnomalies}`,` Throttled: ${s.totalThrottled}`,` Paused: ${s.totalPaused}`,` Blocked: ${s.totalBlocked}`,` Alerts: ${s.totalAlerts}`].join(`
1800
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},y5={definition:{name:"compliance_policy",description:"Declarative compliance rules. Hard-block filesystem/network/command violations. Pre-canned bundles (HIPAA, PCI, SOC2, GDPR).",parameters:[{name:"action",type:"string",description:"check | rules | bundles | enable-bundle | disable-bundle | add | remove | enable | disable | stats | report",required:!0},{name:"rule_type",type:"string",description:"filesystem | network | command | env | secret | tool",required:!1},{name:"value",type:"string",description:"Value to check",required:!1},{name:"direction",type:"string",description:"read | write (filesystem)",required:!1},{name:"rule",type:"object",description:"Rule object for add",required:!1},{name:"rule_id",type:"string",description:"Rule ID for remove/enable/disable",required:!1},{name:"bundle_id",type:"string",description:"Bundle ID",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(ba(),ya)),r=String(e.action);if(r==="check"&&e.rule_type&&e.value){let s={value:String(e.value),sessionId:t.session?.id},i=n.evaluateValue(e.rule_type,s,{direction:e.direction});return i.length===0?"\u2713 No violations":i.map(o=>n.formatViolation(o)).join(`
1830
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},yq={definition:{name:"compliance_policy",description:"Declarative compliance rules. Hard-block filesystem/network/command violations. Pre-canned bundles (HIPAA, PCI, SOC2, GDPR).",parameters:[{name:"action",type:"string",description:"check | rules | bundles | enable-bundle | disable-bundle | add | remove | enable | disable | stats | report",required:!0},{name:"rule_type",type:"string",description:"filesystem | network | command | env | secret | tool",required:!1},{name:"value",type:"string",description:"Value to check",required:!1},{name:"direction",type:"string",description:"read | write (filesystem)",required:!1},{name:"rule",type:"object",description:"Rule object for add",required:!1},{name:"rule_id",type:"string",description:"Rule ID for remove/enable/disable",required:!1},{name:"bundle_id",type:"string",description:"Bundle ID",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(ba(),ya)),r=String(e.action);if(r==="check"&&e.rule_type&&e.value){let s={value:String(e.value),sessionId:t.session?.id},i=n.evaluateValue(e.rule_type,s,{direction:e.direction});return i.length===0?"\u2713 No violations":i.map(o=>n.formatViolation(o)).join(`
1801
1831
  `)}if(r==="rules")return n.listRules().map(i=>` ${i.enabled?"\u2713":"\u2717"} [${i.type.padEnd(11)}] ${i.severity.padEnd(8)} ${i.id.padEnd(25)} ${i.description}`).join(`
1802
1832
  `);if(r==="bundles")return n.listBundles().map(i=>` ${i.enabled?"\u2713":"\u2717"} ${i.id.padEnd(15)} | ${i.ruleCount} rules`).join(`
1803
1833
  `);if(r==="enable-bundle"&&e.bundle_id)return n.enableBundle(String(e.bundle_id))?`\u2713 Enabled bundle ${e.bundle_id}`:"Bundle not found";if(r==="disable-bundle"&&e.bundle_id)return n.disableBundle(String(e.bundle_id))?`\u2713 Disabled bundle ${e.bundle_id}`:"Bundle not found";if(r==="add"&&e.rule){let s=n.addRule(e.rule);return`\u2713 Added rule ${s.id}: ${s.description}`}if(r==="remove"&&e.rule_id)return n.removeRule(String(e.rule_id))?`\u2713 Removed ${e.rule_id}`:"Not found";if(r==="enable"&&e.rule_id)return n.enableRule(String(e.rule_id))?`\u2713 Enabled ${e.rule_id}`:"Not found";if(r==="disable"&&e.rule_id)return n.disableRule(String(e.rule_id))?`\u2713 Disabled ${e.rule_id}`:"Not found";if(r==="stats"){let s=n.getStats();return["Compliance Policy Stats:",` Evaluations: ${s.totalEvaluations}`,` \u{1F6AB} Blocked: ${s.totalBlocked}`,` \u26A0\uFE0F Warned: ${s.totalWarned}`,` \u{1F4CB} Audited: ${s.totalAudited}`,` \u{1F9F9} Sanitized: ${s.totalSanitized}`].join(`
1804
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},b5={definition:{name:"a2a_auth",description:"Cryptographic agent-to-agent authentication. Sign messages, verify envelopes, manage trust between agents.",parameters:[{name:"action",type:"string",description:"create_identity | sign | verify | revoke | trust | check_trust | handshake | identities | stats | report",required:!0},{name:"agent_id",type:"string",description:"Agent ID",required:!1},{name:"parent_agent_id",type:"string",description:"Parent for new identity",required:!1},{name:"from_agent",type:"string",description:"From agent for sign/handshake",required:!1},{name:"to_agent",type:"string",description:"Target agent",required:!1},{name:"message_type",type:"string",description:"request | response | event | broadcast",required:!1},{name:"payload",type:"object",description:"Message payload",required:!1},{name:"envelope",type:"object",description:"Signed envelope to verify",required:!1},{name:"trust_level",type:"number",description:"Trust level 0-1",required:!1},{name:"reason",type:"string",description:"Reason for revoke",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Cc(),$c)),r=String(e.action);if(r==="create_identity"&&e.agent_id)try{let s=n.createAgentIdentity({agentId:String(e.agent_id),parentAgentId:e.parent_agent_id});return["\u2713 Identity created",` Agent: ${s.agentId}`,` Fingerprint: ${s.fingerprint.slice(0,32)}...`," Algorithm: Ed25519",` Expires: ${s.expiresAt?new Date(s.expiresAt).toISOString():"never"}`,s.parentAgentId?` Parent: ${s.parentAgentId}`:""].filter(Boolean).join(`
1834
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},bq={definition:{name:"a2a_auth",description:"Cryptographic agent-to-agent authentication. Sign messages, verify envelopes, manage trust between agents.",parameters:[{name:"action",type:"string",description:"create_identity | sign | verify | revoke | trust | check_trust | handshake | identities | stats | report",required:!0},{name:"agent_id",type:"string",description:"Agent ID",required:!1},{name:"parent_agent_id",type:"string",description:"Parent for new identity",required:!1},{name:"from_agent",type:"string",description:"From agent for sign/handshake",required:!1},{name:"to_agent",type:"string",description:"Target agent",required:!1},{name:"message_type",type:"string",description:"request | response | event | broadcast",required:!1},{name:"payload",type:"object",description:"Message payload",required:!1},{name:"envelope",type:"object",description:"Signed envelope to verify",required:!1},{name:"trust_level",type:"number",description:"Trust level 0-1",required:!1},{name:"reason",type:"string",description:"Reason for revoke",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Cc(),$c)),r=String(e.action);if(r==="create_identity"&&e.agent_id)try{let s=n.createAgentIdentity({agentId:String(e.agent_id),parentAgentId:e.parent_agent_id});return["\u2713 Identity created",` Agent: ${s.agentId}`,` Fingerprint: ${s.fingerprint.slice(0,32)}...`," Algorithm: Ed25519",` Expires: ${s.expiresAt?new Date(s.expiresAt).toISOString():"never"}`,s.parentAgentId?` Parent: ${s.parentAgentId}`:""].filter(Boolean).join(`
1805
1835
  `)}catch(s){return`Error: ${s.message}`}if(r==="sign"&&e.from_agent&&e.to_agent&&e.payload){let s=n.signEnvelope({fromAgent:String(e.from_agent),toAgent:String(e.to_agent),messageType:e.message_type||"request",payload:e.payload});return"error"in s?`Error: ${s.error}`:["\u2713 Envelope signed",` ID: ${s.envelopeId}`,` From: ${s.fromAgent} \u2192 To: ${s.toAgent}`,` Type: ${s.messageType}`,` Signature: ${s.signature.slice(0,32)}...`,` Payload hash: ${s.payloadHash.slice(0,32)}...`,` Expires: ${new Date(s.expiresAt).toISOString()}`].join(`
1806
1836
  `)}if(r==="verify"&&e.envelope){let s=n.verifyEnvelope(e.envelope);return n.formatVerificationResult(s)}if(r==="revoke"&&e.agent_id)return n.revokeAgentIdentity(String(e.agent_id),String(e.reason||"manual"))?`\u2713 Revoked ${e.agent_id}`:"Not found";if(r==="trust"&&e.from_agent&&e.to_agent){let s=n.establishTrust(String(e.from_agent),String(e.to_agent),e.trust_level||.7,"manual");return`\u2713 Trust established: ${s.agentId} \u2192 ${s.trustsAgentId} (level ${s.trustLevel})`}if(r==="check_trust"&&e.from_agent&&e.to_agent){let s=n.checkTrust(String(e.from_agent),String(e.to_agent));return[`${s.trusted?"\u2713":"\u{1F6AB}"} ${s.trusted?"TRUSTED":"UNTRUSTED"}`,` Trust level: ${s.trustLevel.toFixed(2)}`,` Reason: ${s.reason}`].join(`
1807
1837
  `)}if(r==="handshake"&&e.from_agent&&e.to_agent){let s=n.initiateHandshake(String(e.from_agent),String(e.to_agent));return"error"in s?`Error: ${s.error}`:["\u{1F91D} Handshake initiated",` Handshake ID: ${s.handshakeId}`,` Challenge: ${s.challenge.slice(0,32)}...`,` Target must answer with: a2a.answerChallenge(challenge, '${e.to_agent}')`].join(`
1808
1838
  `)}if(r==="identities"){let s=n.listAgentIdentities();return s.length===0?"No identities.":s.map(i=>` ${i.revoked?"\u{1F534}":"\u{1F7E2}"} ${i.agentId.padEnd(30)} | fp=${i.fingerprint.slice(0,16)}... | ${i.parentAgentId?`parent=${i.parentAgentId}`:"root"}`).join(`
1809
1839
  `)}if(r==="stats"){let s=n.getStats();return["A2A Auth Stats:",` Identities: ${s.totalIdentitiesCreated}`,` Messages sent: ${s.totalMessagesSent}`,` Messages received: ${s.totalMessagesReceived}`,` \u2713 Authenticated: ${s.totalAuthenticated}`,` \u{1F501} Replay attempts: ${s.totalReplayAttempts}`,` \u{1F6A8} Signature failures: ${s.totalSignatureFailures}`,` \u{1F91D} Handshakes: ${s.totalHandshakes}`].join(`
1810
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},v5={definition:{name:"kill_switch",description:"Global emergency stop. Terminates all agents, revokes credentials, rolls back changes. Triggered manually or by automated monitors.",parameters:[{name:"action",type:"string",description:"activate | reset | status | history | recover | recovery-checkpoints | stats | report",required:!0},{name:"reason",type:"string",description:"Reason for activate",required:!1},{name:"trigger",type:"string",description:"Trigger type",required:!1},{name:"checkpoint_id",type:"string",description:"Recovery checkpoint ID",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Fm(),Dm)),r=String(e.action);if(r==="activate"){let s=await n.activate({trigger:e.trigger||"manual_user",reason:String(e.reason||"Agent-initiated emergency stop"),initiatedBy:"agent"});return n.formatKillEvent(s)}if(r==="reset"){let s=n.reset();return s.success?`\u2713 Reset: ${s.reason}`:`\u{1F6AB} ${s.reason}`}if(r==="status"){let s=n.getState();return["Kill Switch Status:",` Active: ${s.active?"\u{1F6A8} YES":"\u{1F7E2} NO"}`,s.activatedAt?` Activated at: ${new Date(s.activatedAt).toISOString()}`:"",s.lockedUntil?` Cooldown until: ${new Date(s.lockedUntil).toISOString()}`:"",s.currentEvent?` Current phase: ${s.currentEvent.phase}`:"",s.lastKillId?` Last kill ID: ${s.lastKillId}`:""].filter(Boolean).join(`
1840
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},vq={definition:{name:"kill_switch",description:"Global emergency stop. Terminates all agents, revokes credentials, rolls back changes. Triggered manually or by automated monitors.",parameters:[{name:"action",type:"string",description:"activate | reset | status | history | recover | recovery-checkpoints | stats | report",required:!0},{name:"reason",type:"string",description:"Reason for activate",required:!1},{name:"trigger",type:"string",description:"Trigger type",required:!1},{name:"checkpoint_id",type:"string",description:"Recovery checkpoint ID",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Fm(),Dm)),r=String(e.action);if(r==="activate"){let s=await n.activate({trigger:e.trigger||"manual_user",reason:String(e.reason||"Agent-initiated emergency stop"),initiatedBy:"agent"});return n.formatKillEvent(s)}if(r==="reset"){let s=n.reset();return s.success?`\u2713 Reset: ${s.reason}`:`\u{1F6AB} ${s.reason}`}if(r==="status"){let s=n.getState();return["Kill Switch Status:",` Active: ${s.active?"\u{1F6A8} YES":"\u{1F7E2} NO"}`,s.activatedAt?` Activated at: ${new Date(s.activatedAt).toISOString()}`:"",s.lockedUntil?` Cooldown until: ${new Date(s.lockedUntil).toISOString()}`:"",s.currentEvent?` Current phase: ${s.currentEvent.phase}`:"",s.lastKillId?` Last kill ID: ${s.lastKillId}`:""].filter(Boolean).join(`
1811
1841
  `)}if(r==="history"){let s=n.getHistory(20);return s.length===0?"No history.":s.map(i=>` ${i.id} | ${new Date(i.initiatedAt).toISOString().slice(0,19)} | ${i.trigger.padEnd(20)} | ${i.phase} | ${i.durationMs||"?"}ms`).join(`
1812
1842
  `)}if(r==="recover"&&e.checkpoint_id){let s=await n.recoverFromCheckpoint(String(e.checkpoint_id));return s.success?`\u2713 Recovered ${s.recovered} item(s)`:`\u{1F6AB} ${s.reason}`}if(r==="recovery-checkpoints"){let s=n.listRecoveryCheckpoints();return s.length===0?"No checkpoints.":s.map(i=>` ${i.id} | created ${new Date(i.createdAt).toISOString().slice(0,19)} | expires ${new Date(i.expiresAt).toISOString().slice(0,19)}`).join(`
1813
1843
  `)}if(r==="stats"){let s=n.getStats();return["Kill Switch Stats:",` Total kills: ${s.totalKills}`,` Total recoveries: ${s.totalRecoveries}`,` Manual: ${s.totalManualTriggered}`,` Auto: ${s.totalAutoTriggered}`,` Avg duration: ${s.averageDurationMs.toFixed(0)}ms`].join(`
1814
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},S5={definition:{name:"circuit_breaker",description:"Per-tool circuit breaker. Opens on N consecutive failures. Half-open probe. Cascade detection. Auto-recovery.",parameters:[{name:"action",type:"string",description:"circuits | circuit <id> | trip <id> [reason] | reset <id> | reset-all | check <id> | stats | report",required:!0},{name:"circuit_id",type:"string",description:"Circuit ID",required:!1},{name:"reason",type:"string",description:"Reason for trip",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Td(),Ad)),r=String(e.action);if(r==="circuits"){let s=n.listCircuits();return s.length===0?"No circuits.":s.map(i=>` ${i.metrics.state==="closed"?"\u{1F7E2}":i.metrics.state==="half_open"?"\u{1F7E1}":"\u{1F534}"} ${i.id.padEnd(30)} | ${i.metrics.state.padEnd(11)} | health=${i.metrics.healthScore.toFixed(2)} | ${i.metrics.totalCalls}c/${i.metrics.totalFailures}f`).join(`
1844
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},Sq={definition:{name:"circuit_breaker",description:"Per-tool circuit breaker. Opens on N consecutive failures. Half-open probe. Cascade detection. Auto-recovery.",parameters:[{name:"action",type:"string",description:"circuits | circuit <id> | trip <id> [reason] | reset <id> | reset-all | check <id> | stats | report",required:!0},{name:"circuit_id",type:"string",description:"Circuit ID",required:!1},{name:"reason",type:"string",description:"Reason for trip",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Td(),Ad)),r=String(e.action);if(r==="circuits"){let s=n.listCircuits();return s.length===0?"No circuits.":s.map(i=>` ${i.metrics.state==="closed"?"\u{1F7E2}":i.metrics.state==="half_open"?"\u{1F7E1}":"\u{1F534}"} ${i.id.padEnd(30)} | ${i.metrics.state.padEnd(11)} | health=${i.metrics.healthScore.toFixed(2)} | ${i.metrics.totalCalls}c/${i.metrics.totalFailures}f`).join(`
1815
1845
  `)}if(r==="circuit"&&e.circuit_id){let s=n.getCircuit(String(e.circuit_id));return s?n.formatCircuit(s):"Circuit not found"}if(r==="trip"&&e.circuit_id)return n.trip(String(e.circuit_id),String(e.reason||"manual"))?`\u{1F534} Tripped ${e.circuit_id}`:"Not found";if(r==="reset"&&e.circuit_id)return n.reset(String(e.circuit_id))?`\u2713 Reset ${e.circuit_id}`:"Not found";if(r==="reset-all")return`\u2713 Reset ${n.resetAll()} non-closed circuits`;if(r==="check"&&e.circuit_id){let s=n.canExecute(String(e.circuit_id));return[`${s.allowed?"\u2713":"\u{1F534}"} ${s.allowed?"ALLOWED":"BLOCKED"}`,` State: ${s.state}`,` Reason: ${s.reason}`,` Health: ${(s.healthScore*100).toFixed(0)}/100`,s.retryAfterMs?` Retry after: ${(s.retryAfterMs/1e3).toFixed(0)}s`:""].filter(Boolean).join(`
1816
1846
  `)}if(r==="stats"){let s=n.getStats();return["Circuit Breaker Stats:",` Total calls: ${s.totalCalls}`,` Total failures: ${s.totalFailures}`,` Total successes: ${s.totalSuccesses}`,` Circuit opens: ${s.totalCircuitOpens}`,` Circuit closes: ${s.totalCircuitCloses}`,` Auto-recoveries: ${s.totalAutoRecoveries}`,` Cascades detected: ${s.totalCascadesDetected}`].join(`
1817
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},w5={definition:{name:"trust_boundary",description:"Hierarchical trust enforcement: user > orchestrator > sub-agent > tool. Blocks upward instruction flow + capability escalation.",parameters:[{name:"action",type:"string",description:"check | zones | detect-injection | downgrade | attest | verify-attest | stats | report",required:!0},{name:"from_zone",type:"string",description:"Source zone",required:!1},{name:"to_zone",type:"string",description:"Target zone",required:!1},{name:"capability",type:"string",description:"Capability for check",required:!1},{name:"content",type:"string",description:"Content for injection detection",required:!1},{name:"origin_zone",type:"string",description:"Origin zone for content",required:!1},{name:"attestation_id",type:"string",description:"Attestation ID for verify",required:!1},{name:"attestation_signature",type:"string",description:"Signature for verify",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Sv(),vv)),r=String(e.action);if(r==="check"&&e.from_zone&&e.to_zone){let s=n.checkBoundary({zone:e.from_zone,origin:"agent"},{zone:e.to_zone,origin:"agent"},e.capability);return n.formatBoundaryResult(s)}if(r==="zones")return n.listZones().map(i=>{let o=Array.from(i.allowedCapabilities).slice(0,5).join(", "),a=Array.from(i.deniedCapabilities).slice(0,3).join(", ");return` ${i.zone.padEnd(15)} | level=${i.level.toString().padStart(3)} | allowed: ${o||"none"}${a?` | denied: ${a}`:""}`}).join(`
1847
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},wq={definition:{name:"trust_boundary",description:"Hierarchical trust enforcement: user > orchestrator > sub-agent > tool. Blocks upward instruction flow + capability escalation.",parameters:[{name:"action",type:"string",description:"check | zones | detect-injection | downgrade | attest | verify-attest | stats | report",required:!0},{name:"from_zone",type:"string",description:"Source zone",required:!1},{name:"to_zone",type:"string",description:"Target zone",required:!1},{name:"capability",type:"string",description:"Capability for check",required:!1},{name:"content",type:"string",description:"Content for injection detection",required:!1},{name:"origin_zone",type:"string",description:"Origin zone for content",required:!1},{name:"attestation_id",type:"string",description:"Attestation ID for verify",required:!1},{name:"attestation_signature",type:"string",description:"Signature for verify",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Sv(),vv)),r=String(e.action);if(r==="check"&&e.from_zone&&e.to_zone){let s=n.checkBoundary({zone:e.from_zone,origin:"agent"},{zone:e.to_zone,origin:"agent"},e.capability);return n.formatBoundaryResult(s)}if(r==="zones")return n.listZones().map(i=>{let o=Array.from(i.allowedCapabilities).slice(0,5).join(", "),a=Array.from(i.deniedCapabilities).slice(0,3).join(", ");return` ${i.zone.padEnd(15)} | level=${i.level.toString().padStart(3)} | allowed: ${o||"none"}${a?` | denied: ${a}`:""}`}).join(`
1818
1848
  `);if(r==="detect-injection"&&e.content){let s=n.detectInstructionInjection(String(e.content),e.origin_zone||"tool");return[`${s.detected?"\u{1F6A8}":"\u2713"} ${s.detected?"INJECTION DETECTED":"No injection"}`,`Risk: ${(s.riskScore*100).toFixed(0)}%`,s.patterns.length>0?`Patterns matched: ${s.patterns.length}`:"",...s.patterns.slice(0,5).map(i=>` - ${i}`)].filter(Boolean).join(`
1819
1849
  `)}if(r==="downgrade"&&e.content){let s=n.downgradeContext(String(e.content),e.origin_zone||"tool");return[`${s.downgraded?"\u{1F53D}":"\u2713"} ${s.downgraded?"DOWNGRADED":"No change"}`,`New zone: ${s.newZone}`,`Reason: ${s.reason}`].join(`
1820
1850
  `)}if(r==="attest"&&e.from_zone){let s=n.createAttestation(e.from_zone);return["\u2713 Attestation created",` ID: ${s.id}`,` Signature: ${s.signature.slice(0,32)}...`," TTL: 5 minutes"].join(`
1821
1851
  `)}if(r==="verify-attest"&&e.attestation_id&&e.attestation_signature){let s=n.verifyAttestation(String(e.attestation_id),String(e.attestation_signature));return[`${s.valid?"\u2713":"\u{1F6AB}"} ${s.valid?"Valid":"Invalid"}`,s.zone?` Zone: ${s.zone}`:"",` Reason: ${s.reason}`].filter(Boolean).join(`
1822
1852
  `)}if(r==="stats"){let s=n.getStats();return["Trust Boundary Stats:",` Total checks: ${s.totalChecks}`,` Allowed: ${s.totalAllowed}`,` Blocked: ${s.totalBlocked}`,` Downgraded: ${s.totalDowngraded}`,` Upward flow attempts: ${s.totalUpwardFlowAttempts}`,` Capability escalations: ${s.totalCapabilityEscalations}`,` Instruction injections: ${s.totalInstructionInjections}`].join(`
1823
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},k5={definition:{name:"egress_firewall",description:"Per-project outbound network allowlist. Blocks calls to non-approved domains. Logs every request.",parameters:[{name:"action",type:"string",description:"check | rules | add | remove | block | recent | stats | report",required:!0},{name:"url",type:"string",description:"URL for check",required:!1},{name:"domain",type:"string",description:"Domain for add/block",required:!1},{name:"rule_id",type:"string",description:"Rule ID for remove",required:!1},{name:"description",type:"string",description:"Description for add",required:!1},{name:"decision",type:"string",description:"allow|block|audit_only",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Sf(),vf)),r=String(e.action);if(r==="check"&&e.url){let s=n.checkRequest({url:String(e.url),sessionId:t.session?.id});return n.formatDecision(s,String(e.url))}if(r==="rules"){let s=n.listRules();return s.length===0?"No rules.":s.map(i=>` ${i.decision==="allow"?"\u{1F7E2}":i.decision==="block"?"\u{1F534}":"\u{1F7E1}"} ${i.domain.padEnd(40)} | ${i.decision.padEnd(11)} | ${i.totalRequests} requests | ${i.description||""}`).join(`
1853
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},kq={definition:{name:"egress_firewall",description:"Per-project outbound network allowlist. Blocks calls to non-approved domains. Logs every request.",parameters:[{name:"action",type:"string",description:"check | rules | add | remove | block | recent | stats | report",required:!0},{name:"url",type:"string",description:"URL for check",required:!1},{name:"domain",type:"string",description:"Domain for add/block",required:!1},{name:"rule_id",type:"string",description:"Rule ID for remove",required:!1},{name:"description",type:"string",description:"Description for add",required:!1},{name:"decision",type:"string",description:"allow|block|audit_only",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Sf(),vf)),r=String(e.action);if(r==="check"&&e.url){let s=n.checkRequest({url:String(e.url),sessionId:t.session?.id});return n.formatDecision(s,String(e.url))}if(r==="rules"){let s=n.listRules();return s.length===0?"No rules.":s.map(i=>` ${i.decision==="allow"?"\u{1F7E2}":i.decision==="block"?"\u{1F534}":"\u{1F7E1}"} ${i.domain.padEnd(40)} | ${i.decision.padEnd(11)} | ${i.totalRequests} requests | ${i.description||""}`).join(`
1824
1854
  `)}if(r==="add"&&e.domain){let s=n.addRule({domain:String(e.domain),decision:e.decision||"allow",description:e.description,approvedBy:"agent"});return`\u2713 Rule added
1825
1855
  ${n.formatRule(s)}`}if(r==="remove"&&e.rule_id)return n.removeRule(String(e.rule_id))?`\u2713 Removed ${e.rule_id}`:"Not found";if(r==="block"&&e.domain)return`\u{1F534} Blocked ${n.blockRule(String(e.domain),String(e.description||"manual block")).domain}`;if(r==="recent"){let s=n.getRecentRequests(20);return s.length===0?"No recent requests.":s.map(i=>` ${i.decision==="allow"?"\u2713":i.decision==="block"?"\u{1F6AB}":"\u{1F4CB}"} ${new Date(i.timestamp).toISOString().slice(11,19)} | ${i.hostname.padEnd(35)} | ${i.classification.padEnd(10)} | ${i.toolName||"unknown"}`).join(`
1826
1856
  `)}if(r==="stats"){let s=n.getStats();return["Egress Firewall Stats:",` Total requests: ${s.totalRequests}`,` Allowed: ${s.totalAllowed}`,` Blocked: ${s.totalBlocked}`,` SSRF blocked: ${s.totalSSRFBlocked}`,` Anomalies: ${s.totalAnomalies}`].join(`
1827
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},x5={definition:{name:"data_classification",description:"Classify content (public/internal/confidential/secret) by path + content patterns. Block egress of classified data.",parameters:[{name:"action",type:"string",description:"classify | check | rules | add-rule | remove-rule | stats | report",required:!0},{name:"content",type:"string",description:"Content to classify",required:!1},{name:"file_path",type:"string",description:"File path for path-based heuristics",required:!1},{name:"channel",type:"string",description:"external_network|internal_network|file_write|log|memory|agent_output",required:!1},{name:"destination",type:"string",description:"Destination for check",required:!1},{name:"pattern",type:"string",description:"Regex pattern for add-rule",required:!1},{name:"classification",type:"string",description:"public|internal|confidential|secret",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Bf(),jf)),r=String(e.action);if(r==="classify"&&e.content){let s=n.classify(String(e.content),{filePath:e.file_path});return n.formatClassification(s)}if(r==="check"&&e.channel&&e.content){let s=n.checkDLP({channel:e.channel,content:String(e.content),filePath:e.file_path,destination:e.destination});return[`${s.allowed?"\u2713":"\u{1F6AB}"} **${s.allowed?"ALLOWED":"BLOCKED"}**`,`Classification: ${s.classification}`,`Sensitivity: ${(s.sensitivityScore*100).toFixed(0)}/100`,`Reason: ${s.reason}`,s.shouldRedact?"\u{1F9F9} Will redact before sending":"",s.blockedSignals.length>0?`Blocked signals: ${s.blockedSignals.join(", ")}`:""].filter(Boolean).join(`
1857
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},xq={definition:{name:"data_classification",description:"Classify content (public/internal/confidential/secret) by path + content patterns. Block egress of classified data.",parameters:[{name:"action",type:"string",description:"classify | check | rules | add-rule | remove-rule | stats | report",required:!0},{name:"content",type:"string",description:"Content to classify",required:!1},{name:"file_path",type:"string",description:"File path for path-based heuristics",required:!1},{name:"channel",type:"string",description:"external_network|internal_network|file_write|log|memory|agent_output",required:!1},{name:"destination",type:"string",description:"Destination for check",required:!1},{name:"pattern",type:"string",description:"Regex pattern for add-rule",required:!1},{name:"classification",type:"string",description:"public|internal|confidential|secret",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Bf(),jf)),r=String(e.action);if(r==="classify"&&e.content){let s=n.classify(String(e.content),{filePath:e.file_path});return n.formatClassification(s)}if(r==="check"&&e.channel&&e.content){let s=n.checkDLP({channel:e.channel,content:String(e.content),filePath:e.file_path,destination:e.destination});return[`${s.allowed?"\u2713":"\u{1F6AB}"} **${s.allowed?"ALLOWED":"BLOCKED"}**`,`Classification: ${s.classification}`,`Sensitivity: ${(s.sensitivityScore*100).toFixed(0)}/100`,`Reason: ${s.reason}`,s.shouldRedact?"\u{1F9F9} Will redact before sending":"",s.blockedSignals.length>0?`Blocked signals: ${s.blockedSignals.join(", ")}`:""].filter(Boolean).join(`
1828
1858
  `)}if(r==="rules"){let s=n.listCustomRules();return s.length===0?"No custom rules.":s.map(([i,o])=>` ${o.padEnd(13)} ${i}`).join(`
1829
1859
  `)}if(r==="add-rule"&&e.pattern&&e.classification)return n.addPathRule(String(e.pattern),e.classification),`\u2713 Added rule: ${e.pattern} \u2192 ${e.classification}`;if(r==="remove-rule"&&e.pattern)return n.removePathRule(String(e.pattern))?`\u2713 Removed ${e.pattern}`:"Not found";if(r==="stats"){let s=n.getStats();return["Data Classification & DLP Stats:",` Total classifications: ${s.totalClassifications}`,` Allowed: ${s.totalAllowed}`,` Blocked: ${s.totalBlocked}`,` Redacted: ${s.totalRedacted}`].join(`
1830
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},$5={definition:{name:"tls_pinning",description:"Pin TLS certificates for API endpoints. Detect MITM attacks via cert fingerprint mismatch.",parameters:[{name:"action",type:"string",description:"pins | probe | add | remove | verify | rotate | stats | report",required:!0},{name:"hostname",type:"string",description:"Hostname",required:!1},{name:"port",type:"number",description:"Port (default 443)",required:!1},{name:"fingerprint",type:"string",description:"SHA-256 fingerprint for add",required:!1},{name:"trust_level",type:"string",description:"official|verified|community|tofu",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(by(),yy)),r=String(e.action),s=e.hostname,i=e.port||443;if(r==="pins"){let o=n.listPins();return o.length===0?"No pins.":o.map(a=>` ${a.hostname}:${a.port} | ${a.trustLevel} | ${a.fingerprintSHA256.slice(0,16)}... | ${a.totalConnections} conns`).join(`
1860
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},$q={definition:{name:"tls_pinning",description:"Pin TLS certificates for API endpoints. Detect MITM attacks via cert fingerprint mismatch.",parameters:[{name:"action",type:"string",description:"pins | probe | add | remove | verify | rotate | stats | report",required:!0},{name:"hostname",type:"string",description:"Hostname",required:!1},{name:"port",type:"number",description:"Port (default 443)",required:!1},{name:"fingerprint",type:"string",description:"SHA-256 fingerprint for add",required:!1},{name:"trust_level",type:"string",description:"official|verified|community|tofu",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(by(),yy)),r=String(e.action),s=e.hostname,i=e.port||443;if(r==="pins"){let o=n.listPins();return o.length===0?"No pins.":o.map(a=>` ${a.hostname}:${a.port} | ${a.trustLevel} | ${a.fingerprintSHA256.slice(0,16)}... | ${a.totalConnections} conns`).join(`
1831
1861
  `)}if(r==="probe"&&s){let o=await n.probeCertificate(s,i);return o?[`Probe ${s}:${i}:`,` Subject: ${o.subject}`,` Issuer: ${o.issuer}`,` Valid: ${new Date(o.validFrom).toISOString().slice(0,10)} \u2192 ${new Date(o.validTo).toISOString().slice(0,10)}`,` SHA-256: ${o.fingerprint}`].join(`
1832
1862
  `):"Probe failed"}if(r==="add"&&s&&e.fingerprint){let o=n.addPin({hostname:s,port:i,fingerprintSHA256:String(e.fingerprint),trustLevel:e.trust_level||"community",pinnedBy:"agent"});return`\u2713 Pinned ${o.hostname}:${o.port}`}if(r==="remove"&&s)return n.removePin(s,i)?`\u2713 Removed pin for ${s}:${i}`:"Not found";if(r==="rotate"&&s){let o=await n.autoRotate(s,i);return o.success?`\u2713 ${o.reason}`:`Failed: ${o.reason}`}if(r==="stats"){let o=n.getStats();return["TLS Pinning Stats:",` Total verifications: ${o.totalVerifications}`,` \u2713 Matched: ${o.totalMatched}`,` \u{1F6A8} Mismatches: ${o.totalMismatches}`,` \u{1F504} Rotations: ${o.totalRotations}`,` \u{1F195} TOFU pins: ${o.totalTofuPins}`,` \u23F0 Expiration warnings: ${o.totalExpirationWarnings}`,` \u{1F6A8} MITM detections: ${o.totalMitmDetections}`].join(`
1833
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},C5={definition:{name:"local_first",description:"Manage privacy mode: route between local models and remote APIs. Abstract content client-side before sending.",parameters:[{name:"action",type:"string",description:"mode | mode_set | models | route | abstract | budget | budgets | report | stats",required:!0},{name:"mode",type:"string",description:"full_remote|abstracted|local_only|hybrid|offline",required:!1},{name:"content",type:"string",description:"Content for abstract",required:!1},{name:"level",type:"string",description:"Abstraction: none|summary|diff|structure|redacted",required:!1},{name:"classification",type:"string",description:"Classification for route",required:!1},{name:"session_id",type:"string",description:"Session ID",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(UR(),qR)),r=String(e.action);if(r==="mode")return`Current privacy mode: ${n.getConfig().privacyMode}`;if(r==="mode_set"&&e.mode)return n.setMode(e.mode),`\u2713 Privacy mode set to ${e.mode}`;if(r==="models"){await n.detectLocalModels(!0);let s=n.listLocalModels();return s.length===0?"No local models detected. Install Ollama (https://ollama.ai), llama.cpp server, or MLX.":s.map(i=>` ${i.name} (${i.type})${i.endpoint?" @ "+i.endpoint:""} | ${i.capabilities.join(", ")}`).join(`
1863
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}},Cq={definition:{name:"local_first",description:"Manage privacy mode: route between local models and remote APIs. Abstract content client-side before sending.",parameters:[{name:"action",type:"string",description:"mode | mode_set | models | route | abstract | budget | budgets | report | stats",required:!0},{name:"mode",type:"string",description:"full_remote|abstracted|local_only|hybrid|offline",required:!1},{name:"content",type:"string",description:"Content for abstract",required:!1},{name:"level",type:"string",description:"Abstraction: none|summary|diff|structure|redacted",required:!1},{name:"classification",type:"string",description:"Classification for route",required:!1},{name:"session_id",type:"string",description:"Session ID",required:!1}]},handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(UR(),qR)),r=String(e.action);if(r==="mode")return`Current privacy mode: ${n.getConfig().privacyMode}`;if(r==="mode_set"&&e.mode)return n.setMode(e.mode),`\u2713 Privacy mode set to ${e.mode}`;if(r==="models"){await n.detectLocalModels(!0);let s=n.listLocalModels();return s.length===0?"No local models detected. Install Ollama (https://ollama.ai), llama.cpp server, or MLX.":s.map(i=>` ${i.name} (${i.type})${i.endpoint?" @ "+i.endpoint:""} | ${i.capabilities.join(", ")}`).join(`
1834
1864
  `)}if(r==="route"&&e.content){let s=n.decideRoute({sessionId:e.session_id||t.session?.id||"default",contentLength:String(e.content).length,classification:e.classification});return n.formatRouteDecision(s)}if(r==="abstract"&&e.content){let s=n.abstractContent(String(e.content),e.level||"summary");return[`Original: ${s.original.length} bytes`,`Abstracted: ${s.abstracted.length} bytes (${(s.reductionRatio*100).toFixed(0)}% of original)`,`Bytes removed: ${s.bytesRemoved}`,`Sensitive signals removed: ${s.sensitiveSignalsRemoved}`,"",s.abstracted.slice(0,500)].join(`
1835
1865
  `)}if(r==="budget"&&e.session_id){let s=n.getOrCreateBudget(String(e.session_id));return n.formatBudget(s)}if(r==="budgets"){let s=n.listBudgets();return s.length===0?"No active budgets.":s.map(i=>n.formatBudget(i)).join(`
1836
1866
 
1837
1867
  `)}if(r==="stats"){let s=n.getStats();return["Local-First Stats:",` Total requests: ${s.totalRequests}`,` \u{1F3E0} Local: ${s.totalLocalRouted}`,` \u{1F310} Remote: ${s.totalRemoteRouted}`,` \u{1F3AD} Abstracted: ${s.totalAbstracted}`,` \u{1F4E4} Bytes sent: ${(s.totalBytesSent/1024).toFixed(1)}KB`,` \u{1F6E1}\uFE0F Bytes saved: ${(s.totalBytesAbstractedAway/1024).toFixed(1)}KB`,` \u26A0\uFE0F Budget warnings: ${s.totalBudgetWarnings}`,` \u{1F6AB} Budget blocks: ${s.totalBudgetBlocks}`].join(`
1838
- `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}}});import{writeFileSync as R5,mkdirSync as GSe,createWriteStream as VSe}from"fs";import{resolve as JSe,dirname as WSe}from"path";import{Document as KSe,Packer as YSe,Paragraph as ug,HeadingLevel as m0,TextRun as a1}from"docx";import QSe from"pptxgenjs";import ZSe from"exceljs";import XSe from"pdfkit";function ewe(e,t){if(e&&g0[e.toLowerCase()])return g0[e.toLowerCase()];let n=Object.keys(g0),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)|0;return g0[n[Math.abs(r)%n.length]]}async function twe(e,t,n,r){let s=[new ug({heading:m0.TITLE,children:[new a1({text:t,color:r.primary,bold:!0})]})];for(let a of n.split(`
1839
- `)){let c=a.replace(/\r$/,""),l=c.match(/^(#{1,6})\s+(.*)/);if(l){let u=l[1].length,d=u===1?m0.HEADING_1:u===2?m0.HEADING_2:m0.HEADING_3;s.push(new ug({heading:d,children:[new a1({text:Wi(l[2]),color:r.primary,bold:!0})]}))}else/^\s*[-*]\s+/.test(c)?s.push(new ug({text:Wi(c.replace(/^\s*[-*]\s+/,"")),bullet:{level:0}})):c.trim()?s.push(new ug({children:[new a1(Wi(c))]})):s.push(new ug({}))}let i=new KSe({sections:[{children:s}]}),o=await YSe.toBuffer(i);R5(e,o)}async function nwe(e,t,n,r){let s=new QSe;s.defineLayout({name:"AIACA_WIDE",width:13.333,height:7.5}),s.layout="AIACA_WIDE";let i=13.333,o=7.5,a=n.split(/^\s*---\s*$/m).map(l=>l.trim()).filter(Boolean),c=s.addSlide();c.background={color:r.primary},c.addShape(s.ShapeType.rect,{x:0,y:0,w:.35,h:o,fill:{color:r.accent}}),c.addText(Wi(t),{x:1,y:2.6,w:i-2,h:1.6,fontSize:44,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia"}),c.addText("AiCraftAlchemy \xB7 AIACA",{x:1,y:4.3,w:i-2,h:.5,fontSize:14,color:r.secondary,align:"left"}),a.forEach((l,u)=>{let d=l.split(`
1868
+ `)}return r==="report"?n.generateComplianceReport():`Unknown action: ${r}`}}});import{writeFileSync as Rq,mkdirSync as GSe,createWriteStream as VSe}from"fs";import{resolve as JSe,dirname as WSe}from"path";import{Document as KSe,Packer as YSe,Paragraph as ug,HeadingLevel as m0,TextRun as a1}from"docx";import QSe from"pptxgenjs";import ZSe from"exceljs";import XSe from"pdfkit";function ewe(e,t){if(e&&g0[e.toLowerCase()])return g0[e.toLowerCase()];let n=Object.keys(g0),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)|0;return g0[n[Math.abs(r)%n.length]]}async function twe(e,t,n,r){let s=[new ug({heading:m0.TITLE,children:[new a1({text:t,color:r.primary,bold:!0})]})];for(let a of n.split(`
1869
+ `)){let c=a.replace(/\r$/,""),l=c.match(/^(#{1,6})\s+(.*)/);if(l){let u=l[1].length,d=u===1?m0.HEADING_1:u===2?m0.HEADING_2:m0.HEADING_3;s.push(new ug({heading:d,children:[new a1({text:Wi(l[2]),color:r.primary,bold:!0})]}))}else/^\s*[-*]\s+/.test(c)?s.push(new ug({text:Wi(c.replace(/^\s*[-*]\s+/,"")),bullet:{level:0}})):c.trim()?s.push(new ug({children:[new a1(Wi(c))]})):s.push(new ug({}))}let i=new KSe({sections:[{children:s}]}),o=await YSe.toBuffer(i);Rq(e,o)}async function nwe(e,t,n,r){let s=new QSe;s.defineLayout({name:"AIACA_WIDE",width:13.333,height:7.5}),s.layout="AIACA_WIDE";let i=13.333,o=7.5,a=n.split(/^\s*---\s*$/m).map(l=>l.trim()).filter(Boolean),c=s.addSlide();c.background={color:r.primary},c.addShape(s.ShapeType.rect,{x:0,y:0,w:.35,h:o,fill:{color:r.accent}}),c.addText(Wi(t),{x:1,y:2.6,w:i-2,h:1.6,fontSize:44,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia"}),c.addText("AiCraftAlchemy \xB7 AIACA",{x:1,y:4.3,w:i-2,h:.5,fontSize:14,color:r.secondary,align:"left"}),a.forEach((l,u)=>{let d=l.split(`
1840
1870
  `).filter(v=>v.trim());if(!d.length)return;let f="",p=[];for(let v of d.slice(1)){let y=v.match(/^note:\s*(.*)/i);y?f+=y[1]+" ":p.push(v)}let m=d[0].replace(/^#+\s*/,""),g=s.addSlide();g.background={color:r.lightBg},g.addShape(s.ShapeType.rect,{x:0,y:0,w:.22,h:o,fill:{color:r.accent}}),g.addShape(s.ShapeType.rect,{x:.22,y:0,w:i-.22,h:1.25,fill:{color:r.primary}}),g.addText(Wi(m),{x:.7,y:.2,w:i-1.2,h:.85,fontSize:28,bold:!0,color:r.onDark,align:"left",fontFace:"Georgia",valign:"middle"});let h=p.map(v=>({text:Wi(v.replace(/^[-*]\s*/,"")),options:{bullet:{code:"2022"},fontSize:18,color:r.onLight,paraSpaceAfter:10}}));h.length&&g.addText(h,{x:.9,y:1.7,w:i-1.8,h:o-2.4,align:"left",valign:"top"}),g.addText(String(u+1),{x:i-1,y:o-.55,w:.7,h:.35,fontSize:11,color:r.secondary,align:"right"}),f.trim()&&g.addNotes(f.trim())}),await s.writeFile({fileName:e})}async function rwe(e,t,n){let r=new ZSe.Workbook,s=r.addWorksheet(t.slice(0,31)||"Sheet1");n.split(`
1841
1871
  `).filter(o=>o.trim()&&!/^\s*\|?\s*-+\s*\|/.test(o)).map(o=>o.replace(/^\||\|$/g,"").split(/\s*[|,\t]\s*/).map(a=>a.trim()).filter((a,c,l)=>l.length>1||a!=="")).forEach((o,a)=>{let c=s.addRow(o);a===0&&(c.font={bold:!0,color:{argb:"FFFFFFFF"}},c.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FF4472C4"}})}),s.columns.forEach(o=>{o.width=20}),await r.xlsx.writeFile(e)}function swe(e,t,n,r){return new Promise((s,i)=>{let o="#"+r.primary,a=new XSe({margin:50}),c=VSe(e);c.on("finish",()=>s()),c.on("error",i),a.pipe(c),a.fontSize(24).fillColor(o).text(t,{underline:!1}),a.moveDown(.5);let l=!1;for(let u of n.split(`
1842
- `)){let d=u.replace(/\r$/,"");if(d.startsWith("```")){l=!l,a.moveDown(.3);continue}if(l){a.font("Courier").fontSize(10).fillColor("#333").text(d);continue}a.font("Helvetica");let f=d.match(/^(#{1,6})\s+(.*)/);if(f){let p=f[1].length===1?18:f[1].length===2?15:13;a.moveDown(.4).fontSize(p).fillColor(o).text(Wi(f[2]))}else/^\s*[-*]\s+/.test(d)?a.fontSize(11).fillColor("#000").text("\u2022 "+Wi(d.replace(/^\s*[-*]\s+/,"")),{indent:16}):d.trim()?a.fontSize(11).fillColor("#000").text(Wi(d)):a.moveDown(.4)}a.end()})}function _5(e,t,n){let r=`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${ta(t)}</title>
1872
+ `)){let d=u.replace(/\r$/,"");if(d.startsWith("```")){l=!l,a.moveDown(.3);continue}if(l){a.font("Courier").fontSize(10).fillColor("#333").text(d);continue}a.font("Helvetica");let f=d.match(/^(#{1,6})\s+(.*)/);if(f){let p=f[1].length===1?18:f[1].length===2?15:13;a.moveDown(.4).fontSize(p).fillColor(o).text(Wi(f[2]))}else/^\s*[-*]\s+/.test(d)?a.fontSize(11).fillColor("#000").text("\u2022 "+Wi(d.replace(/^\s*[-*]\s+/,"")),{indent:16}):d.trim()?a.fontSize(11).fillColor("#000").text(Wi(d)):a.moveDown(.4)}a.end()})}function _q(e,t,n){let r=`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${ta(t)}</title>
1843
1873
  <style>body{font-family:system-ui,sans-serif;max-width:800px;margin:40px auto;padding:20px;line-height:1.6;color:#333}
1844
1874
  h1,h2,h3{color:#1a1a2e}code{background:#f0f0f0;padding:2px 5px;border-radius:3px}
1845
1875
  pre{background:#1e1e2e;color:#cdd6f4;padding:16px;border-radius:8px;overflow-x:auto}</style>
1846
- </head><body>${iwe(t,n)}</body></html>`;R5(e,r,"utf-8")}function iwe(e,t){let n=`<h1>${ta(e)}</h1>
1876
+ </head><body>${iwe(t,n)}</body></html>`;Rq(e,r,"utf-8")}function iwe(e,t){let n=`<h1>${ta(e)}</h1>
1847
1877
  `,r=!1,s=!1;for(let i of t.split(`
1848
1878
  `)){if(i.startsWith("```")){n+=r?`</code></pre>
1849
1879
  `:"<pre><code>",r=!r;continue}if(r){n+=ta(i)+`
@@ -1858,40 +1888,40 @@ pre{background:#1e1e2e;color:#cdd6f4;padding:16px;border-radius:8px;overflow-x:a
1858
1888
  `;continue}n+=`<p>${ta(i)}</p>
1859
1889
  `}return s&&(n+=`</ul>
1860
1890
  `),r&&(n+=`</code></pre>
1861
- `),n}function Wi(e){return e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/`(.+?)`/g,"$1")}function ta(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var c1,g0,P5=w(()=>{"use strict";c1={definition:{name:"doc_create",description:"Create REAL, presentation-grade document files (.docx, .pptx, .xlsx, .pdf, .html) from markdown. Produces genuine Office/PDF files that open natively. Decks and reports are auto-styled with a cohesive color theme, typography, and layout \u2014 not plain bullets.",parameters:[{name:"path",type:"string",description:"Output file path (e.g. notes.docx, slides.pptx, report.pdf, data.xlsx)",required:!0},{name:"content",type:"string",description:'Document content in markdown. For slides, separate each slide with a line containing only "---"; the first line of each block is the slide title, following lines are bullets. For spreadsheets, use markdown tables or CSV rows. Optionally end a slide with a line "note: ..." for speaker notes.',required:!0},{name:"title",type:"string",description:"Document title",required:!1},{name:"theme",type:"string",description:"Visual theme for decks/PDFs. One of: midnight, forest, coral, ocean, teal, berry, charcoal, cherry. Omit to auto-pick a topic-appropriate palette.",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=JSe(t.cwd,e.path),r=String(e.content??""),s=e.title||"Document",i=ewe(e.theme,s+" "+r),o=n.split(".").pop()?.toLowerCase();GSe(WSe(n),{recursive:!0});try{switch(o){case"docx":await twe(n,s,r,i);break;case"pptx":await nwe(n,s,r,i);break;case"xlsx":await rwe(n,s,r);break;case"pdf":await swe(n,s,r,i);break;case"html":_5(n,s,r);break;default:_5(n,s,r);break}}catch(a){return`Error creating ${o} document: ${a.message}`}return`Created ${n} (genuine ${(o||"html").toUpperCase()} file, theme: ${i.name})`}},g0={midnight:{name:"midnight",primary:"1E2761",secondary:"408EC6",accent:"7A2048",lightBg:"F4F6FB",onDark:"FFFFFF",onLight:"1E2761"},forest:{name:"forest",primary:"2C5F2D",secondary:"97BC62",accent:"D98E04",lightBg:"F5F7F0",onDark:"FFFFFF",onLight:"23401F"},coral:{name:"coral",primary:"2F3C7E",secondary:"F96167",accent:"F9E795",lightBg:"FFF8F0",onDark:"FFFFFF",onLight:"2F3C7E"},ocean:{name:"ocean",primary:"065A82",secondary:"1C7293",accent:"00A896",lightBg:"EEF6F8",onDark:"FFFFFF",onLight:"07314A"},teal:{name:"teal",primary:"028090",secondary:"00A896",accent:"F0A202",lightBg:"EDF7F6",onDark:"FFFFFF",onLight:"023E48"},berry:{name:"berry",primary:"6D2E46",secondary:"A26769",accent:"D5B942",lightBg:"FAF4EF",onDark:"FFFFFF",onLight:"4A1F30"},charcoal:{name:"charcoal",primary:"2D3142",secondary:"4F5D75",accent:"EF8354",lightBg:"F5F5F7",onDark:"FFFFFF",onLight:"2D3142"},cherry:{name:"cherry",primary:"990011",secondary:"CC5803",accent:"2F3C7E",lightBg:"FCF6F5",onDark:"FFFFFF",onLight:"5A0009"}}});var B5={};$(B5,{addRegistry:()=>mwe,buildSkillPrompt:()=>b1,fetchRegistry:()=>g1,getSkill:()=>Nd,getSkillStats:()=>vwe,installFromRegistry:()=>ywe,installSkill:()=>L5,listAllSkills:()=>m1,loadRegistries:()=>Zc,rateSkill:()=>bwe,removeRegistry:()=>gwe,saveRegistries:()=>mg,searchRemote:()=>hwe,searchSkills:()=>p1,trackSkillUse:()=>y1,uninstallSkill:()=>fwe});import{existsSync as fg,mkdirSync as I5,readFileSync as y0,writeFileSync as f1,readdirSync as M5,unlinkSync as owe}from"fs";import{join as ri}from"path";import{homedir as awe}from"os";import{createHash as cwe}from"crypto";function Qc(){I5(pg,{recursive:!0}),I5(dg,{recursive:!0})}function uwe(){let e=m1(),t=new Map,n=new Map,r=[],s=new Map;for(let i of e){t.set(i.name,i);for(let a of i.tags)n.has(a)||n.set(a,[]),n.get(a).push(i);let o=F5(`${i.name} ${i.description} ${i.tags.join(" ")} ${i.examples?.join(" ")||""}`);r.push({skill:i,tokens:o});for(let a of new Set(o))s.set(a,(s.get(a)||0)+1)}return{byName:t,byTag:n,documents:r,docFrequency:s}}function D5(){return h0||(h0=uwe()),h0}function b0(){h0=null}function F5(e){return e.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!dwe.has(t))}function p1(e,t={}){let n=D5(),r=n.documents;if(t.source&&(r=r.filter(a=>a.skill.source===t.source)),t.tags?.length&&(r=r.filter(a=>t.tags.some(c=>a.skill.tags.includes(c)))),t.minRating!==void 0&&(r=r.filter(a=>(a.skill.rating||0)>=t.minRating)),!e.trim())return r.map(a=>a.skill).sort((a,c)=>c.usageCount-a.usageCount).slice(0,t.limit||10);let s=F5(e),i=r.length||1;return r.map(({skill:a,tokens:c})=>{let l=new Map;for(let d of c)l.set(d,(l.get(d)||0)+1);let u=0;for(let d of s){a.name.includes(d)&&(u+=5),a.tags.includes(d)&&(u+=3);let f=(l.get(d)||0)/Math.max(1,c.length),p=n.docFrequency.get(d)||1,m=Math.log(i/p)+1;u+=f*m}return u*=1+a.usageCount*.05,a.rating&&(u*=1+(a.rating-3)*.1),{skill:a,score:u}}).filter(a=>a.score>0).sort((a,c)=>c.score-a.score).slice(0,t.limit||10).map(a=>a.skill)}function m1(){Qc();let e=[];for(let n of lwe)e.push(E5(n,"bundled","<bundled>"));if(fg(dg)){for(let n of M5(dg))if(n.endsWith(".json"))try{let r=ri(dg,n),s=JSON.parse(y0(r,"utf-8"));s.installPath=r,e.push(s)}catch{}}let t=ri(process.cwd(),".aiaca","skills");if(fg(t)){for(let n of M5(t))if(n.endsWith(".json"))try{let r=JSON.parse(y0(ri(t,n),"utf-8"));e.push(E5(r,"project",ri(t,n)))}catch{}}return e}function E5(e,t,n){let r=h1(),s=`${e.name}@${e.version}`;return{...e,id:s,source:t,installedAt:r[s]?.installedAt||new Date().toISOString(),installPath:n,usageCount:r[s]?.usageCount||0,rating:r[s]?.rating,lastUsedAt:r[s]?.lastUsedAt,checksum:O5(e)}}function Nd(e){return D5().byName.get(e)||null}function L5(e,t="local",n){Qc(),pwe(e);let r=`${e.name}@${e.version}`,s=ri(dg,`${r.replace(/[^a-zA-Z0-9.-]/g,"_")}.json`),i={...e,id:r,source:t,installedAt:new Date().toISOString(),installPath:s,usageCount:0,registryUrl:n,checksum:O5(e)};return f1(s,JSON.stringify(i,null,2),"utf-8"),b0(),i}function fwe(e){Qc();let t=Nd(e);if(!t||t.source==="bundled"||!fg(t.installPath))return!1;try{return owe(t.installPath),b0(),!0}catch{return!1}}function pwe(e){if(!e.name||typeof e.name!="string")throw new Error("Invalid skill: missing name");if(!e.version)throw new Error("Invalid skill: missing version");if(!e.description)throw new Error("Invalid skill: missing description");if(!e.prompt)throw new Error("Invalid skill: missing prompt");Array.isArray(e.tags)||(e.tags=[]),Array.isArray(e.parameters)||(e.parameters=[])}function O5(e){let t=JSON.stringify({name:e.name,version:e.version,prompt:e.prompt});return cwe("sha256").update(t).digest("hex").slice(0,16)}function Zc(){if(Qc(),!fg(u1))return mg(l1),l1;try{return JSON.parse(y0(u1,"utf-8"))}catch{return l1}}function mg(e){Qc(),f1(u1,JSON.stringify(e,null,2),"utf-8")}function mwe(e,t,n=!1){let r=Zc();if(r.some(s=>s.name===e))throw new Error(`Registry "${e}" already exists`);r.push({name:e,url:t,trusted:n}),mg(r)}function gwe(e){let t=Zc(),n=t.filter(r=>r.name!==e);return n.length===t.length?!1:(mg(n),!0)}async function g1(e){let t=Zc(),n=t.find(r=>r.name===e);if(!n)return{skills:[],error:`Registry "${e}" not found`};try{let r=await fetch(n.url,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"AIACA/1.0"}});if(!r.ok)return{skills:[],error:`HTTP ${r.status}`};let s=await r.json(),i=Array.isArray(s)?s:s.skills||[];return n.skills=i,n.lastFetched=new Date().toISOString(),mg(t),{skills:i}}catch(r){return{skills:[],error:r.message}}}async function hwe(e,t={}){let n=Zc(),r=[];for(let s of n){if(!s.skills){let{skills:i}=await g1(s.name);s.skills=i}for(let i of s.skills||[])(i.name.toLowerCase().includes(e.toLowerCase())||i.description.toLowerCase().includes(e.toLowerCase())||i.tags.some(a=>a.toLowerCase().includes(e.toLowerCase())))&&(t.tags?.length&&!t.tags.some(a=>i.tags.includes(a))||r.push({skill:i,registry:s.name}))}return r.slice(0,t.limit||20)}async function ywe(e,t){let{skills:n,error:r}=await g1(t);if(r)return{error:r};let s=n.find(i=>i.name===e);return s?L5(s,"remote",Zc().find(i=>i.name===t)?.url):{error:`Skill "${e}" not found in registry "${t}"`}}function h1(){if(Qc(),!fg(d1))return{};try{return JSON.parse(y0(d1,"utf-8"))}catch{return{}}}function j5(e){Qc(),f1(d1,JSON.stringify(e,null,2),"utf-8")}function y1(e){let t=Nd(e);if(!t)return;let n=h1();n[t.id]||(n[t.id]={installedAt:t.installedAt,usageCount:0}),n[t.id].usageCount++,n[t.id].lastUsedAt=new Date().toISOString(),j5(n),b0()}function bwe(e,t){let n=Nd(e);if(!n||t<1||t>5)return!1;let r=h1();return r[n.id]||(r[n.id]={installedAt:n.installedAt,usageCount:0}),r[n.id].rating=t,j5(r),b0(),!0}function b1(e,t){let n=e.prompt;for(let[s,i]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),String(i));let r=e.parameters.filter(s=>t[s.name]!==void 0&&!e.prompt.includes(`{{${s.name}}}`)).map(s=>`${s.name}: ${t[s.name]}`).join(`
1891
+ `),n}function Wi(e){return e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/`(.+?)`/g,"$1")}function ta(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var c1,g0,Pq=w(()=>{"use strict";c1={definition:{name:"doc_create",description:"Create REAL, presentation-grade document files (.docx, .pptx, .xlsx, .pdf, .html) from markdown. Produces genuine Office/PDF files that open natively. Decks and reports are auto-styled with a cohesive color theme, typography, and layout \u2014 not plain bullets.",parameters:[{name:"path",type:"string",description:"Output file path (e.g. notes.docx, slides.pptx, report.pdf, data.xlsx)",required:!0},{name:"content",type:"string",description:'Document content in markdown. For slides, separate each slide with a line containing only "---"; the first line of each block is the slide title, following lines are bullets. For spreadsheets, use markdown tables or CSV rows. Optionally end a slide with a line "note: ..." for speaker notes.',required:!0},{name:"title",type:"string",description:"Document title",required:!1},{name:"theme",type:"string",description:"Visual theme for decks/PDFs. One of: midnight, forest, coral, ocean, teal, berry, charcoal, cherry. Omit to auto-pick a topic-appropriate palette.",required:!1}],requiresPermission:!0},handler:async(e,t)=>{let n=JSe(t.cwd,e.path),r=String(e.content??""),s=e.title||"Document",i=ewe(e.theme,s+" "+r),o=n.split(".").pop()?.toLowerCase();GSe(WSe(n),{recursive:!0});try{switch(o){case"docx":await twe(n,s,r,i);break;case"pptx":await nwe(n,s,r,i);break;case"xlsx":await rwe(n,s,r);break;case"pdf":await swe(n,s,r,i);break;case"html":_q(n,s,r);break;default:_q(n,s,r);break}}catch(a){return`Error creating ${o} document: ${a.message}`}return`Created ${n} (genuine ${(o||"html").toUpperCase()} file, theme: ${i.name})`}},g0={midnight:{name:"midnight",primary:"1E2761",secondary:"408EC6",accent:"7A2048",lightBg:"F4F6FB",onDark:"FFFFFF",onLight:"1E2761"},forest:{name:"forest",primary:"2C5F2D",secondary:"97BC62",accent:"D98E04",lightBg:"F5F7F0",onDark:"FFFFFF",onLight:"23401F"},coral:{name:"coral",primary:"2F3C7E",secondary:"F96167",accent:"F9E795",lightBg:"FFF8F0",onDark:"FFFFFF",onLight:"2F3C7E"},ocean:{name:"ocean",primary:"065A82",secondary:"1C7293",accent:"00A896",lightBg:"EEF6F8",onDark:"FFFFFF",onLight:"07314A"},teal:{name:"teal",primary:"028090",secondary:"00A896",accent:"F0A202",lightBg:"EDF7F6",onDark:"FFFFFF",onLight:"023E48"},berry:{name:"berry",primary:"6D2E46",secondary:"A26769",accent:"D5B942",lightBg:"FAF4EF",onDark:"FFFFFF",onLight:"4A1F30"},charcoal:{name:"charcoal",primary:"2D3142",secondary:"4F5D75",accent:"EF8354",lightBg:"F5F5F7",onDark:"FFFFFF",onLight:"2D3142"},cherry:{name:"cherry",primary:"990011",secondary:"CC5803",accent:"2F3C7E",lightBg:"FCF6F5",onDark:"FFFFFF",onLight:"5A0009"}}});var Bq={};$(Bq,{addRegistry:()=>mwe,buildSkillPrompt:()=>b1,fetchRegistry:()=>g1,getSkill:()=>Nd,getSkillStats:()=>vwe,installFromRegistry:()=>ywe,installSkill:()=>Lq,listAllSkills:()=>m1,loadRegistries:()=>Zc,rateSkill:()=>bwe,removeRegistry:()=>gwe,saveRegistries:()=>mg,searchRemote:()=>hwe,searchSkills:()=>p1,trackSkillUse:()=>y1,uninstallSkill:()=>fwe});import{existsSync as fg,mkdirSync as Iq,readFileSync as y0,writeFileSync as f1,readdirSync as Mq,unlinkSync as owe}from"fs";import{join as ri}from"path";import{homedir as awe}from"os";import{createHash as cwe}from"crypto";function Qc(){Iq(pg,{recursive:!0}),Iq(dg,{recursive:!0})}function uwe(){let e=m1(),t=new Map,n=new Map,r=[],s=new Map;for(let i of e){t.set(i.name,i);for(let a of i.tags)n.has(a)||n.set(a,[]),n.get(a).push(i);let o=Fq(`${i.name} ${i.description} ${i.tags.join(" ")} ${i.examples?.join(" ")||""}`);r.push({skill:i,tokens:o});for(let a of new Set(o))s.set(a,(s.get(a)||0)+1)}return{byName:t,byTag:n,documents:r,docFrequency:s}}function Dq(){return h0||(h0=uwe()),h0}function b0(){h0=null}function Fq(e){return e.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!dwe.has(t))}function p1(e,t={}){let n=Dq(),r=n.documents;if(t.source&&(r=r.filter(a=>a.skill.source===t.source)),t.tags?.length&&(r=r.filter(a=>t.tags.some(c=>a.skill.tags.includes(c)))),t.minRating!==void 0&&(r=r.filter(a=>(a.skill.rating||0)>=t.minRating)),!e.trim())return r.map(a=>a.skill).sort((a,c)=>c.usageCount-a.usageCount).slice(0,t.limit||10);let s=Fq(e),i=r.length||1;return r.map(({skill:a,tokens:c})=>{let l=new Map;for(let d of c)l.set(d,(l.get(d)||0)+1);let u=0;for(let d of s){a.name.includes(d)&&(u+=5),a.tags.includes(d)&&(u+=3);let f=(l.get(d)||0)/Math.max(1,c.length),p=n.docFrequency.get(d)||1,m=Math.log(i/p)+1;u+=f*m}return u*=1+a.usageCount*.05,a.rating&&(u*=1+(a.rating-3)*.1),{skill:a,score:u}}).filter(a=>a.score>0).sort((a,c)=>c.score-a.score).slice(0,t.limit||10).map(a=>a.skill)}function m1(){Qc();let e=[];for(let n of lwe)e.push(Eq(n,"bundled","<bundled>"));if(fg(dg)){for(let n of Mq(dg))if(n.endsWith(".json"))try{let r=ri(dg,n),s=JSON.parse(y0(r,"utf-8"));s.installPath=r,e.push(s)}catch{}}let t=ri(process.cwd(),".aiaca","skills");if(fg(t)){for(let n of Mq(t))if(n.endsWith(".json"))try{let r=JSON.parse(y0(ri(t,n),"utf-8"));e.push(Eq(r,"project",ri(t,n)))}catch{}}return e}function Eq(e,t,n){let r=h1(),s=`${e.name}@${e.version}`;return{...e,id:s,source:t,installedAt:r[s]?.installedAt||new Date().toISOString(),installPath:n,usageCount:r[s]?.usageCount||0,rating:r[s]?.rating,lastUsedAt:r[s]?.lastUsedAt,checksum:Oq(e)}}function Nd(e){return Dq().byName.get(e)||null}function Lq(e,t="local",n){Qc(),pwe(e);let r=`${e.name}@${e.version}`,s=ri(dg,`${r.replace(/[^a-zA-Z0-9.-]/g,"_")}.json`),i={...e,id:r,source:t,installedAt:new Date().toISOString(),installPath:s,usageCount:0,registryUrl:n,checksum:Oq(e)};return f1(s,JSON.stringify(i,null,2),"utf-8"),b0(),i}function fwe(e){Qc();let t=Nd(e);if(!t||t.source==="bundled"||!fg(t.installPath))return!1;try{return owe(t.installPath),b0(),!0}catch{return!1}}function pwe(e){if(!e.name||typeof e.name!="string")throw new Error("Invalid skill: missing name");if(!e.version)throw new Error("Invalid skill: missing version");if(!e.description)throw new Error("Invalid skill: missing description");if(!e.prompt)throw new Error("Invalid skill: missing prompt");Array.isArray(e.tags)||(e.tags=[]),Array.isArray(e.parameters)||(e.parameters=[])}function Oq(e){let t=JSON.stringify({name:e.name,version:e.version,prompt:e.prompt});return cwe("sha256").update(t).digest("hex").slice(0,16)}function Zc(){if(Qc(),!fg(u1))return mg(l1),l1;try{return JSON.parse(y0(u1,"utf-8"))}catch{return l1}}function mg(e){Qc(),f1(u1,JSON.stringify(e,null,2),"utf-8")}function mwe(e,t,n=!1){let r=Zc();if(r.some(s=>s.name===e))throw new Error(`Registry "${e}" already exists`);r.push({name:e,url:t,trusted:n}),mg(r)}function gwe(e){let t=Zc(),n=t.filter(r=>r.name!==e);return n.length===t.length?!1:(mg(n),!0)}async function g1(e){let t=Zc(),n=t.find(r=>r.name===e);if(!n)return{skills:[],error:`Registry "${e}" not found`};try{let r=await fetch(n.url,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"AIACA/1.0"}});if(!r.ok)return{skills:[],error:`HTTP ${r.status}`};let s=await r.json(),i=Array.isArray(s)?s:s.skills||[];return n.skills=i,n.lastFetched=new Date().toISOString(),mg(t),{skills:i}}catch(r){return{skills:[],error:r.message}}}async function hwe(e,t={}){let n=Zc(),r=[];for(let s of n){if(!s.skills){let{skills:i}=await g1(s.name);s.skills=i}for(let i of s.skills||[])(i.name.toLowerCase().includes(e.toLowerCase())||i.description.toLowerCase().includes(e.toLowerCase())||i.tags.some(a=>a.toLowerCase().includes(e.toLowerCase())))&&(t.tags?.length&&!t.tags.some(a=>i.tags.includes(a))||r.push({skill:i,registry:s.name}))}return r.slice(0,t.limit||20)}async function ywe(e,t){let{skills:n,error:r}=await g1(t);if(r)return{error:r};let s=n.find(i=>i.name===e);return s?Lq(s,"remote",Zc().find(i=>i.name===t)?.url):{error:`Skill "${e}" not found in registry "${t}"`}}function h1(){if(Qc(),!fg(d1))return{};try{return JSON.parse(y0(d1,"utf-8"))}catch{return{}}}function jq(e){Qc(),f1(d1,JSON.stringify(e,null,2),"utf-8")}function y1(e){let t=Nd(e);if(!t)return;let n=h1();n[t.id]||(n[t.id]={installedAt:t.installedAt,usageCount:0}),n[t.id].usageCount++,n[t.id].lastUsedAt=new Date().toISOString(),jq(n),b0()}function bwe(e,t){let n=Nd(e);if(!n||t<1||t>5)return!1;let r=h1();return r[n.id]||(r[n.id]={installedAt:n.installedAt,usageCount:0}),r[n.id].rating=t,jq(r),b0(),!0}function b1(e,t){let n=e.prompt;for(let[s,i]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),String(i));let r=e.parameters.filter(s=>t[s.name]!==void 0&&!e.prompt.includes(`{{${s.name}}}`)).map(s=>`${s.name}: ${t[s.name]}`).join(`
1862
1892
  `);return r&&(n+=`
1863
1893
 
1864
1894
  Parameters:
1865
- `+r),n}function vwe(){let e=m1(),t=Zc(),n=[...e].sort((r,s)=>s.usageCount-r.usageCount).slice(0,5).map(r=>({name:r.name,uses:r.usageCount}));return{totalInstalled:e.length,bundled:e.filter(r=>r.source==="bundled").length,localInstalled:e.filter(r=>r.source==="local"||r.source==="remote").length,project:e.filter(r=>r.source==="project").length,totalRegistries:t.length,topUsed:n}}var pg,dg,u1,WDe,d1,lwe,h0,dwe,l1,v1=w(()=>{"use strict";pg=ri(awe(),".aiaca","skills"),dg=ri(pg,"installed"),u1=ri(pg,"registries.json"),WDe=ri(pg,"index.json"),d1=ri(pg,"stats.json");lwe=[{name:"code-review",version:"1.0.0",description:"Perform a thorough code review of changes",tags:["review","quality","git"],parameters:[{name:"scope",type:"string",description:"What to review (file/diff/branch)",required:!1}],prompt:"Review the code carefully for: bugs, security issues, performance, maintainability, style. Use git diff for recent changes if no scope given. Provide actionable feedback with file:line references.",tools:["file_read","grep","bash"],examples:["Review my last commit","Review changes to src/auth/"]},{name:"test-writer",version:"1.0.0",description:"Generate comprehensive tests for code",tags:["testing","quality"],parameters:[{name:"file",type:"string",description:"File to test",required:!0}],prompt:"Generate comprehensive unit tests including edge cases, error handling, and happy path. Match the project's existing test framework and style.",tools:["file_read","file_write","bash","glob"],examples:["Write tests for src/utils/parser.ts"]},{name:"refactor",version:"1.0.0",description:"Refactor code for clarity and maintainability",tags:["refactor","quality"],parameters:[{name:"target",type:"string",description:"File or function to refactor",required:!0}],prompt:"Refactor while preserving exact behavior. Improve: naming, structure, abstractions, type safety. Write tests first if missing. Verify tests pass after.",tools:["file_read","file_edit","bash","grep"],examples:["Refactor the auth module"]},{name:"doc-generator",version:"1.0.0",description:"Generate documentation from code",tags:["docs","readme"],parameters:[{name:"type",type:"string",description:"readme/api/architecture",required:!1}],prompt:"Generate clear, structured documentation. Include: overview, setup, usage, examples, architecture. Use proper Markdown formatting.",tools:["file_read","glob","doc_create","file_write"],examples:["Generate a README","Document the API"]},{name:"bug-hunter",version:"1.0.0",description:"Find and fix bugs in the codebase",tags:["debug","bugs"],parameters:[{name:"description",type:"string",description:"Bug description",required:!0}],prompt:"Reproduce the bug, identify root cause, fix it, and verify with tests. Don't suppress symptoms \u2014 fix the underlying issue.",tools:["file_read","file_edit","bash","grep","glob"],examples:["Fix the login error","Find why the build is failing"]},{name:"security-audit",version:"1.0.0",description:"Audit code for security vulnerabilities",tags:["security","audit"],parameters:[],prompt:"Audit for: SQL injection, XSS, CSRF, secrets in code, weak crypto, auth bypasses, unsafe deserialization, race conditions, unsafe regex. Report findings with severity and fix recommendations.",tools:["grep","glob","file_read","web_search"],examples:["Audit my authentication code"]},{name:"perf-optimize",version:"1.0.0",description:"Profile and optimize code performance",tags:["performance","optimization"],parameters:[{name:"target",type:"string",description:"What to optimize",required:!1}],prompt:"Profile the code, identify bottlenecks (algorithmic, I/O, memory), implement optimizations, and benchmark to verify improvements.",tools:["file_read","file_edit","bash","grep"],examples:["Optimize the database queries"]},{name:"migration",version:"1.0.0",description:"Migrate code between frameworks/versions",tags:["migration","upgrade"],parameters:[{name:"from",type:"string",description:"Source (e.g. react-17)",required:!0},{name:"to",type:"string",description:"Target (e.g. react-18)",required:!0}],prompt:"Plan the migration step-by-step. Update dependencies, code, tests. Handle breaking changes. Verify after each step.",tools:["file_read","file_edit","bash","web_search","glob"],examples:["Migrate from CommonJS to ESM"]},{name:"api-design",version:"1.0.0",description:"Design REST/GraphQL APIs",tags:["api","design","architecture"],parameters:[{name:"description",type:"string",description:"API requirements",required:!0}],prompt:"Design a clean API: endpoints, request/response schemas, error handling, auth, versioning, pagination. Generate OpenAPI/GraphQL schema.",tools:["file_write","doc_create","web_search"],examples:["Design a user management API"]},{name:"database-design",version:"1.0.0",description:"Design database schemas",tags:["database","schema"],parameters:[{name:"requirements",type:"string",description:"Domain requirements",required:!0}],prompt:"Design a normalized schema with proper relationships, indexes, constraints. Include migration scripts. Consider query patterns.",tools:["file_write","web_search"],examples:["Design a schema for an e-commerce app"]}],h0=null;dwe=new Set(["a","an","the","and","or","for","in","on","at","to","of","with","is","are"]);l1=[]});var N5,q5,U5=w(()=>{"use strict";v1();N5={definition:{name:"skill",description:"Invoke a registered skill (reusable agent capability). Use skill_search to find skills first.",parameters:[{name:"name",type:"string",description:'Skill name (e.g. "code-review")',required:!0},{name:"params",type:"object",description:"Skill parameters as JSON object",required:!1}]},handler:async(e,t)=>{let n=String(e.name||"");if(!n)return"Error: skill name required";let r=Nd(n);if(!r)return`Error: skill "${n}" not found. Use skill_search to find available skills.`;let s=e.params||{},i=r.parameters.filter(a=>a.required&&s[a.name]===void 0);if(i.length>0)return`Error: missing required parameters: ${i.map(a=>a.name).join(", ")}`;y1(n);let o=b1(r,s);return`[Skill: ${r.name} v${r.version}]
1895
+ `+r),n}function vwe(){let e=m1(),t=Zc(),n=[...e].sort((r,s)=>s.usageCount-r.usageCount).slice(0,5).map(r=>({name:r.name,uses:r.usageCount}));return{totalInstalled:e.length,bundled:e.filter(r=>r.source==="bundled").length,localInstalled:e.filter(r=>r.source==="local"||r.source==="remote").length,project:e.filter(r=>r.source==="project").length,totalRegistries:t.length,topUsed:n}}var pg,dg,u1,WDe,d1,lwe,h0,dwe,l1,v1=w(()=>{"use strict";pg=ri(awe(),".aiaca","skills"),dg=ri(pg,"installed"),u1=ri(pg,"registries.json"),WDe=ri(pg,"index.json"),d1=ri(pg,"stats.json");lwe=[{name:"code-review",version:"1.0.0",description:"Perform a thorough code review of changes",tags:["review","quality","git"],parameters:[{name:"scope",type:"string",description:"What to review (file/diff/branch)",required:!1}],prompt:"Review the code carefully for: bugs, security issues, performance, maintainability, style. Use git diff for recent changes if no scope given. Provide actionable feedback with file:line references.",tools:["file_read","grep","bash"],examples:["Review my last commit","Review changes to src/auth/"]},{name:"test-writer",version:"1.0.0",description:"Generate comprehensive tests for code",tags:["testing","quality"],parameters:[{name:"file",type:"string",description:"File to test",required:!0}],prompt:"Generate comprehensive unit tests including edge cases, error handling, and happy path. Match the project's existing test framework and style.",tools:["file_read","file_write","bash","glob"],examples:["Write tests for src/utils/parser.ts"]},{name:"refactor",version:"1.0.0",description:"Refactor code for clarity and maintainability",tags:["refactor","quality"],parameters:[{name:"target",type:"string",description:"File or function to refactor",required:!0}],prompt:"Refactor while preserving exact behavior. Improve: naming, structure, abstractions, type safety. Write tests first if missing. Verify tests pass after.",tools:["file_read","file_edit","bash","grep"],examples:["Refactor the auth module"]},{name:"doc-generator",version:"1.0.0",description:"Generate documentation from code",tags:["docs","readme"],parameters:[{name:"type",type:"string",description:"readme/api/architecture",required:!1}],prompt:"Generate clear, structured documentation. Include: overview, setup, usage, examples, architecture. Use proper Markdown formatting.",tools:["file_read","glob","doc_create","file_write"],examples:["Generate a README","Document the API"]},{name:"bug-hunter",version:"1.0.0",description:"Find and fix bugs in the codebase",tags:["debug","bugs"],parameters:[{name:"description",type:"string",description:"Bug description",required:!0}],prompt:"Reproduce the bug, identify root cause, fix it, and verify with tests. Don't suppress symptoms \u2014 fix the underlying issue.",tools:["file_read","file_edit","bash","grep","glob"],examples:["Fix the login error","Find why the build is failing"]},{name:"security-audit",version:"1.0.0",description:"Audit code for security vulnerabilities",tags:["security","audit"],parameters:[],prompt:"Audit for: SQL injection, XSS, CSRF, secrets in code, weak crypto, auth bypasses, unsafe deserialization, race conditions, unsafe regex. Report findings with severity and fix recommendations.",tools:["grep","glob","file_read","web_search"],examples:["Audit my authentication code"]},{name:"perf-optimize",version:"1.0.0",description:"Profile and optimize code performance",tags:["performance","optimization"],parameters:[{name:"target",type:"string",description:"What to optimize",required:!1}],prompt:"Profile the code, identify bottlenecks (algorithmic, I/O, memory), implement optimizations, and benchmark to verify improvements.",tools:["file_read","file_edit","bash","grep"],examples:["Optimize the database queries"]},{name:"migration",version:"1.0.0",description:"Migrate code between frameworks/versions",tags:["migration","upgrade"],parameters:[{name:"from",type:"string",description:"Source (e.g. react-17)",required:!0},{name:"to",type:"string",description:"Target (e.g. react-18)",required:!0}],prompt:"Plan the migration step-by-step. Update dependencies, code, tests. Handle breaking changes. Verify after each step.",tools:["file_read","file_edit","bash","web_search","glob"],examples:["Migrate from CommonJS to ESM"]},{name:"api-design",version:"1.0.0",description:"Design REST/GraphQL APIs",tags:["api","design","architecture"],parameters:[{name:"description",type:"string",description:"API requirements",required:!0}],prompt:"Design a clean API: endpoints, request/response schemas, error handling, auth, versioning, pagination. Generate OpenAPI/GraphQL schema.",tools:["file_write","doc_create","web_search"],examples:["Design a user management API"]},{name:"database-design",version:"1.0.0",description:"Design database schemas",tags:["database","schema"],parameters:[{name:"requirements",type:"string",description:"Domain requirements",required:!0}],prompt:"Design a normalized schema with proper relationships, indexes, constraints. Include migration scripts. Consider query patterns.",tools:["file_write","web_search"],examples:["Design a schema for an e-commerce app"]}],h0=null;dwe=new Set(["a","an","the","and","or","for","in","on","at","to","of","with","is","are"]);l1=[]});var Nq,qq,Uq=w(()=>{"use strict";v1();Nq={definition:{name:"skill",description:"Invoke a registered skill (reusable agent capability). Use skill_search to find skills first.",parameters:[{name:"name",type:"string",description:'Skill name (e.g. "code-review")',required:!0},{name:"params",type:"object",description:"Skill parameters as JSON object",required:!1}]},handler:async(e,t)=>{let n=String(e.name||"");if(!n)return"Error: skill name required";let r=Nd(n);if(!r)return`Error: skill "${n}" not found. Use skill_search to find available skills.`;let s=e.params||{},i=r.parameters.filter(a=>a.required&&s[a.name]===void 0);if(i.length>0)return`Error: missing required parameters: ${i.map(a=>a.name).join(", ")}`;y1(n);let o=b1(r,s);return`[Skill: ${r.name} v${r.version}]
1866
1896
  ${r.description}
1867
1897
 
1868
1898
  FOLLOW THESE INSTRUCTIONS:
1869
1899
  ${o}
1870
1900
 
1871
- Required tools: ${r.tools?.join(", ")||"any"}`}},q5={definition:{name:"skill_search",description:"Search for available skills (reusable agent capabilities) by query or tags.",parameters:[{name:"query",type:"string",description:"Search query",required:!1},{name:"tags",type:"array",description:'Filter by tags (e.g. ["testing", "review"])',required:!1},{name:"limit",type:"number",description:"Max results (default 10)",required:!1}]},handler:async e=>{let t=String(e.query||""),n=Array.isArray(e.tags)?e.tags:void 0,r=Number(e.limit)||10,s=p1(t,{tags:n,limit:r});return s.length===0?"No matching skills found.":s.map(i=>`[${i.name}] v${i.version} (${i.source})
1901
+ Required tools: ${r.tools?.join(", ")||"any"}`}},qq={definition:{name:"skill_search",description:"Search for available skills (reusable agent capabilities) by query or tags.",parameters:[{name:"query",type:"string",description:"Search query",required:!1},{name:"tags",type:"array",description:'Filter by tags (e.g. ["testing", "review"])',required:!1},{name:"limit",type:"number",description:"Max results (default 10)",required:!1}]},handler:async e=>{let t=String(e.query||""),n=Array.isArray(e.tags)?e.tags:void 0,r=Number(e.limit)||10,s=p1(t,{tags:n,limit:r});return s.length===0?"No matching skills found.":s.map(i=>`[${i.name}] v${i.version} (${i.source})
1872
1902
  ${i.description}
1873
1903
  Tags: ${i.tags.join(", ")}
1874
1904
  Params: ${i.parameters.map(o=>`${o.name}${o.required?"*":""}`).join(", ")||"(none)"}`).join(`
1875
1905
 
1876
- `)}}});var T5={};$(T5,{findTool:()=>wr,getToolDefinitions:()=>Jm,getToolNames:()=>hg,getTools:()=>e_,getToolsByCategory:()=>wwe});function e_(){return gg}function Jm(e){if(e&&e.length>0){let t=new Set(e);return gg.filter(n=>t.has(n.definition.name)).map(n=>n.definition)}return gg.filter(t=>Swe.has(t.definition.name)).map(t=>t.definition)}function wr(e){return gg.find(t=>t.definition.name===e)}function hg(){return gg.map(e=>e.definition.name)}function wwe(){return{"File Operations":[_w,tx,rx,VR,c1],Search:[sx,ox],Shell:[nw,...process.platform==="win32"?[gx]:[]],Web:[px,mx],Image:[Nb,qb],"Tasks & Agents":[Tx,_x,Rx,Px,HR,zR,GR],Modes:[KR,YR,QR,ZR],Team:[XR,e1,t1],Productivity:[$x,JR,WR,n1],System:[r1,s1,i1,o1]}}var gg,Swe,Ls=w(()=>{"use strict";OI();yM();FD();UD();KD();tF();fF();pF();mF();hF();yF();A5();P5();Lm();U5();gg=[_w,tx,rx,VR,c1,sx,ox,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,e5,t5,n5,r5,s5,i5,o5,a5,c5,l5,u5,d5,f5,p5,m5,g5,h5,y5,b5,v5,S5,w5,k5,x5,$5,C5,nw,...process.platform==="win32"?[gx]:[],px,mx,Nb,qb,N5,q5,Tx,_x,Rx,Px,HR,zR,GR,$x,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1];Swe=new Set(["file_read","file_write","file_edit","notebook_edit","glob","grep","code_search","code_index","code_references","find_callers","impact_analysis","nl_search","tool_search","bash","powershell","web_fetch","web_search","search_past_work","analyze_code","detect_smells","generate_tests","find_untested","infer_types","doc_create","spawn_specialist","spawn_pipeline","agent","todo_write","enter_plan_mode","exit_plan_mode","task_create","task_get","task_list","task_update","task_output","task_stop","skill","skill_search","ask_user","image_read","clipboard_image","diff_preview","explain","cron_create","cron_list","cron_delete"])});var aq={};$(aq,{addInterceptor:()=>Bwe,compareCassettes:()=>Uwe,createCassette:()=>k1,deleteCassette:()=>Lwe,exportCassetteAsJSONL:()=>qwe,findReplay:()=>bg,getActiveCassette:()=>jwe,getCassetteStats:()=>Nwe,getMode:()=>Owe,getVCRDir:()=>Hwe,listCassettes:()=>Fwe,loadCassette:()=>qd,record:()=>Xc,saveCassette:()=>A1,setMode:()=>iq,shouldRecord:()=>el,shouldReplay:()=>vg,withCassette:()=>zwe});import{existsSync as rq,mkdirSync as Pwe,readFileSync as sq,writeFileSync as x1,readdirSync as Iwe,statSync as Mwe}from"fs";import{join as $1}from"path";import{homedir as Ewe}from"os";import{createHash as Dwe}from"crypto";function C1(){Pwe(yg,{recursive:!0})}function k1(e,t={}){let n={name:e,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),episodes:[],metadata:t};return A1(n),n}function qd(e){C1();let t=T1(e);if(!rq(t))return null;try{return JSON.parse(sq(t,"utf-8"))}catch{return null}}function A1(e){C1(),e.updatedAt=new Date().toISOString(),x1(T1(e.name),JSON.stringify(e,null,2),"utf-8")}function Fwe(){return C1(),Iwe(yg).filter(e=>e.endsWith(".json")).map(e=>{try{let t=$1(yg,e),n=JSON.parse(sq(t,"utf-8")),r=Mwe(t);return{name:n.name,episodeCount:n.episodes.length,sizeKB:Math.round(r.size/1024),createdAt:n.createdAt,updatedAt:n.updatedAt}}catch{return null}}).filter(Boolean)}function Lwe(e){let t=T1(e);if(!rq(t))return!1;try{return x1(t,"","utf-8"),!0}catch{return!1}}function iq(e,t){if(Gr=e,e==="passthrough"){Ar=null;return}if(!t)throw new Error(`VCR mode "${e}" requires a cassette name`);let n=qd(t);if(e==="record")Ar=n||k1(t),Ar.episodes=[];else if(e==="replay"){if(!n)throw new Error(`Cassette "${t}" not found for replay`);Ar=n}else e==="new_episodes"&&(Ar=n||k1(t))}function Owe(){return Gr}function jwe(){return Ar}function Xc(e,t){let n={id:`ep_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,request:e,response:t,requestHash:oq(e)};Ar&&(Gr==="record"||Gr==="new_episodes")&&(Ar.episodes.push(n),A1(Ar));for(let r of S0)try{r(n)}catch{}return n}function bg(e){if(!Ar||Gr==="passthrough"||Gr==="record")return null;let t=oq(e),n=Ar.episodes.find(r=>r.requestHash===t);return n?n.response:null}function vg(){return Gr==="replay"||Gr==="new_episodes"}function el(){return Gr==="record"||Gr==="new_episodes"}function oq(e){let t={provider:e.provider,model:e.model,systemPrompt:e.systemPrompt,messages:e.messages.map(n=>({role:n.role,content:n.content})),tools:[...e.tools].sort()};return Dwe("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}function Bwe(e){return S0.push(e),()=>{let t=S0.indexOf(e);t!==-1&&S0.splice(t,1)}}function Nwe(e){let t=qd(e);if(!t)return null;let n=0,r=0,s=0,i=0;for(let o of t.episodes)n+=o.response.durationMs,r+=o.response.usage?.inputTokens||0,s+=o.response.usage?.outputTokens||0,i+=o.response.toolCalls.length;return{episodes:t.episodes.length,totalDurationMs:n,avgDurationMs:t.episodes.length?Math.round(n/t.episodes.length):0,totalInputTokens:r,totalOutputTokens:s,toolCallCount:i}}function qwe(e,t){let n=qd(e);if(!n)return!1;try{let r=n.episodes.map(s=>JSON.stringify(s));return x1(t,r.join(`
1877
- `),"utf-8"),!0}catch{return!1}}function Uwe(e,t){let n=qd(e),r=qd(t);if(!n||!r)return{matching:0,differing:0,only1:0,only2:0,differences:[]};let s=new Map(n.episodes.map(d=>[d.requestHash,d])),i=new Map(r.episodes.map(d=>[d.requestHash,d])),o=0,a=0,c=[];for(let[d,f]of s){let p=i.get(d);p&&(f.response.content===p.response.content?o++:(a++,c.push({requestHash:d,reason:"Response content differs"})))}let l=[...s.keys()].filter(d=>!i.has(d)).length,u=[...i.keys()].filter(d=>!s.has(d)).length;return{matching:o,differing:a,only1:l,only2:u,differences:c}}function T1(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return $1(yg,`${t}.json`)}function Hwe(){return yg}function zwe(e,t,n){let r=Gr,s=Ar;return iq(t,e),n().finally(()=>{Gr=r,Ar=s})}var yg,Gr,Ar,S0,w0=w(()=>{"use strict";yg=$1(Ewe(),".aiaca","cassettes"),Gr="passthrough",Ar=null,S0=[]});var $0={};$($0,{captureSnapshot:()=>dq,clearAllSnapshots:()=>mke,clearProjectSnapshots:()=>pke,computeDiff:()=>mq,diffSinceLastSession:()=>dke,formatBriefing:()=>M1,getDiffTrackerStats:()=>fke,getLastSnapshot:()=>fq,listSnapshots:()=>ake,loadSnapshot:()=>pq});import{existsSync as Tr,mkdirSync as Gwe,readFileSync as si,writeFileSync as cq,readdirSync as k0,unlinkSync as P1,statSync as Vwe}from"fs";import{join as Zn,resolve as Ud,relative as Jwe}from"path";import{homedir as Wwe}from"os";import{createHash as Sg}from"crypto";import{execSync as na}from"child_process";import{glob as Kwe}from"glob";function Ywe(e){return Sg("sha256").update(Ud(e)).digest("hex").slice(0,16)}function x0(e){return Zn(tl,Ywe(e))}function lq(e){Gwe(x0(e),{recursive:!0})}function R1(e,t){return Zn(x0(e),`${t}.json`)}function uq(e){return Zn(x0(e),"index.json")}async function tke(e){let t=[];for(let l of Qwe)try{let u=await Kwe(l,{cwd:e,absolute:!0,ignore:Zwe,nodir:!0});t.push(...u)}catch{}let n={},r={},s=new Set,i=[],o=0,a=t.map(l=>{try{return{f:l,stat:Vwe(l)}}catch{return null}}).filter(l=>l!==null&&!l.stat.isDirectory()).sort((l,u)=>u.stat.mtimeMs-l.stat.mtimeMs),c=0;for(let{f:l,stat:u}of a){let d=Jwe(e,l).replace(/\\/g,"/"),f=(d.match(/\.([^./\\]+)$/)||["","noext"])[1].toLowerCase();n[f]=(n[f]||0)+1,o+=u.size;let p=d.split("/")[0];if(p&&s.add(p),i.length<20&&i.push({path:d,mtime:u.mtimeMs}),c<Xwe&&u.size<eke)try{let m=si(l),g=Sg("sha256").update(m).digest("hex").slice(0,16),h=m.toString("utf-8",0,Math.min(m.length,1e5)).split(`
1906
+ `)}}});var Tq={};$(Tq,{findTool:()=>wr,getToolDefinitions:()=>Jm,getToolNames:()=>hg,getTools:()=>e_,getToolsByCategory:()=>wwe});function e_(){return gg}function Jm(e){if(e&&e.length>0){let t=new Set(e);return gg.filter(n=>t.has(n.definition.name)).map(n=>n.definition)}return gg.filter(t=>Swe.has(t.definition.name)).map(t=>t.definition)}function wr(e){return gg.find(t=>t.definition.name===e)}function hg(){return gg.map(e=>e.definition.name)}function wwe(){return{"File Operations":[_w,tx,rx,VR,c1],Search:[sx,ox],Shell:[nw,...process.platform==="win32"?[gx]:[]],Web:[px,mx],Image:[Nb,qb],"Tasks & Agents":[Tx,_x,Rx,Px,HR,zR,GR],Modes:[KR,YR,QR,ZR],Team:[XR,e1,t1],Productivity:[$x,JR,WR,n1],System:[r1,s1,i1,o1]}}var gg,Swe,Ls=w(()=>{"use strict";OI();yM();FD();UD();KD();tF();fF();pF();mF();hF();yF();Aq();Pq();Lm();Uq();gg=[_w,tx,rx,VR,c1,sx,ox,h2,y2,b2,v2,S2,w2,k2,x2,$2,C2,A2,T2,_2,R2,P2,I2,M2,E2,D2,F2,L2,O2,j2,B2,N2,q2,U2,H2,z2,G2,V2,J2,W2,K2,Y2,Q2,Z2,X2,eq,tq,nq,rq,sq,iq,oq,aq,cq,lq,uq,dq,fq,pq,mq,gq,hq,yq,bq,vq,Sq,wq,kq,xq,$q,Cq,nw,...process.platform==="win32"?[gx]:[],px,mx,Nb,qb,Nq,qq,Tx,_x,Rx,Px,HR,zR,GR,$x,JR,WR,KR,YR,QR,ZR,XR,e1,t1,n1,r1,s1,i1,o1];Swe=new Set(["file_read","file_write","file_edit","notebook_edit","glob","grep","code_search","code_index","code_references","find_callers","impact_analysis","nl_search","tool_search","bash","powershell","web_fetch","web_search","search_past_work","analyze_code","detect_smells","generate_tests","find_untested","infer_types","doc_create","spawn_specialist","spawn_pipeline","agent","todo_write","enter_plan_mode","exit_plan_mode","task_create","task_get","task_list","task_update","task_output","task_stop","skill","skill_search","ask_user","image_read","clipboard_image","diff_preview","explain","cron_create","cron_list","cron_delete"])});var a5={};$(a5,{addInterceptor:()=>Bwe,compareCassettes:()=>Uwe,createCassette:()=>k1,deleteCassette:()=>Lwe,exportCassetteAsJSONL:()=>qwe,findReplay:()=>bg,getActiveCassette:()=>jwe,getCassetteStats:()=>Nwe,getMode:()=>Owe,getVCRDir:()=>Hwe,listCassettes:()=>Fwe,loadCassette:()=>qd,record:()=>Xc,saveCassette:()=>A1,setMode:()=>i5,shouldRecord:()=>el,shouldReplay:()=>vg,withCassette:()=>zwe});import{existsSync as r5,mkdirSync as Pwe,readFileSync as s5,writeFileSync as x1,readdirSync as Iwe,statSync as Mwe}from"fs";import{join as $1}from"path";import{homedir as Ewe}from"os";import{createHash as Dwe}from"crypto";function C1(){Pwe(yg,{recursive:!0})}function k1(e,t={}){let n={name:e,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),episodes:[],metadata:t};return A1(n),n}function qd(e){C1();let t=T1(e);if(!r5(t))return null;try{return JSON.parse(s5(t,"utf-8"))}catch{return null}}function A1(e){C1(),e.updatedAt=new Date().toISOString(),x1(T1(e.name),JSON.stringify(e,null,2),"utf-8")}function Fwe(){return C1(),Iwe(yg).filter(e=>e.endsWith(".json")).map(e=>{try{let t=$1(yg,e),n=JSON.parse(s5(t,"utf-8")),r=Mwe(t);return{name:n.name,episodeCount:n.episodes.length,sizeKB:Math.round(r.size/1024),createdAt:n.createdAt,updatedAt:n.updatedAt}}catch{return null}}).filter(Boolean)}function Lwe(e){let t=T1(e);if(!r5(t))return!1;try{return x1(t,"","utf-8"),!0}catch{return!1}}function i5(e,t){if(Gr=e,e==="passthrough"){Ar=null;return}if(!t)throw new Error(`VCR mode "${e}" requires a cassette name`);let n=qd(t);if(e==="record")Ar=n||k1(t),Ar.episodes=[];else if(e==="replay"){if(!n)throw new Error(`Cassette "${t}" not found for replay`);Ar=n}else e==="new_episodes"&&(Ar=n||k1(t))}function Owe(){return Gr}function jwe(){return Ar}function Xc(e,t){let n={id:`ep_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,request:e,response:t,requestHash:o5(e)};Ar&&(Gr==="record"||Gr==="new_episodes")&&(Ar.episodes.push(n),A1(Ar));for(let r of S0)try{r(n)}catch{}return n}function bg(e){if(!Ar||Gr==="passthrough"||Gr==="record")return null;let t=o5(e),n=Ar.episodes.find(r=>r.requestHash===t);return n?n.response:null}function vg(){return Gr==="replay"||Gr==="new_episodes"}function el(){return Gr==="record"||Gr==="new_episodes"}function o5(e){let t={provider:e.provider,model:e.model,systemPrompt:e.systemPrompt,messages:e.messages.map(n=>({role:n.role,content:n.content})),tools:[...e.tools].sort()};return Dwe("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}function Bwe(e){return S0.push(e),()=>{let t=S0.indexOf(e);t!==-1&&S0.splice(t,1)}}function Nwe(e){let t=qd(e);if(!t)return null;let n=0,r=0,s=0,i=0;for(let o of t.episodes)n+=o.response.durationMs,r+=o.response.usage?.inputTokens||0,s+=o.response.usage?.outputTokens||0,i+=o.response.toolCalls.length;return{episodes:t.episodes.length,totalDurationMs:n,avgDurationMs:t.episodes.length?Math.round(n/t.episodes.length):0,totalInputTokens:r,totalOutputTokens:s,toolCallCount:i}}function qwe(e,t){let n=qd(e);if(!n)return!1;try{let r=n.episodes.map(s=>JSON.stringify(s));return x1(t,r.join(`
1907
+ `),"utf-8"),!0}catch{return!1}}function Uwe(e,t){let n=qd(e),r=qd(t);if(!n||!r)return{matching:0,differing:0,only1:0,only2:0,differences:[]};let s=new Map(n.episodes.map(d=>[d.requestHash,d])),i=new Map(r.episodes.map(d=>[d.requestHash,d])),o=0,a=0,c=[];for(let[d,f]of s){let p=i.get(d);p&&(f.response.content===p.response.content?o++:(a++,c.push({requestHash:d,reason:"Response content differs"})))}let l=[...s.keys()].filter(d=>!i.has(d)).length,u=[...i.keys()].filter(d=>!s.has(d)).length;return{matching:o,differing:a,only1:l,only2:u,differences:c}}function T1(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return $1(yg,`${t}.json`)}function Hwe(){return yg}function zwe(e,t,n){let r=Gr,s=Ar;return i5(t,e),n().finally(()=>{Gr=r,Ar=s})}var yg,Gr,Ar,S0,w0=w(()=>{"use strict";yg=$1(Ewe(),".aiaca","cassettes"),Gr="passthrough",Ar=null,S0=[]});var $0={};$($0,{captureSnapshot:()=>d5,clearAllSnapshots:()=>mke,clearProjectSnapshots:()=>pke,computeDiff:()=>m5,diffSinceLastSession:()=>dke,formatBriefing:()=>M1,getDiffTrackerStats:()=>fke,getLastSnapshot:()=>f5,listSnapshots:()=>ake,loadSnapshot:()=>p5});import{existsSync as Tr,mkdirSync as Gwe,readFileSync as si,writeFileSync as c5,readdirSync as k0,unlinkSync as P1,statSync as Vwe}from"fs";import{join as Zn,resolve as Ud,relative as Jwe}from"path";import{homedir as Wwe}from"os";import{createHash as Sg}from"crypto";import{execSync as na}from"child_process";import{glob as Kwe}from"glob";function Ywe(e){return Sg("sha256").update(Ud(e)).digest("hex").slice(0,16)}function x0(e){return Zn(tl,Ywe(e))}function l5(e){Gwe(x0(e),{recursive:!0})}function R1(e,t){return Zn(x0(e),`${t}.json`)}function u5(e){return Zn(x0(e),"index.json")}async function tke(e){let t=[];for(let l of Qwe)try{let u=await Kwe(l,{cwd:e,absolute:!0,ignore:Zwe,nodir:!0});t.push(...u)}catch{}let n={},r={},s=new Set,i=[],o=0,a=t.map(l=>{try{return{f:l,stat:Vwe(l)}}catch{return null}}).filter(l=>l!==null&&!l.stat.isDirectory()).sort((l,u)=>u.stat.mtimeMs-l.stat.mtimeMs),c=0;for(let{f:l,stat:u}of a){let d=Jwe(e,l).replace(/\\/g,"/"),f=(d.match(/\.([^./\\]+)$/)||["","noext"])[1].toLowerCase();n[f]=(n[f]||0)+1,o+=u.size;let p=d.split("/")[0];if(p&&s.add(p),i.length<20&&i.push({path:d,mtime:u.mtimeMs}),c<Xwe&&u.size<eke)try{let m=si(l),g=Sg("sha256").update(m).digest("hex").slice(0,16),h=m.toString("utf-8",0,Math.min(m.length,1e5)).split(`
1878
1908
  `).length;r[d]={hash:g,size:u.size,mtime:u.mtimeMs,lines:h},c++}catch{}}return{totalCount:t.length,byExtension:n,topLevelDirs:Array.from(s).sort(),totalSizeKB:Math.round(o/1024),trackedFiles:r,recentlyModified:i}}function nke(e){let t={isRepo:!1,isDirty:!1,modifiedFiles:[],untrackedFiles:[],stashCount:0,recentCommits:[]};try{na("git rev-parse --git-dir",{cwd:e,stdio:"pipe"}),t.isRepo=!0}catch{return t}try{t.branch=na("git rev-parse --abbrev-ref HEAD",{cwd:e,stdio:"pipe"}).toString().trim()}catch{}try{t.head=na("git rev-parse HEAD",{cwd:e,stdio:"pipe"}).toString().trim().slice(0,12)}catch{}try{let r=na("git status --porcelain",{cwd:e,stdio:"pipe"}).toString().split(`
1879
1909
  `).filter(Boolean);for(let s of r){let i=s.slice(0,2),o=s.slice(3);i.startsWith("??")?t.untrackedFiles.push(o):t.modifiedFiles.push(o)}t.isDirty=r.length>0}catch{}try{let n=na("git stash list",{cwd:e,stdio:"pipe"}).toString();t.stashCount=n.split(`
1880
1910
  `).filter(Boolean).length}catch{}try{let n=na("git log -10 --pretty=format:%H|%s|%an|%aI",{cwd:e,stdio:"pipe"}).toString();t.recentCommits=n.split(`
1881
1911
  `).filter(Boolean).map(r=>{let[s,i,o,a]=r.split("|");return{sha:s.slice(0,12),message:i,author:o,date:a}})}catch{}try{t.remoteUrl=na("git config --get remote.origin.url",{cwd:e,stdio:"pipe"}).toString().trim()}catch{}try{let n=na("git rev-list --left-right --count HEAD...@{u}",{cwd:e,stdio:"pipe"}).toString().trim(),[r,s]=n.split(" ").map(i=>parseInt(i,10));t.ahead=isFinite(r)?r:0,t.behind=isFinite(s)?s:0}catch{}return t}function rke(e){let t={},n=Zn(e,"package.json");if(Tr(n))try{let o=JSON.parse(si(n,"utf-8"));t.packageJson={version:o.version||"",dependencies:o.dependencies||{},devDependencies:o.devDependencies||{},scripts:o.scripts||{}}}catch{}for(let o of["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb"]){let a=Zn(e,o);if(Tr(a))try{let c=si(a);t.lockfileHash=Sg("md5").update(c).digest("hex").slice(0,16);break}catch{}}let r=Zn(e,"requirements.txt");if(Tr(r))try{let o=si(r,"utf-8").split(`
1882
1912
  `),a={};for(let c of o){let l=c.match(/^([\w_-]+)([=<>!]+.+)?/);l&&(a[l[1]]=l[2]||"*")}t.pythonRequirements=a}catch{}let s=Zn(e,"go.mod");if(Tr(s))try{let o=si(s,"utf-8"),a=o.match(/^module\s+(\S+)/m),c={},l=o.match(/require\s*\(([\s\S]*?)\)/)?.[1]||"";for(let u of l.split(`
1883
1913
  `)){let d=u.trim().match(/^(\S+)\s+(\S+)/);d&&(c[d[1]]=d[2])}t.goMod={module:a?.[1]||"",deps:c}}catch{}let i=Zn(e,"Cargo.toml");if(Tr(i))try{let o=si(i,"utf-8"),a=o.match(/^\s*name\s*=\s*"([^"]+)"/m),c=o.match(/^\s*version\s*=\s*"([^"]+)"/m),l={},u=o.match(/\[dependencies\]([\s\S]*?)(?=\n\[|$)/)?.[1]||"";for(let d of u.split(`
1884
- `)){let f=d.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'\n]+)/);f&&(l[f[1]]=f[2].trim())}t.cargoToml={name:a?.[1]||"",version:c?.[1]||"",deps:l}}catch{}return t}function ske(e){let t={configFiles:{},envFiles:[]},n=[".aiaca.json","tsconfig.json",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".prettierrc",".prettierrc.json",".prettierrc.js","jest.config.js","vitest.config.ts","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","rollup.config.js","docker-compose.yml","docker-compose.yaml","pyproject.toml","setup.py","setup.cfg","go.work"];for(let r of n){let s=Zn(e,r);if(Tr(s))try{let i=si(s);if(t.configFiles[r]=Sg("md5").update(i).digest("hex").slice(0,12),r===".aiaca.json")try{t.aiacaConfig=JSON.parse(i.toString("utf-8"))}catch{}}catch{}}for(let r of[".env",".env.local",".env.development",".env.production"]){let s=Zn(e,r);Tr(s)&&t.envFiles.push(r)}return t}function ike(e){let t=["NODE_ENV","PYTHON_VERSION","GO_VERSION","RUST_VERSION","CI","PATH"],n={};for(let r of t)process.env[r]&&(n[r]=r==="PATH"?process.env[r].split(/[;:]/).slice(0,5).join(";")+"...":process.env[r]);return{cwd:e,hostname:process.env.COMPUTERNAME||process.env.HOSTNAME,user:process.env.USER||process.env.USERNAME,shell:process.env.SHELL||process.env.ComSpec,relevantEnv:n}}async function dq(e,t,n=""){lq(e);let r=Date.now(),s=Ud(e),[i,o,a,c]=await Promise.all([tke(s),Promise.resolve(nke(s)),Promise.resolve(rke(s)),Promise.resolve(ske(s))]),l=ike(s),u={id:Sg("sha256").update(`${t}:${Date.now()}:${Math.random()}`).digest("hex").slice(0,16),projectPath:s,sessionId:t,capturedAt:Date.now(),capturedAtISO:new Date().toISOString(),summary:n,files:i,git:o,dependencies:a,config:c,environment:l,stats:{filesScanned:i.totalCount,filesHashed:Object.keys(i.trackedFiles).length,scanDurationMs:Date.now()-r,totalSizeKB:i.totalSizeKB},metadata:{nodeVersion:process.version,platform:process.platform}};cq(R1(s,u.id),JSON.stringify(u),"utf-8");let d=I1(s);if(d.snapshots.push({id:u.id,sessionId:t,capturedAt:u.capturedAt,summary:n}),d.snapshots.length>_1){let f=d.snapshots.slice(0,d.snapshots.length-_1);for(let p of f)try{P1(R1(s,p.id))}catch{}d.snapshots=d.snapshots.slice(-_1)}return oke(s,d),u}function I1(e){let t=uq(e);if(!Tr(t))return{snapshots:[]};try{return JSON.parse(si(t,"utf-8"))}catch{return{snapshots:[]}}}function oke(e,t){lq(e),cq(uq(e),JSON.stringify(t,null,2),"utf-8")}function fq(e){let t=I1(Ud(e));if(t.snapshots.length===0)return null;let n=t.snapshots[t.snapshots.length-1];return pq(e,n.id)}function pq(e,t){let n=R1(Ud(e),t);if(!Tr(n))return null;try{return JSON.parse(si(n,"utf-8"))}catch{return null}}function ake(e){return I1(Ud(e)).snapshots}function mq(e,t){let n=new Set(Object.keys(e.files.trackedFiles)),r=new Set(Object.keys(t.files.trackedFiles)),s=[...r].filter(T=>!n.has(T)),i=[...n].filter(T=>!r.has(T)),o=[];for(let T of r)n.has(T)&&e.files.trackedFiles[T].hash!==t.files.trackedFiles[T].hash&&o.push(T);let a=[],c=new Map(i.map(T=>[e.files.trackedFiles[T].hash,T])),l=[];for(let T of s){let ce=c.get(t.files.trackedFiles[T].hash);if(ce){a.push({from:ce,to:T});let se=i.indexOf(ce);se>=0&&i.splice(se,1)}else l.push(T)}let u=e.git.branch!==t.git.branch&&e.git.branch&&t.git.branch?{from:e.git.branch,to:t.git.branch}:void 0,d=new Set(e.git.recentCommits.map(T=>T.sha)),f=t.git.recentCommits.filter(T=>!d.has(T.sha)),p=new Set(e.git.modifiedFiles),m=new Set(t.git.modifiedFiles),g=[...m].filter(T=>!p.has(T)),h=[...p].filter(T=>!m.has(T)),v={},y=[],b=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T={...e.dependencies.packageJson.dependencies,...e.dependencies.packageJson.devDependencies},ce={...t.dependencies.packageJson.dependencies,...t.dependencies.packageJson.devDependencies};for(let[se,C]of Object.entries(ce))se in T?T[se]!==C&&b.push({name:se,from:T[se],to:C}):v[se]=C;for(let se of Object.keys(T))se in ce||y.push(se)}let k=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T=e.dependencies.packageJson.scripts||{},ce=t.dependencies.packageJson.scripts||{},se=new Set([...Object.keys(T),...Object.keys(ce)]);for(let C of se)T[C]!==ce[C]&&k.push({name:C,from:T[C],to:ce[C]})}let S=new Set(Object.keys(e.config.configFiles)),x=new Set(Object.keys(t.config.configFiles)),A=[...x].filter(T=>!S.has(T)),j=[...S].filter(T=>!x.has(T)),I=[];for(let T of x)S.has(T)&&e.config.configFiles[T]!==t.config.configFiles[T]&&I.push(T);let ye;if(e.config.aiacaConfig&&t.config.aiacaConfig){ye={};let T=new Set([...Object.keys(e.config.aiacaConfig),...Object.keys(t.config.aiacaConfig)]);for(let ce of T){let se=e.config.aiacaConfig[ce],C=t.config.aiacaConfig[ce];JSON.stringify(se)!==JSON.stringify(C)&&(ye[ce]={from:se,to:C})}Object.keys(ye).length===0&&(ye=void 0)}let Ne={};for(let T of new Set([...Object.keys(e.environment.relevantEnv),...Object.keys(t.environment.relevantEnv)]))e.environment.relevantEnv[T]!==t.environment.relevantEnv[T]&&(Ne[T]={from:e.environment.relevantEnv[T]||"",to:t.environment.relevantEnv[T]||""});let mn=l.length+i.length+o.length+a.length,nn="none";mn+f.length+Object.keys(v).length+y.length+b.length>0&&(mn>50||f.length>5||u?nn="major":mn>10||b.length>0?nn="moderate":nn="minor");let De=t.capturedAt-e.capturedAt,Et=uke(De),gn={fromSnapshotId:e.id,toSnapshotId:t.id,fromTimestamp:e.capturedAt,toTimestamp:t.capturedAt,durationMs:De,durationFormatted:Et,filesAdded:l,filesRemoved:i,filesModified:o,filesRenamed:a,totalFileChanges:mn,branchChanged:u,commitsAdded:f,dirtyChanged:{wasDirty:e.git.isDirty,isDirty:t.git.isDirty},modifiedFilesChanged:{added:g,removed:h},dependenciesAdded:v,dependenciesRemoved:y,dependenciesUpdated:b,scriptsChanged:k,lockfileChanged:e.dependencies.lockfileHash!==t.dependencies.lockfileHash,configFilesChanged:I,configFilesAdded:A,configFilesRemoved:j,aiacaConfigChanges:ye,envChanges:Ne,significance:nn,briefing:""};return gn.briefing=M1(gn,{format:"markdown",detail:"detailed"}),gn}function M1(e,t={}){let n=t.format||"markdown",r=t.detail||"detailed",s=t.maxFileChanges||20,i=t.maxCommits||10,o=t.maxDeps||15;if(n==="xml")return cke(e,t);if(n==="plain")return lke(e,t);let a=[];if(a.push(`# Session Diff \u2014 ${e.durationFormatted} since last session`),a.push(""),a.push(`**Significance:** ${e.significance}`),e.totalFileChanges===0&&e.commitsAdded.length===0&&Object.keys(e.dependenciesAdded).length===0&&e.dependenciesUpdated.length===0)return a.push(""),a.push("No significant changes since last session."),a.join(`
1914
+ `)){let f=d.match(/^\s*([\w_-]+)\s*=\s*["']?([^"'\n]+)/);f&&(l[f[1]]=f[2].trim())}t.cargoToml={name:a?.[1]||"",version:c?.[1]||"",deps:l}}catch{}return t}function ske(e){let t={configFiles:{},envFiles:[]},n=[".aiaca.json","tsconfig.json",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".prettierrc",".prettierrc.json",".prettierrc.js","jest.config.js","vitest.config.ts","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","rollup.config.js","docker-compose.yml","docker-compose.yaml","pyproject.toml","setup.py","setup.cfg","go.work"];for(let r of n){let s=Zn(e,r);if(Tr(s))try{let i=si(s);if(t.configFiles[r]=Sg("md5").update(i).digest("hex").slice(0,12),r===".aiaca.json")try{t.aiacaConfig=JSON.parse(i.toString("utf-8"))}catch{}}catch{}}for(let r of[".env",".env.local",".env.development",".env.production"]){let s=Zn(e,r);Tr(s)&&t.envFiles.push(r)}return t}function ike(e){let t=["NODE_ENV","PYTHON_VERSION","GO_VERSION","RUST_VERSION","CI","PATH"],n={};for(let r of t)process.env[r]&&(n[r]=r==="PATH"?process.env[r].split(/[;:]/).slice(0,5).join(";")+"...":process.env[r]);return{cwd:e,hostname:process.env.COMPUTERNAME||process.env.HOSTNAME,user:process.env.USER||process.env.USERNAME,shell:process.env.SHELL||process.env.ComSpec,relevantEnv:n}}async function d5(e,t,n=""){l5(e);let r=Date.now(),s=Ud(e),[i,o,a,c]=await Promise.all([tke(s),Promise.resolve(nke(s)),Promise.resolve(rke(s)),Promise.resolve(ske(s))]),l=ike(s),u={id:Sg("sha256").update(`${t}:${Date.now()}:${Math.random()}`).digest("hex").slice(0,16),projectPath:s,sessionId:t,capturedAt:Date.now(),capturedAtISO:new Date().toISOString(),summary:n,files:i,git:o,dependencies:a,config:c,environment:l,stats:{filesScanned:i.totalCount,filesHashed:Object.keys(i.trackedFiles).length,scanDurationMs:Date.now()-r,totalSizeKB:i.totalSizeKB},metadata:{nodeVersion:process.version,platform:process.platform}};c5(R1(s,u.id),JSON.stringify(u),"utf-8");let d=I1(s);if(d.snapshots.push({id:u.id,sessionId:t,capturedAt:u.capturedAt,summary:n}),d.snapshots.length>_1){let f=d.snapshots.slice(0,d.snapshots.length-_1);for(let p of f)try{P1(R1(s,p.id))}catch{}d.snapshots=d.snapshots.slice(-_1)}return oke(s,d),u}function I1(e){let t=u5(e);if(!Tr(t))return{snapshots:[]};try{return JSON.parse(si(t,"utf-8"))}catch{return{snapshots:[]}}}function oke(e,t){l5(e),c5(u5(e),JSON.stringify(t,null,2),"utf-8")}function f5(e){let t=I1(Ud(e));if(t.snapshots.length===0)return null;let n=t.snapshots[t.snapshots.length-1];return p5(e,n.id)}function p5(e,t){let n=R1(Ud(e),t);if(!Tr(n))return null;try{return JSON.parse(si(n,"utf-8"))}catch{return null}}function ake(e){return I1(Ud(e)).snapshots}function m5(e,t){let n=new Set(Object.keys(e.files.trackedFiles)),r=new Set(Object.keys(t.files.trackedFiles)),s=[...r].filter(T=>!n.has(T)),i=[...n].filter(T=>!r.has(T)),o=[];for(let T of r)n.has(T)&&e.files.trackedFiles[T].hash!==t.files.trackedFiles[T].hash&&o.push(T);let a=[],c=new Map(i.map(T=>[e.files.trackedFiles[T].hash,T])),l=[];for(let T of s){let ce=c.get(t.files.trackedFiles[T].hash);if(ce){a.push({from:ce,to:T});let se=i.indexOf(ce);se>=0&&i.splice(se,1)}else l.push(T)}let u=e.git.branch!==t.git.branch&&e.git.branch&&t.git.branch?{from:e.git.branch,to:t.git.branch}:void 0,d=new Set(e.git.recentCommits.map(T=>T.sha)),f=t.git.recentCommits.filter(T=>!d.has(T.sha)),p=new Set(e.git.modifiedFiles),m=new Set(t.git.modifiedFiles),g=[...m].filter(T=>!p.has(T)),h=[...p].filter(T=>!m.has(T)),v={},y=[],b=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T={...e.dependencies.packageJson.dependencies,...e.dependencies.packageJson.devDependencies},ce={...t.dependencies.packageJson.dependencies,...t.dependencies.packageJson.devDependencies};for(let[se,C]of Object.entries(ce))se in T?T[se]!==C&&b.push({name:se,from:T[se],to:C}):v[se]=C;for(let se of Object.keys(T))se in ce||y.push(se)}let k=[];if(e.dependencies.packageJson&&t.dependencies.packageJson){let T=e.dependencies.packageJson.scripts||{},ce=t.dependencies.packageJson.scripts||{},se=new Set([...Object.keys(T),...Object.keys(ce)]);for(let C of se)T[C]!==ce[C]&&k.push({name:C,from:T[C],to:ce[C]})}let S=new Set(Object.keys(e.config.configFiles)),x=new Set(Object.keys(t.config.configFiles)),A=[...x].filter(T=>!S.has(T)),j=[...S].filter(T=>!x.has(T)),I=[];for(let T of x)S.has(T)&&e.config.configFiles[T]!==t.config.configFiles[T]&&I.push(T);let ye;if(e.config.aiacaConfig&&t.config.aiacaConfig){ye={};let T=new Set([...Object.keys(e.config.aiacaConfig),...Object.keys(t.config.aiacaConfig)]);for(let ce of T){let se=e.config.aiacaConfig[ce],C=t.config.aiacaConfig[ce];JSON.stringify(se)!==JSON.stringify(C)&&(ye[ce]={from:se,to:C})}Object.keys(ye).length===0&&(ye=void 0)}let Ne={};for(let T of new Set([...Object.keys(e.environment.relevantEnv),...Object.keys(t.environment.relevantEnv)]))e.environment.relevantEnv[T]!==t.environment.relevantEnv[T]&&(Ne[T]={from:e.environment.relevantEnv[T]||"",to:t.environment.relevantEnv[T]||""});let mn=l.length+i.length+o.length+a.length,nn="none";mn+f.length+Object.keys(v).length+y.length+b.length>0&&(mn>50||f.length>5||u?nn="major":mn>10||b.length>0?nn="moderate":nn="minor");let De=t.capturedAt-e.capturedAt,Et=uke(De),gn={fromSnapshotId:e.id,toSnapshotId:t.id,fromTimestamp:e.capturedAt,toTimestamp:t.capturedAt,durationMs:De,durationFormatted:Et,filesAdded:l,filesRemoved:i,filesModified:o,filesRenamed:a,totalFileChanges:mn,branchChanged:u,commitsAdded:f,dirtyChanged:{wasDirty:e.git.isDirty,isDirty:t.git.isDirty},modifiedFilesChanged:{added:g,removed:h},dependenciesAdded:v,dependenciesRemoved:y,dependenciesUpdated:b,scriptsChanged:k,lockfileChanged:e.dependencies.lockfileHash!==t.dependencies.lockfileHash,configFilesChanged:I,configFilesAdded:A,configFilesRemoved:j,aiacaConfigChanges:ye,envChanges:Ne,significance:nn,briefing:""};return gn.briefing=M1(gn,{format:"markdown",detail:"detailed"}),gn}function M1(e,t={}){let n=t.format||"markdown",r=t.detail||"detailed",s=t.maxFileChanges||20,i=t.maxCommits||10,o=t.maxDeps||15;if(n==="xml")return cke(e,t);if(n==="plain")return lke(e,t);let a=[];if(a.push(`# Session Diff \u2014 ${e.durationFormatted} since last session`),a.push(""),a.push(`**Significance:** ${e.significance}`),e.totalFileChanges===0&&e.commitsAdded.length===0&&Object.keys(e.dependenciesAdded).length===0&&e.dependenciesUpdated.length===0)return a.push(""),a.push("No significant changes since last session."),a.join(`
1885
1915
  `);if(e.totalFileChanges>0){if(a.push(""),a.push(`## File Changes (${e.totalFileChanges})`),e.filesAdded.length>0){a.push(""),a.push(`### Added (${e.filesAdded.length})`);for(let l of e.filesAdded.slice(0,s))a.push(`- ${l}`);e.filesAdded.length>s&&a.push(`- \u2026 +${e.filesAdded.length-s} more`)}if(e.filesModified.length>0){a.push(""),a.push(`### Modified (${e.filesModified.length})`);for(let l of e.filesModified.slice(0,s))a.push(`- ${l}`);e.filesModified.length>s&&a.push(`- \u2026 +${e.filesModified.length-s} more`)}if(e.filesRemoved.length>0){a.push(""),a.push(`### Removed (${e.filesRemoved.length})`);for(let l of e.filesRemoved.slice(0,s))a.push(`- ${l}`)}if(e.filesRenamed.length>0){a.push(""),a.push(`### Renamed (${e.filesRenamed.length})`);for(let l of e.filesRenamed.slice(0,s))a.push(`- ${l.from} \u2192 ${l.to}`)}}if(e.branchChanged||e.commitsAdded.length>0||e.dirtyChanged.wasDirty!==e.dirtyChanged.isDirty){if(a.push(""),a.push("## Git"),e.branchChanged&&a.push(`- Branch: ${e.branchChanged.from} \u2192 ${e.branchChanged.to}`),e.commitsAdded.length>0){a.push(`- New commits (${e.commitsAdded.length}):`);for(let l of e.commitsAdded.slice(0,i))a.push(` - ${l.sha} ${l.message} (${l.author})`)}e.dirtyChanged.wasDirty&&!e.dirtyChanged.isDirty&&a.push("- Working tree was cleaned"),!e.dirtyChanged.wasDirty&&e.dirtyChanged.isDirty&&a.push("- Working tree is now dirty")}if(Object.keys(e.dependenciesAdded).length>0||e.dependenciesRemoved.length>0||e.dependenciesUpdated.length>0){if(a.push(""),a.push("## Dependencies"),Object.keys(e.dependenciesAdded).length>0){a.push(""),a.push("### Added");for(let[l,u]of Object.entries(e.dependenciesAdded).slice(0,o))a.push(`- ${l}@${u}`)}if(e.dependenciesUpdated.length>0){a.push(""),a.push("### Updated");for(let l of e.dependenciesUpdated.slice(0,o))a.push(`- ${l.name}: ${l.from} \u2192 ${l.to}`)}if(e.dependenciesRemoved.length>0){a.push(""),a.push("### Removed");for(let l of e.dependenciesRemoved.slice(0,o))a.push(`- ${l}`)}e.lockfileChanged&&a.push("- Lockfile changed")}if(e.scriptsChanged.length>0){a.push(""),a.push("## Scripts Changed");for(let l of e.scriptsChanged.slice(0,10))l.from?l.to?a.push(`- ${l.name}: ${l.from} \u2192 ${l.to}`):a.push(`- - ${l.name}: ${l.from}`):a.push(`- + ${l.name}: ${l.to}`)}if((e.configFilesChanged.length>0||e.configFilesAdded.length>0||e.configFilesRemoved.length>0||e.aiacaConfigChanges)&&(a.push(""),a.push("## Config"),e.configFilesAdded.length>0&&a.push(`- Added: ${e.configFilesAdded.join(", ")}`),e.configFilesChanged.length>0&&a.push(`- Changed: ${e.configFilesChanged.join(", ")}`),e.configFilesRemoved.length>0&&a.push(`- Removed: ${e.configFilesRemoved.join(", ")}`),e.aiacaConfigChanges)){a.push("- AIACA config changes:");for(let[l,u]of Object.entries(e.aiacaConfigChanges))a.push(` - ${l}: ${JSON.stringify(u.from)} \u2192 ${JSON.stringify(u.to)}`)}if(t.includeEnv&&Object.keys(e.envChanges).length>0){a.push(""),a.push("## Environment");for(let[l,u]of Object.entries(e.envChanges))a.push(`- ${l}: ${u.from||"(unset)"} \u2192 ${u.to||"(unset)"}`)}return a.join(`
1886
1916
  `)}function cke(e,t){let n=[];if(n.push(`<session_diff duration="${e.durationFormatted}" significance="${e.significance}">`),e.totalFileChanges>0){n.push(` <files added="${e.filesAdded.length}" modified="${e.filesModified.length}" removed="${e.filesRemoved.length}" renamed="${e.filesRenamed.length}">`);for(let r of e.filesModified.slice(0,30))n.push(` <modified>${r}</modified>`);for(let r of e.filesAdded.slice(0,30))n.push(` <added>${r}</added>`);for(let r of e.filesRemoved.slice(0,30))n.push(` <removed>${r}</removed>`);n.push(" </files>")}if(e.commitsAdded.length>0){n.push(` <new_commits count="${e.commitsAdded.length}">`);for(let r of e.commitsAdded.slice(0,10))n.push(` <commit sha="${r.sha}" author="${r.author}">${r.message}</commit>`);n.push(" </new_commits>")}if(e.branchChanged&&n.push(` <branch_change from="${e.branchChanged.from}" to="${e.branchChanged.to}"/>`),e.dependenciesUpdated.length>0){n.push(" <dependency_updates>");for(let r of e.dependenciesUpdated.slice(0,15))n.push(` <update name="${r.name}" from="${r.from}" to="${r.to}"/>`);n.push(" </dependency_updates>")}return n.push("</session_diff>"),n.join(`
1887
- `)}function lke(e,t){if(e.totalFileChanges===0&&e.commitsAdded.length===0)return`No significant changes since last session (${e.durationFormatted} ago).`;let n=[];return n.push(`Since last session (${e.durationFormatted} ago):`),e.totalFileChanges>0&&n.push(`${e.totalFileChanges} files changed`),e.commitsAdded.length>0&&n.push(`${e.commitsAdded.length} new commits`),e.branchChanged&&n.push(`branch ${e.branchChanged.from}\u2192${e.branchChanged.to}`),e.dependenciesUpdated.length>0&&n.push(`${e.dependenciesUpdated.length} deps updated`),Object.keys(e.dependenciesAdded).length>0&&n.push(`${Object.keys(e.dependenciesAdded).length} deps added`),n.join(", ")+"."}function uke(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60),s=Math.floor(r/24);return s>0?`${s}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}async function dke(e,t,n={}){let r=fq(e),s=await dq(e,t,"");if(!r)return{briefing:"First session for this project \u2014 no previous state to diff against.",diff:null,snapshot:s};let i=mq(r,s);return{briefing:M1(i,n),diff:i,snapshot:s}}function fke(){if(!Tr(tl))return{totalSnapshots:0,totalDiffs:0,totalProjects:0,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:0,newestSnapshotAt:0,perProjectSnapshots:{}};let e=0,t=0,n=Date.now(),r=0,s={};try{let i=k0(tl);for(let o of i){let a=Zn(tl,o,"index.json");if(Tr(a))try{let c=JSON.parse(si(a,"utf-8"));e+=c.snapshots.length,t++,s[o]=c.snapshots.length;for(let l of c.snapshots)l.capturedAt<n&&(n=l.capturedAt),l.capturedAt>r&&(r=l.capturedAt)}catch{}}}catch{}return{totalSnapshots:e,totalDiffs:Math.max(0,e-t),totalProjects:t,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:n,newestSnapshotAt:r,perProjectSnapshots:s}}function pke(e){let t=x0(Ud(e));if(!Tr(t))return!1;try{for(let n of k0(t))try{P1(Zn(t,n))}catch{}return!0}catch{return!1}}function mke(){if(!Tr(tl))return!0;try{for(let e of k0(tl)){let t=Zn(tl,e);try{for(let n of k0(t))P1(Zn(t,n))}catch{}}return!0}catch{return!1}}var tl,_1,Qwe,Zwe,Xwe,eke,C0=w(()=>{"use strict";tl=Zn(Wwe(),".aiaca","session-diff"),_1=30;Qwe=["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,java,go,rs,c,cpp,h,hpp}","**/*.{json,yaml,yml,toml,xml}","**/*.{md,txt,rst}","**/*.{html,css,scss,sass}","**/*.{sh,ps1,bat,cmd}","**/*.sql","**/Makefile","**/Dockerfile*"],Zwe=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.cache/**","**/coverage/**","**/target/**","**/.next/**","**/.nuxt/**","**/__pycache__/**","**/.venv/**","**/venv/**","**/vendor/**","**/*.min.js","**/*.lock"],Xwe=2e3,eke=1024*1024});var bq={};$(bq,{addCustomTip:()=>Rke,buildContext:()=>Fke,checkContextualTriggers:()=>$ke,dismissTip:()=>Ake,formatTip:()=>Lke,getAllTipsForBrowsing:()=>Oke,getPreferences:()=>Mke,getTipForTrigger:()=>bs,getTipsStats:()=>Dke,rateTip:()=>Tke,recordQuery:()=>_ke,recordTipShown:()=>Cke,removeCustomTip:()=>Pke,resetTips:()=>Eke,setPreferences:()=>Ike});import{existsSync as gke,readFileSync as hke,writeFileSync as yke,mkdirSync as bke}from"fs";import{join as gq}from"path";import{homedir as vke}from"os";function yq(){bke(hq,{recursive:!0})}function wke(){if(yq(),!gke(E1)){Ki();return}try{V={...V,...JSON.parse(hke(E1,"utf-8"))}}catch{}}function Ki(){yq(),yke(E1,JSON.stringify(V,null,2),"utf-8")}function D1(){return[...Ske,...V.customTips]}function kke(e,t){if(V.dismissed.includes(e.id)||!V.preferences.enabled||V.preferences.showFrequency==="off"||V.preferences.categories.length>0&&!V.preferences.categories.includes(e.category)||V.preferences.tags.length>0&&!e.tags.some(i=>V.preferences.tags.includes(i)))return!1;let n={beginner:0,intermediate:1,advanced:2};if(n[e.difficulty]<n[V.preferences.minDifficulty])return!1;let r=V.shown[e.id]||[];if(e.showOnce&&r.length>0)return!1;let s=r.filter(i=>Date.now()-new Date(i.shownAt).getTime()<t.sessionAge);if(e.maxShowsPerSession&&s.length>=e.maxShowsPerSession)return!1;if(e.cooldownMs&&r.length>0){let i=r[r.length-1];if(Date.now()-new Date(i.shownAt).getTime()<e.cooldownMs)return!1}return!(e.triggerCondition&&!e.triggerCondition(t))}function xke(e,t){return D1().filter(n=>n.trigger===e).filter(n=>kke(n,t)).sort((n,r)=>r.priority-n.priority)}function bs(e,t){let n=xke(e,t);if(n.length===0)return null;let r=V.preferences.showFrequency;if(r==="rare"&&Math.random()>.3||r==="normal"&&Math.random()>.6)return null;let s=n.slice(0,3);return s[Math.floor(Math.random()*s.length)]}function $ke(e){if(e.isFirstRun){let n=bs("first_run",e);if(n)return n}if(e.errorCount>=3){let n=bs("multiple_failures",e);if(n)return n}else if(e.errorCount>0){let n=bs("after_error",e);if(n)return n}if(e.sessionAge>1800*1e3){let n=bs("long_session",e);if(n)return n}if(e.contextTokens>5e4){let n=bs("large_context",e);if(n)return n}if(e.totalCost>1){let n=bs("high_cost",e);if(n)return n}if([10,50,100,500,1e3,5e3].includes(e.totalQueriesEver)){let n=bs("milestone",e);if(n)return n}if(e.filesModified.length>0){let n=bs("file_modified",e);if(n)return n}if(e.toolUseCount===1){let n=bs("first_tool_use",e);if(n)return n}if(e.idleTimeMs>600*1e3){let n=bs("idle",e);if(n)return n}return null}function Cke(e,t){V.shown[e]||(V.shown[e]=[]),V.shown[e].push({tipId:e,trigger:t,shownAt:new Date().toISOString(),dismissed:!1}),Ki()}function Ake(e){V.dismissed.includes(e)||V.dismissed.push(e),Ki()}function Tke(e,t){let n=V.shown[e];n&&n.length>0&&(n[n.length-1].rated=t,Ki())}function _ke(){V.totalQueriesEver++,Ki()}function Rke(e){V.customTips.push(e),Ki()}function Pke(e){let t=V.customTips.length;return V.customTips=V.customTips.filter(n=>n.id!==e),Ki(),V.customTips.length<t}function Ike(e){V.preferences={...V.preferences,...e},Ki()}function Mke(){return{...V.preferences}}function Eke(){V.shown={},V.dismissed=[],Ki()}function Dke(){let e=new Map(D1().map(i=>[i.id,i])),t=0,n=0,r=0,s=[];for(let[i,o]of Object.entries(V.shown))t+=o.length,n+=o.filter(a=>a.rated==="helpful").length,r+=o.filter(a=>a.rated==="not_helpful").length,s.push({id:i,shows:o.length});return s.sort((i,o)=>o.shows-i.shows),{totalShows:t,uniqueTipsShown:Object.keys(V.shown).length,dismissedCount:V.dismissed.length,helpfulCount:n,notHelpfulCount:r,customTipsCount:V.customTips.length,totalQueries:V.totalQueriesEver,topShownTips:s.slice(0,10).map(i=>({id:i.id,message:e.get(i.id)?.message||"?",shows:i.shows}))}}function Fke(e,t){let n=Date.now(),r=t.sessionStartTime?n-t.sessionStartTime:0,s=0,i=0,o=[],a=[],c=[];for(let l of e){if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)s++,c.push(u.name),(u.name==="file_write"||u.name==="file_edit")&&a.push(String(u.input?.path));if(l.role==="user"&&/<tool_result.*error="true"|Error:|Exit code:/.test(l.content)){i++;let u=l.content.match(/Error: ([^\n]+)/);u&&o.push(u[1])}}return{sessionAge:r,messageCount:e.length,toolUseCount:s,errorCount:i,recentErrors:o.slice(-5),filesModified:[...new Set(a)],totalCost:t.totalCost||0,contextTokens:t.contextTokens||0,isFirstRun:V.totalQueriesEver===0,totalQueriesEver:V.totalQueriesEver,lastUsedTools:c.slice(-10),idleTimeMs:t.idleTimeMs||0}}function Lke(e){return`${e.difficulty==="beginner"?"\u{1F4A1}":e.difficulty==="intermediate"?"\u2728":"\u{1F393}"} Tip: ${e.message}`}function Oke(e){let t=D1();return e?.category&&(t=t.filter(n=>n.category===e.category)),e?.difficulty&&(t=t.filter(n=>n.difficulty===e.difficulty)),t.sort((n,r)=>r.priority-n.priority)}var Ske,hq,E1,V,vq=w(()=>{"use strict";Ske=[{id:"gs_help",message:"Type /help to see all available commands",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:9,tags:["basics"]},{id:"gs_init",message:"Create AIACA.md in your project root with /init to give persistent project context",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:8,tags:["memory"]},{id:"gs_model",message:"Use /model to switch between Claude and Gemini models for different tasks",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:7,tags:["models"]},{id:"gs_first_run",message:'Welcome to AIACA! Try asking it to "explain this codebase" to get started',category:"getting_started",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:10,tags:["welcome"]},{id:"prod_compact",message:"Use /compact to summarize long conversations and free up context window",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:9,cooldownMs:1800*1e3,tags:["context"]},{id:"prod_collapse",message:"Use /collapse for lossless context compression \u2014 preserves all info while shrinking tool results",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:8,tags:["context","efficiency"]},{id:"prod_recall",message:"Use /recall extract to save important facts from this session for future use",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["memory"]},{id:"prod_skill",message:"Browse pre-built skills with /skill list \u2014 they save typing for common tasks",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:6,tags:["skills"]},{id:"cmd_resume",message:"Continue past sessions with /resume \u2014 your conversation history persists",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["session"]},{id:"cmd_export",message:"Save conversations as markdown with /export",category:"commands",difficulty:"beginner",trigger:"long_session",showOnce:!0,priority:5,tags:["export"]},{id:"cmd_diff",message:"Use /diff to see git changes inline",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:4,tags:["git"]},{id:"cmd_search",message:"Search past conversations with /search <query>",category:"commands",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:5,tags:["search"]},{id:"tool_first_bash",message:'Tip: AIACA can run any shell command via the bash tool \u2014 say "run npm install"',category:"tools",difficulty:"beginner",trigger:"first_tool_use",showOnce:!0,priority:7,tags:["shell"]},{id:"tool_image",message:'Copy an image to clipboard then ask AIACA to "look at this" \u2014 it auto-detects',category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["vision"]},{id:"tool_doc",message:"Generate .docx, .pptx, .pdf files using natural language \u2014 AIACA handles formatting",category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["docs"]},{id:"tool_agent",message:"Spawn parallel sub-agents with the agent tool for independent subtasks",category:"tools",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["agents"]},{id:"eff_plan_mode",message:"Use /plan for read-only exploration \u2014 prevents accidental writes",category:"efficiency",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["safety"]},{id:"eff_perm_auto",message:'Set permission mode to "auto" with /permissions auto for fewer interruptions on safe ops',category:"efficiency",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["permissions"]},{id:"eff_cache",message:"Enable response caching with /cache on for faster repeated queries",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:5,tags:["cache"]},{id:"eff_vcr",message:"Record + replay API calls with /vcr \u2014 perfect for testing and debugging",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["testing"]},{id:"qual_review",message:"Run /review or use the code-review skill before committing changes",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:7,cooldownMs:3600*1e3,tags:["review"]},{id:"qual_test",message:"Use the test-writer skill to generate comprehensive tests automatically",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["testing"]},{id:"qual_security",message:"Run /skill security-audit periodically to catch vulnerabilities",category:"quality",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:6,tags:["security"]},{id:"qual_docs",message:"Generate documentation automatically with /docs readme --ai --write",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:5,tags:["docs"]},{id:"safe_perm",message:'Default permission mode "ask" prompts before destructive operations \u2014 safer for production',category:"safety",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["permissions"]},{id:"safe_undo",message:"File edits are auto-snapshotted \u2014 recovery available via fileHistory",category:"safety",difficulty:"intermediate",trigger:"file_modified",showOnce:!0,priority:7,tags:["safety"]},{id:"safe_worktree",message:"Use /worktree for isolated git operations without affecting main branch",category:"safety",difficulty:"advanced",trigger:"startup",showOnce:!0,priority:5,tags:["git"]},{id:"cost_haiku",message:"Use /model gemini-2.5-flash-lite for cheap/fast simple queries",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["cost"]},{id:"cost_compact",message:"Compact context regularly \u2014 saves tokens on long sessions",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["cost"]},{id:"cost_cache",message:"Enable /cache for repeated similar queries \u2014 cuts cost dramatically",category:"cost_savings",difficulty:"advanced",trigger:"high_cost",showOnce:!0,priority:8,tags:["cost","cache"]},{id:"collab_team",message:"Sync memories across machines with /team start \u2014 knowledge persists across devices",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["team"]},{id:"collab_mcp",message:"Connect external tools via Model Context Protocol \u2014 see /mcp",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["mcp"]},{id:"collab_share",message:"Share session transcripts via /share for collaboration",category:"collaboration",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:4,tags:["share"]},{id:"wf_init_first",message:"For new projects, run /init to scaffold an AIACA.md instructions file",category:"workflows",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:8,tags:["setup"]},{id:"wf_research",message:"For research tasks, web_search + web_fetch combination works great",category:"workflows",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["research"]},{id:"wf_refactor",message:"For refactoring: use the refactor skill with target file specified",category:"workflows",difficulty:"intermediate",trigger:"workflow_pattern",showOnce:!0,priority:6,tags:["refactor"]},{id:"wf_bug_hunt",message:"For bugs: describe the symptom, AIACA traces from observable to root cause",category:"workflows",difficulty:"intermediate",trigger:"after_failure",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["debug"]},{id:"adv_dream",message:"Run /dream periodically \u2014 consolidates memories like REM sleep, generates insights",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["memory"]},{id:"adv_diag",message:"Track performance with /diagnose metrics \u2014 identify bottlenecks",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:3,tags:["perf"]},{id:"adv_hooks",message:"Add custom hooks (/hooks) to run shell commands on tool events",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["hooks"]},{id:"ts_doctor",message:"Run /doctor to diagnose configuration issues",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!1,priority:8,cooldownMs:1800*1e3,tags:["debug"]},{id:"ts_retry",message:"AIACA auto-retries on rate limits with exponential backoff",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!0,priority:7,tags:["errors"]},{id:"ts_logs",message:"Inspect detailed logs with /diagnose logs",category:"troubleshooting",difficulty:"intermediate",trigger:"multiple_failures",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["debug"]},{id:"ts_clear",message:"If things get weird, /clear resets the conversation",category:"troubleshooting",difficulty:"beginner",trigger:"multiple_failures",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["reset"]},{id:"ms_10",message:"\u{1F389} You've made 10 queries! Try /skill list to discover pre-built workflows",category:"getting_started",difficulty:"beginner",trigger:"milestone",showOnce:!0,priority:6,triggerCondition:e=>e.totalQueriesEver===10,tags:["milestone"]},{id:"ms_100",message:"\u{1F680} 100 queries! You're a power user. Have you tried /dream for memory consolidation?",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:5,triggerCondition:e=>e.totalQueriesEver===100,tags:["milestone"]},{id:"ms_1000",message:"\u{1F3C6} 1000 queries! You're officially an AIACA expert. Consider sharing skills with the community via /skill registry",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:4,triggerCondition:e=>e.totalQueriesEver===1e3,tags:["milestone"]},{id:"nf_image",message:"NEW: AIACA now supports image inputs \u2014 paste from clipboard or reference file paths",category:"productivity",difficulty:"intermediate",trigger:"new_feature",showOnce:!0,priority:7,tags:["vision"]},{id:"nf_team",message:"NEW: Team memory sync lets multiple agents share knowledge \u2014 try /team start",category:"collaboration",difficulty:"advanced",trigger:"new_feature",showOnce:!0,priority:5,tags:["team"]},{id:"opp_no_tests",message:"I notice no test framework \u2014 consider adding one (jest, vitest, pytest)",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:6,tags:["testing"]},{id:"opp_no_readme",message:"No README found \u2014 generate one with /docs readme --ai --write",category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:7,tags:["docs"]},{id:"opp_no_git",message:'Not a git repo \u2014 initialize with "git init" to track changes',category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:6,tags:["git"]}],hq=gq(vke(),".aiaca","tips"),E1=gq(hq,"state.json"),V={installedAt:new Date().toISOString(),totalQueriesEver:0,shown:{},dismissed:[],preferences:{enabled:!0,showFrequency:"normal",minDifficulty:"beginner",categories:[],tags:[]},customTips:[]};wke()});var j1={};$(j1,{clearTeamMemory:()=>Zke,discoverAgents:()=>kq,getAgentPresence:()=>xq,getOrCreateIdentity:()=>ii,getTeamSyncStats:()=>Qke,loadTeamConfig:()=>Yke,manualSync:()=>exe,pruneOldData:()=>Xke,receiveMemories:()=>A0,registerPresence:()=>L1,saveTeamConfig:()=>Cq,shareMemories:()=>O1,startAutoSync:()=>Vke,startFileWatcher:()=>Wke,stopAutoSync:()=>Jke,stopFileWatcher:()=>Kke,updateIdentity:()=>$g});import{existsSync as Vr,readFileSync as sl,writeFileSync as ra,mkdirSync as Hd,readdirSync as il,statSync as jke,watch as Bke,unlinkSync as xg}from"fs";import{join as Mt}from"path";import{homedir as Nke,hostname as Sq}from"os";import{createHash as qke,randomUUID as Uke}from"crypto";function Jr(){Hd(ol,{recursive:!0}),Hd(Yi,{recursive:!0}),Hd(Gd,{recursive:!0}),Hd(Qi,{recursive:!0})}function ii(e){if(Jr(),_r)return _r;if(Vr(nl))try{return _r=JSON.parse(sl(nl,"utf-8")),_r.lastSeenAt=new Date().toISOString(),ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}catch{}return _r={id:`agent_${Uke()}`,name:e||`aiaca-${Sq()}-${Date.now().toString(36).slice(-6)}`,hostname:Sq(),startedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),capabilities:["memory_sync","conflict_resolution","crdt"],syncMode:"manual",factsShared:0,factsReceived:0},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function $g(e){return _r={...ii(),...e,lastSeenAt:new Date().toISOString()},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function L1(){Jr();let e=ii();e.lastSeenAt=new Date().toISOString(),ra(Mt(Yi,`${e.id}.json`),JSON.stringify(e,null,2),"utf-8")}function kq(){if(Jr(),!Vr(Yi))return[];let e=ii().id,t=Date.now()-1440*60*1e3,n=[];for(let r of il(Yi))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(Yi,r),"utf-8"));if(s.id===e)continue;if(new Date(s.lastSeenAt).getTime()<t){xg(Mt(Yi,r));continue}n.push(s)}catch{}return n}function xq(e){Jr();let t=Mt(Yi,`${e}.json`);if(!Vr(t))return"offline";try{let n=JSON.parse(sl(t,"utf-8")),r=Date.now()-new Date(n.lastSeenAt).getTime();return r<300*1e3?"online":r<3600*1e3?"recent":"offline"}catch{return"offline"}}function Hke(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=!1,s=!1;for(let i of n){let o=e[i]||0,a=t[i]||0;o>a&&(r=!0),a>o&&(s=!0)}return r&&s?"concurrent":r?"after":s?"before":"equal"}function zke(e,t){let n={...e};for(let[r,s]of Object.entries(t))n[r]=Math.max(n[r]||0,s);return n}function Gke(e,t="team"){let n=ii().id;return{...e,scope:t,ownerId:n,vectorClock:{[n]:1},signature:$q(e)}}function $q(e){return qke("sha256").update(`${e.id}:${e.content}:${e.category}`).digest("hex").slice(0,16)}function O1(e={}){Jr();let t=ii(),r=Jn().filter(o=>!(e.scope&&o.scope&&o.scope==="private"||e.categories&&!e.categories.includes(o.category)||e.minConfidence&&o.confidence<e.minConfidence||e.minImportance&&o.importance<e.minImportance));if(e.maxFacts&&(r=r.slice(0,e.maxFacts)),r.length===0)return{sharedCount:0,envelope:null};let s=r.map(o=>Gke(o,e.scope||"team")),i={fromAgent:t.id,toAgent:e.toAgentId,timestamp:new Date().toISOString(),facts:s,metadata:{syncRound:t.factsShared,totalFacts:s.length}};if(e.toAgentId){let o=Mt(Gd,e.toAgentId);Hd(o,{recursive:!0});let a=Mt(o,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(a,JSON.stringify(i,null,2),"utf-8")}else{let o=Mt(Qi,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(o,JSON.stringify(i,null,2),"utf-8")}return $g({factsShared:t.factsShared+s.length}),{sharedCount:s.length,envelope:i}}function A0(){Jr();let e=ii(),t=[],n=Mt(Gd,e.id);if(Vr(n)){for(let r of il(n))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(n,r),"utf-8")),i=wq(s);t.push(i),xg(Mt(n,r))}catch(s){t.push({added:0,updated:0,conflicts:0,rejected:0,totalReceived:0,errors:[s.message],durationMs:0})}}if(Vr(Qi))for(let r of il(Qi)){if(!r.endsWith(".json"))continue;let s=Mt(Qi,r);try{let i=JSON.parse(sl(s,"utf-8"));if(i.fromAgent===e.id)continue;let o=Mt(ol,`last_processed_${e.id}.json`),a={};if(Vr(o))try{a=JSON.parse(sl(o,"utf-8"))}catch{}if(a[i.fromAgent]&&a[i.fromAgent]>=i.timestamp)continue;let c=wq(i);t.push(c),a[i.fromAgent]=i.timestamp,ra(o,JSON.stringify(a,null,2),"utf-8")}catch{}}return t}function wq(e){let t=Date.now(),n=ii(),r=0,s=0,i=0,o=0,a=[],c=Jn(),l=new Map(c.map(u=>[u.id,u]));for(let u of e.facts)try{if(u.signature&&u.signature!==$q(u)){o++,a.push(`Bad signature on ${u.id}`);continue}let d=l.get(u.id);if(d){let f=Hke(d.vectorClock||{},u.vectorClock||{});f==="before"?(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent}}),s++):f==="concurrent"&&(i++,u.confidence>d.confidence&&(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent,mergedClock:zke(d.vectorClock||{},u.vectorClock||{})}}),s++))}else{let f=u.vectorClock||{[e.fromAgent]:1};us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,tags:[...u.tags||[],`from:${e.fromAgent.slice(-8)}`],metadata:{...u.metadata,syncedFrom:e.fromAgent,vectorClock:f,scope:u.scope}}),r++}}catch(d){a.push(`Error merging ${u.id}: ${d.message}`),o++}return $g({factsReceived:n.factsReceived+r+s}),{added:r,updated:s,conflicts:i,rejected:o,totalReceived:e.facts.length,errors:a,fromAgent:e.fromAgent,durationMs:Date.now()-t}}function Vke(e=300*1e3,t="auto"){rl&&clearInterval(rl),$g({syncMode:t}),rl=setInterval(()=>{try{L1(),A0(),(t==="realtime"||t==="auto")&&O1({minConfidence:.75,minImportance:.6,maxFacts:50})}catch{}},e),rl.unref()}function Jke(){rl&&(clearInterval(rl),rl=null),$g({syncMode:"manual"})}function Wke(){if(kg)return;Jr();let e=ii(),t=Mt(Gd,e.id);Hd(t,{recursive:!0});try{kg=Bke(t,n=>{n==="rename"&&setTimeout(()=>A0(),100)})}catch{}}function Kke(){kg&&(kg.close(),kg=null)}function Yke(){if(Jr(),!Vr(F1))return Cq(wg),wg;try{let e=JSON.parse(sl(F1,"utf-8"));return zd={...wg,...e},zd}catch{return wg}}function Cq(e){return Jr(),zd={...zd,...e},ra(F1,JSON.stringify(zd,null,2),"utf-8"),zd}function Qke(){Jr();let e=ii(),t=kq(),n=t.filter(o=>xq(o.id)==="online").length,r=Mt(Gd,e.id),s=0;Vr(r)&&(s=il(r).filter(o=>o.endsWith(".json")).length);let i=0;return Vr(Qi)&&(i=il(Qi).filter(o=>o.endsWith(".json")).length),{myAgent:e,knownAgents:t.length,onlineAgents:n,totalFactsShared:e.factsShared,totalFactsReceived:e.factsReceived,inboxPending:s,sharedQueueSize:i,syncMode:e.syncMode}}function Zke(){Jr();for(let e of[Yi,Gd,Qi])if(Vr(e))for(let t of il(e))try{xg(Mt(e,t))}catch{}if(Vr(nl))try{xg(nl)}catch{}_r=null}function Xke(){Jr();let e=Date.now()-10080*60*1e3;for(let t of[Qi,Yi])if(Vr(t))for(let n of il(t))try{let r=Mt(t,n);jke(r).mtimeMs<e&&xg(r)}catch{}}async function exe(){L1();let e=O1({minConfidence:.75,minImportance:.6}),t=A0(),n=t.reduce((r,s)=>r+s.added+s.updated,0);return{shared:e.sharedCount,received:n,results:t}}var ol,Yi,Gd,Qi,nl,F1,_r,rl,kg,wg,zd,B1=w(()=>{"use strict";xu();ol=Mt(Nke(),".aiaca","team-memory"),Yi=Mt(ol,"agents"),Gd=Mt(ol,"inbox"),Qi=Mt(ol,"shared"),nl=Mt(ol,"identity.json"),F1=Mt(ol,"config.json");_r=null;rl=null;kg=null;wg={enabled:!1,mode:"manual",intervalMs:300*1e3,shareScope:"team",minConfidence:.75,minImportance:.6,maxFactsPerSync:50,enableFileWatcher:!1},zd={...wg}});var Nq={};$(Nq,{analyzeProject:()=>U1,categorizeCommits:()=>Mq,extractSymbols:()=>H1,generateAPIDocs:()=>Dq,generateAllDocs:()=>bxe,generateArchitecture:()=>Lq,generateChangelog:()=>Fq,generateDoc:()=>Oq,generateReadme:()=>N1,getDocSuggestion:()=>vxe,getGitChangelog:()=>Iq,renderFileTree:()=>Vd});import{existsSync as qt,readFileSync as q1,writeFileSync as T0,readdirSync as txe,statSync as nxe}from"fs";import{join as pt,basename as _q,extname as rxe,relative as Cg,dirname as sxe}from"path";import{execSync as ixe}from"child_process";import{globSync as Rq}from"glob";function U1(e){let t=axe(e),n=cxe(e),r=lxe(e,t),s=Pq(e,e),i=uxe(e,t);return{name:t?.name||_q(e),description:t?.description,version:t?.version,language:n,framework:r,dependencies:t?.dependencies?Object.keys(t.dependencies):[],devDependencies:t?.devDependencies?Object.keys(t.devDependencies):[],scripts:t?.scripts||{},fileTree:s,entryPoint:t?.main||dxe(e,n),hasTests:!!i,testFramework:i}}function axe(e){let t=pt(e,"package.json");if(!qt(t))return null;try{return JSON.parse(q1(t,"utf-8"))}catch{return null}}function cxe(e){return qt(pt(e,"package.json"))?"JavaScript/TypeScript":qt(pt(e,"Cargo.toml"))?"Rust":qt(pt(e,"go.mod"))?"Go":qt(pt(e,"pyproject.toml"))||qt(pt(e,"requirements.txt"))?"Python":qt(pt(e,"pom.xml"))||qt(pt(e,"build.gradle"))?"Java":qt(pt(e,"Gemfile"))?"Ruby":qt(pt(e,"*.csproj"))?"C#":"Unknown"}function lxe(e,t){if(!t?.dependencies&&!t?.devDependencies)return;let n={...t.dependencies,...t.devDependencies};if(n.react)return"React";if(n.vue)return"Vue";if(n["@angular/core"])return"Angular";if(n.svelte)return"Svelte";if(n.next)return"Next.js";if(n.nuxt)return"Nuxt";if(n.express)return"Express";if(n.fastify)return"Fastify";if(n["@nestjs/core"])return"NestJS";if(n.ink)return"Ink (CLI)"}function uxe(e,t){if(!t)return;let n={...t.dependencies,...t.devDependencies};if(n.jest)return"Jest";if(n.vitest)return"Vitest";if(n.mocha)return"Mocha";if(n.cypress)return"Cypress";if(n.playwright)return"Playwright";if(qt(pt(e,"pytest.ini"))||qt(pt(e,"pyproject.toml")))return"pytest"}function dxe(e,t){let n=["src/index.ts","src/index.js","src/main.ts","index.ts","index.js","main.py","main.go","src/main.rs"];for(let r of n)if(qt(pt(e,r)))return r}function Pq(e,t,n=0,r=4){let s=_q(t)||t,i=nxe(t);if(!i.isDirectory())return{name:s,type:"file",path:Cg(e,t),size:i.size};let o={name:s,type:"dir",path:Cg(e,t),children:[]};if(n>=r)return o;try{let a=txe(t);for(let c of a){if(c.startsWith(".")&&!Aq.has(c)||oxe.has(c))continue;let l=pt(t,c);try{let u=Pq(e,l,n+1,r);Aq.has(c)&&(u.important=!0),o.children.push(u)}catch{}}}catch{}return o}function H1(e){if(!qt(e))return[];let t=rxe(e);if(![".ts",".tsx",".js",".jsx",".mjs"].includes(t))return[];let n=q1(e,"utf-8"),r=[];for(let[s,i]of Object.entries(fxe)){i.lastIndex=0;let o;for(;(o=i.exec(n))!==null;){let a=n.slice(0,o.index).split(`
1917
+ `)}function lke(e,t){if(e.totalFileChanges===0&&e.commitsAdded.length===0)return`No significant changes since last session (${e.durationFormatted} ago).`;let n=[];return n.push(`Since last session (${e.durationFormatted} ago):`),e.totalFileChanges>0&&n.push(`${e.totalFileChanges} files changed`),e.commitsAdded.length>0&&n.push(`${e.commitsAdded.length} new commits`),e.branchChanged&&n.push(`branch ${e.branchChanged.from}\u2192${e.branchChanged.to}`),e.dependenciesUpdated.length>0&&n.push(`${e.dependenciesUpdated.length} deps updated`),Object.keys(e.dependenciesAdded).length>0&&n.push(`${Object.keys(e.dependenciesAdded).length} deps added`),n.join(", ")+"."}function uke(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60),s=Math.floor(r/24);return s>0?`${s}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}async function dke(e,t,n={}){let r=f5(e),s=await d5(e,t,"");if(!r)return{briefing:"First session for this project \u2014 no previous state to diff against.",diff:null,snapshot:s};let i=m5(r,s);return{briefing:M1(i,n),diff:i,snapshot:s}}function fke(){if(!Tr(tl))return{totalSnapshots:0,totalDiffs:0,totalProjects:0,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:0,newestSnapshotAt:0,perProjectSnapshots:{}};let e=0,t=0,n=Date.now(),r=0,s={};try{let i=k0(tl);for(let o of i){let a=Zn(tl,o,"index.json");if(Tr(a))try{let c=JSON.parse(si(a,"utf-8"));e+=c.snapshots.length,t++,s[o]=c.snapshots.length;for(let l of c.snapshots)l.capturedAt<n&&(n=l.capturedAt),l.capturedAt>r&&(r=l.capturedAt)}catch{}}}catch{}return{totalSnapshots:e,totalDiffs:Math.max(0,e-t),totalProjects:t,averageSessionDurationMs:0,totalFileChangesTracked:0,totalCommitsTracked:0,oldestSnapshotAt:n,newestSnapshotAt:r,perProjectSnapshots:s}}function pke(e){let t=x0(Ud(e));if(!Tr(t))return!1;try{for(let n of k0(t))try{P1(Zn(t,n))}catch{}return!0}catch{return!1}}function mke(){if(!Tr(tl))return!0;try{for(let e of k0(tl)){let t=Zn(tl,e);try{for(let n of k0(t))P1(Zn(t,n))}catch{}}return!0}catch{return!1}}var tl,_1,Qwe,Zwe,Xwe,eke,C0=w(()=>{"use strict";tl=Zn(Wwe(),".aiaca","session-diff"),_1=30;Qwe=["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/*.{py,java,go,rs,c,cpp,h,hpp}","**/*.{json,yaml,yml,toml,xml}","**/*.{md,txt,rst}","**/*.{html,css,scss,sass}","**/*.{sh,ps1,bat,cmd}","**/*.sql","**/Makefile","**/Dockerfile*"],Zwe=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.cache/**","**/coverage/**","**/target/**","**/.next/**","**/.nuxt/**","**/__pycache__/**","**/.venv/**","**/venv/**","**/vendor/**","**/*.min.js","**/*.lock"],Xwe=2e3,eke=1024*1024});var b5={};$(b5,{addCustomTip:()=>Rke,buildContext:()=>Fke,checkContextualTriggers:()=>$ke,dismissTip:()=>Ake,formatTip:()=>Lke,getAllTipsForBrowsing:()=>Oke,getPreferences:()=>Mke,getTipForTrigger:()=>bs,getTipsStats:()=>Dke,rateTip:()=>Tke,recordQuery:()=>_ke,recordTipShown:()=>Cke,removeCustomTip:()=>Pke,resetTips:()=>Eke,setPreferences:()=>Ike});import{existsSync as gke,readFileSync as hke,writeFileSync as yke,mkdirSync as bke}from"fs";import{join as g5}from"path";import{homedir as vke}from"os";function y5(){bke(h5,{recursive:!0})}function wke(){if(y5(),!gke(E1)){Ki();return}try{V={...V,...JSON.parse(hke(E1,"utf-8"))}}catch{}}function Ki(){y5(),yke(E1,JSON.stringify(V,null,2),"utf-8")}function D1(){return[...Ske,...V.customTips]}function kke(e,t){if(V.dismissed.includes(e.id)||!V.preferences.enabled||V.preferences.showFrequency==="off"||V.preferences.categories.length>0&&!V.preferences.categories.includes(e.category)||V.preferences.tags.length>0&&!e.tags.some(i=>V.preferences.tags.includes(i)))return!1;let n={beginner:0,intermediate:1,advanced:2};if(n[e.difficulty]<n[V.preferences.minDifficulty])return!1;let r=V.shown[e.id]||[];if(e.showOnce&&r.length>0)return!1;let s=r.filter(i=>Date.now()-new Date(i.shownAt).getTime()<t.sessionAge);if(e.maxShowsPerSession&&s.length>=e.maxShowsPerSession)return!1;if(e.cooldownMs&&r.length>0){let i=r[r.length-1];if(Date.now()-new Date(i.shownAt).getTime()<e.cooldownMs)return!1}return!(e.triggerCondition&&!e.triggerCondition(t))}function xke(e,t){return D1().filter(n=>n.trigger===e).filter(n=>kke(n,t)).sort((n,r)=>r.priority-n.priority)}function bs(e,t){let n=xke(e,t);if(n.length===0)return null;let r=V.preferences.showFrequency;if(r==="rare"&&Math.random()>.3||r==="normal"&&Math.random()>.6)return null;let s=n.slice(0,3);return s[Math.floor(Math.random()*s.length)]}function $ke(e){if(e.isFirstRun){let n=bs("first_run",e);if(n)return n}if(e.errorCount>=3){let n=bs("multiple_failures",e);if(n)return n}else if(e.errorCount>0){let n=bs("after_error",e);if(n)return n}if(e.sessionAge>1800*1e3){let n=bs("long_session",e);if(n)return n}if(e.contextTokens>5e4){let n=bs("large_context",e);if(n)return n}if(e.totalCost>1){let n=bs("high_cost",e);if(n)return n}if([10,50,100,500,1e3,5e3].includes(e.totalQueriesEver)){let n=bs("milestone",e);if(n)return n}if(e.filesModified.length>0){let n=bs("file_modified",e);if(n)return n}if(e.toolUseCount===1){let n=bs("first_tool_use",e);if(n)return n}if(e.idleTimeMs>600*1e3){let n=bs("idle",e);if(n)return n}return null}function Cke(e,t){V.shown[e]||(V.shown[e]=[]),V.shown[e].push({tipId:e,trigger:t,shownAt:new Date().toISOString(),dismissed:!1}),Ki()}function Ake(e){V.dismissed.includes(e)||V.dismissed.push(e),Ki()}function Tke(e,t){let n=V.shown[e];n&&n.length>0&&(n[n.length-1].rated=t,Ki())}function _ke(){V.totalQueriesEver++,Ki()}function Rke(e){V.customTips.push(e),Ki()}function Pke(e){let t=V.customTips.length;return V.customTips=V.customTips.filter(n=>n.id!==e),Ki(),V.customTips.length<t}function Ike(e){V.preferences={...V.preferences,...e},Ki()}function Mke(){return{...V.preferences}}function Eke(){V.shown={},V.dismissed=[],Ki()}function Dke(){let e=new Map(D1().map(i=>[i.id,i])),t=0,n=0,r=0,s=[];for(let[i,o]of Object.entries(V.shown))t+=o.length,n+=o.filter(a=>a.rated==="helpful").length,r+=o.filter(a=>a.rated==="not_helpful").length,s.push({id:i,shows:o.length});return s.sort((i,o)=>o.shows-i.shows),{totalShows:t,uniqueTipsShown:Object.keys(V.shown).length,dismissedCount:V.dismissed.length,helpfulCount:n,notHelpfulCount:r,customTipsCount:V.customTips.length,totalQueries:V.totalQueriesEver,topShownTips:s.slice(0,10).map(i=>({id:i.id,message:e.get(i.id)?.message||"?",shows:i.shows}))}}function Fke(e,t){let n=Date.now(),r=t.sessionStartTime?n-t.sessionStartTime:0,s=0,i=0,o=[],a=[],c=[];for(let l of e){if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)s++,c.push(u.name),(u.name==="file_write"||u.name==="file_edit")&&a.push(String(u.input?.path));if(l.role==="user"&&/<tool_result.*error="true"|Error:|Exit code:/.test(l.content)){i++;let u=l.content.match(/Error: ([^\n]+)/);u&&o.push(u[1])}}return{sessionAge:r,messageCount:e.length,toolUseCount:s,errorCount:i,recentErrors:o.slice(-5),filesModified:[...new Set(a)],totalCost:t.totalCost||0,contextTokens:t.contextTokens||0,isFirstRun:V.totalQueriesEver===0,totalQueriesEver:V.totalQueriesEver,lastUsedTools:c.slice(-10),idleTimeMs:t.idleTimeMs||0}}function Lke(e){return`${e.difficulty==="beginner"?"\u{1F4A1}":e.difficulty==="intermediate"?"\u2728":"\u{1F393}"} Tip: ${e.message}`}function Oke(e){let t=D1();return e?.category&&(t=t.filter(n=>n.category===e.category)),e?.difficulty&&(t=t.filter(n=>n.difficulty===e.difficulty)),t.sort((n,r)=>r.priority-n.priority)}var Ske,h5,E1,V,v5=w(()=>{"use strict";Ske=[{id:"gs_help",message:"Type /help to see all available commands",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:9,tags:["basics"]},{id:"gs_init",message:"Create AIACA.md in your project root with /init to give persistent project context",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:8,tags:["memory"]},{id:"gs_model",message:"Use /model to switch between Claude and Gemini models for different tasks",category:"getting_started",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:7,tags:["models"]},{id:"gs_first_run",message:'Welcome to AIACA! Try asking it to "explain this codebase" to get started',category:"getting_started",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:10,tags:["welcome"]},{id:"prod_compact",message:"Use /compact to summarize long conversations and free up context window",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:9,cooldownMs:1800*1e3,tags:["context"]},{id:"prod_collapse",message:"Use /collapse for lossless context compression \u2014 preserves all info while shrinking tool results",category:"productivity",difficulty:"intermediate",trigger:"large_context",showOnce:!1,priority:8,tags:["context","efficiency"]},{id:"prod_recall",message:"Use /recall extract to save important facts from this session for future use",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["memory"]},{id:"prod_skill",message:"Browse pre-built skills with /skill list \u2014 they save typing for common tasks",category:"productivity",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:6,tags:["skills"]},{id:"cmd_resume",message:"Continue past sessions with /resume \u2014 your conversation history persists",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["session"]},{id:"cmd_export",message:"Save conversations as markdown with /export",category:"commands",difficulty:"beginner",trigger:"long_session",showOnce:!0,priority:5,tags:["export"]},{id:"cmd_diff",message:"Use /diff to see git changes inline",category:"commands",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:4,tags:["git"]},{id:"cmd_search",message:"Search past conversations with /search <query>",category:"commands",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:5,tags:["search"]},{id:"tool_first_bash",message:'Tip: AIACA can run any shell command via the bash tool \u2014 say "run npm install"',category:"tools",difficulty:"beginner",trigger:"first_tool_use",showOnce:!0,priority:7,tags:["shell"]},{id:"tool_image",message:'Copy an image to clipboard then ask AIACA to "look at this" \u2014 it auto-detects',category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["vision"]},{id:"tool_doc",message:"Generate .docx, .pptx, .pdf files using natural language \u2014 AIACA handles formatting",category:"tools",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["docs"]},{id:"tool_agent",message:"Spawn parallel sub-agents with the agent tool for independent subtasks",category:"tools",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["agents"]},{id:"eff_plan_mode",message:"Use /plan for read-only exploration \u2014 prevents accidental writes",category:"efficiency",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:6,tags:["safety"]},{id:"eff_perm_auto",message:'Set permission mode to "auto" with /permissions auto for fewer interruptions on safe ops',category:"efficiency",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:7,tags:["permissions"]},{id:"eff_cache",message:"Enable response caching with /cache on for faster repeated queries",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:5,tags:["cache"]},{id:"eff_vcr",message:"Record + replay API calls with /vcr \u2014 perfect for testing and debugging",category:"efficiency",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["testing"]},{id:"qual_review",message:"Run /review or use the code-review skill before committing changes",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:7,cooldownMs:3600*1e3,tags:["review"]},{id:"qual_test",message:"Use the test-writer skill to generate comprehensive tests automatically",category:"quality",difficulty:"intermediate",trigger:"file_modified",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["testing"]},{id:"qual_security",message:"Run /skill security-audit periodically to catch vulnerabilities",category:"quality",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:6,tags:["security"]},{id:"qual_docs",message:"Generate documentation automatically with /docs readme --ai --write",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:5,tags:["docs"]},{id:"safe_perm",message:'Default permission mode "ask" prompts before destructive operations \u2014 safer for production',category:"safety",difficulty:"beginner",trigger:"startup",showOnce:!0,priority:6,tags:["permissions"]},{id:"safe_undo",message:"File edits are auto-snapshotted \u2014 recovery available via fileHistory",category:"safety",difficulty:"intermediate",trigger:"file_modified",showOnce:!0,priority:7,tags:["safety"]},{id:"safe_worktree",message:"Use /worktree for isolated git operations without affecting main branch",category:"safety",difficulty:"advanced",trigger:"startup",showOnce:!0,priority:5,tags:["git"]},{id:"cost_haiku",message:"Use /model gemini-2.5-flash-lite for cheap/fast simple queries",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["cost"]},{id:"cost_compact",message:"Compact context regularly \u2014 saves tokens on long sessions",category:"cost_savings",difficulty:"intermediate",trigger:"high_cost",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["cost"]},{id:"cost_cache",message:"Enable /cache for repeated similar queries \u2014 cuts cost dramatically",category:"cost_savings",difficulty:"advanced",trigger:"high_cost",showOnce:!0,priority:8,tags:["cost","cache"]},{id:"collab_team",message:"Sync memories across machines with /team start \u2014 knowledge persists across devices",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["team"]},{id:"collab_mcp",message:"Connect external tools via Model Context Protocol \u2014 see /mcp",category:"collaboration",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["mcp"]},{id:"collab_share",message:"Share session transcripts via /share for collaboration",category:"collaboration",difficulty:"intermediate",trigger:"long_session",showOnce:!0,priority:4,tags:["share"]},{id:"wf_init_first",message:"For new projects, run /init to scaffold an AIACA.md instructions file",category:"workflows",difficulty:"beginner",trigger:"first_run",showOnce:!0,priority:8,tags:["setup"]},{id:"wf_research",message:"For research tasks, web_search + web_fetch combination works great",category:"workflows",difficulty:"intermediate",trigger:"startup",showOnce:!0,priority:5,tags:["research"]},{id:"wf_refactor",message:"For refactoring: use the refactor skill with target file specified",category:"workflows",difficulty:"intermediate",trigger:"workflow_pattern",showOnce:!0,priority:6,tags:["refactor"]},{id:"wf_bug_hunt",message:"For bugs: describe the symptom, AIACA traces from observable to root cause",category:"workflows",difficulty:"intermediate",trigger:"after_failure",showOnce:!1,priority:7,cooldownMs:1800*1e3,tags:["debug"]},{id:"adv_dream",message:"Run /dream periodically \u2014 consolidates memories like REM sleep, generates insights",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["memory"]},{id:"adv_diag",message:"Track performance with /diagnose metrics \u2014 identify bottlenecks",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:3,tags:["perf"]},{id:"adv_hooks",message:"Add custom hooks (/hooks) to run shell commands on tool events",category:"advanced",difficulty:"advanced",trigger:"long_session",showOnce:!0,priority:4,tags:["hooks"]},{id:"ts_doctor",message:"Run /doctor to diagnose configuration issues",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!1,priority:8,cooldownMs:1800*1e3,tags:["debug"]},{id:"ts_retry",message:"AIACA auto-retries on rate limits with exponential backoff",category:"troubleshooting",difficulty:"beginner",trigger:"after_error",showOnce:!0,priority:7,tags:["errors"]},{id:"ts_logs",message:"Inspect detailed logs with /diagnose logs",category:"troubleshooting",difficulty:"intermediate",trigger:"multiple_failures",showOnce:!1,priority:8,cooldownMs:3600*1e3,tags:["debug"]},{id:"ts_clear",message:"If things get weird, /clear resets the conversation",category:"troubleshooting",difficulty:"beginner",trigger:"multiple_failures",showOnce:!1,priority:6,cooldownMs:3600*1e3,tags:["reset"]},{id:"ms_10",message:"\u{1F389} You've made 10 queries! Try /skill list to discover pre-built workflows",category:"getting_started",difficulty:"beginner",trigger:"milestone",showOnce:!0,priority:6,triggerCondition:e=>e.totalQueriesEver===10,tags:["milestone"]},{id:"ms_100",message:"\u{1F680} 100 queries! You're a power user. Have you tried /dream for memory consolidation?",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:5,triggerCondition:e=>e.totalQueriesEver===100,tags:["milestone"]},{id:"ms_1000",message:"\u{1F3C6} 1000 queries! You're officially an AIACA expert. Consider sharing skills with the community via /skill registry",category:"advanced",difficulty:"advanced",trigger:"milestone",showOnce:!0,priority:4,triggerCondition:e=>e.totalQueriesEver===1e3,tags:["milestone"]},{id:"nf_image",message:"NEW: AIACA now supports image inputs \u2014 paste from clipboard or reference file paths",category:"productivity",difficulty:"intermediate",trigger:"new_feature",showOnce:!0,priority:7,tags:["vision"]},{id:"nf_team",message:"NEW: Team memory sync lets multiple agents share knowledge \u2014 try /team start",category:"collaboration",difficulty:"advanced",trigger:"new_feature",showOnce:!0,priority:5,tags:["team"]},{id:"opp_no_tests",message:"I notice no test framework \u2014 consider adding one (jest, vitest, pytest)",category:"quality",difficulty:"intermediate",trigger:"opportunity",showOnce:!0,priority:6,tags:["testing"]},{id:"opp_no_readme",message:"No README found \u2014 generate one with /docs readme --ai --write",category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:7,tags:["docs"]},{id:"opp_no_git",message:'Not a git repo \u2014 initialize with "git init" to track changes',category:"quality",difficulty:"beginner",trigger:"opportunity",showOnce:!0,priority:6,tags:["git"]}],h5=g5(vke(),".aiaca","tips"),E1=g5(h5,"state.json"),V={installedAt:new Date().toISOString(),totalQueriesEver:0,shown:{},dismissed:[],preferences:{enabled:!0,showFrequency:"normal",minDifficulty:"beginner",categories:[],tags:[]},customTips:[]};wke()});var j1={};$(j1,{clearTeamMemory:()=>Zke,discoverAgents:()=>k5,getAgentPresence:()=>x5,getOrCreateIdentity:()=>ii,getTeamSyncStats:()=>Qke,loadTeamConfig:()=>Yke,manualSync:()=>exe,pruneOldData:()=>Xke,receiveMemories:()=>A0,registerPresence:()=>L1,saveTeamConfig:()=>C5,shareMemories:()=>O1,startAutoSync:()=>Vke,startFileWatcher:()=>Wke,stopAutoSync:()=>Jke,stopFileWatcher:()=>Kke,updateIdentity:()=>$g});import{existsSync as Vr,readFileSync as sl,writeFileSync as ra,mkdirSync as Hd,readdirSync as il,statSync as jke,watch as Bke,unlinkSync as xg}from"fs";import{join as Mt}from"path";import{homedir as Nke,hostname as S5}from"os";import{createHash as qke,randomUUID as Uke}from"crypto";function Jr(){Hd(ol,{recursive:!0}),Hd(Yi,{recursive:!0}),Hd(Gd,{recursive:!0}),Hd(Qi,{recursive:!0})}function ii(e){if(Jr(),_r)return _r;if(Vr(nl))try{return _r=JSON.parse(sl(nl,"utf-8")),_r.lastSeenAt=new Date().toISOString(),ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}catch{}return _r={id:`agent_${Uke()}`,name:e||`aiaca-${S5()}-${Date.now().toString(36).slice(-6)}`,hostname:S5(),startedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),capabilities:["memory_sync","conflict_resolution","crdt"],syncMode:"manual",factsShared:0,factsReceived:0},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function $g(e){return _r={...ii(),...e,lastSeenAt:new Date().toISOString()},ra(nl,JSON.stringify(_r,null,2),"utf-8"),_r}function L1(){Jr();let e=ii();e.lastSeenAt=new Date().toISOString(),ra(Mt(Yi,`${e.id}.json`),JSON.stringify(e,null,2),"utf-8")}function k5(){if(Jr(),!Vr(Yi))return[];let e=ii().id,t=Date.now()-1440*60*1e3,n=[];for(let r of il(Yi))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(Yi,r),"utf-8"));if(s.id===e)continue;if(new Date(s.lastSeenAt).getTime()<t){xg(Mt(Yi,r));continue}n.push(s)}catch{}return n}function x5(e){Jr();let t=Mt(Yi,`${e}.json`);if(!Vr(t))return"offline";try{let n=JSON.parse(sl(t,"utf-8")),r=Date.now()-new Date(n.lastSeenAt).getTime();return r<300*1e3?"online":r<3600*1e3?"recent":"offline"}catch{return"offline"}}function Hke(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=!1,s=!1;for(let i of n){let o=e[i]||0,a=t[i]||0;o>a&&(r=!0),a>o&&(s=!0)}return r&&s?"concurrent":r?"after":s?"before":"equal"}function zke(e,t){let n={...e};for(let[r,s]of Object.entries(t))n[r]=Math.max(n[r]||0,s);return n}function Gke(e,t="team"){let n=ii().id;return{...e,scope:t,ownerId:n,vectorClock:{[n]:1},signature:$5(e)}}function $5(e){return qke("sha256").update(`${e.id}:${e.content}:${e.category}`).digest("hex").slice(0,16)}function O1(e={}){Jr();let t=ii(),r=Jn().filter(o=>!(e.scope&&o.scope&&o.scope==="private"||e.categories&&!e.categories.includes(o.category)||e.minConfidence&&o.confidence<e.minConfidence||e.minImportance&&o.importance<e.minImportance));if(e.maxFacts&&(r=r.slice(0,e.maxFacts)),r.length===0)return{sharedCount:0,envelope:null};let s=r.map(o=>Gke(o,e.scope||"team")),i={fromAgent:t.id,toAgent:e.toAgentId,timestamp:new Date().toISOString(),facts:s,metadata:{syncRound:t.factsShared,totalFacts:s.length}};if(e.toAgentId){let o=Mt(Gd,e.toAgentId);Hd(o,{recursive:!0});let a=Mt(o,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(a,JSON.stringify(i,null,2),"utf-8")}else{let o=Mt(Qi,`${i.timestamp.replace(/[:.]/g,"_")}_${t.id.slice(-6)}.json`);ra(o,JSON.stringify(i,null,2),"utf-8")}return $g({factsShared:t.factsShared+s.length}),{sharedCount:s.length,envelope:i}}function A0(){Jr();let e=ii(),t=[],n=Mt(Gd,e.id);if(Vr(n)){for(let r of il(n))if(r.endsWith(".json"))try{let s=JSON.parse(sl(Mt(n,r),"utf-8")),i=w5(s);t.push(i),xg(Mt(n,r))}catch(s){t.push({added:0,updated:0,conflicts:0,rejected:0,totalReceived:0,errors:[s.message],durationMs:0})}}if(Vr(Qi))for(let r of il(Qi)){if(!r.endsWith(".json"))continue;let s=Mt(Qi,r);try{let i=JSON.parse(sl(s,"utf-8"));if(i.fromAgent===e.id)continue;let o=Mt(ol,`last_processed_${e.id}.json`),a={};if(Vr(o))try{a=JSON.parse(sl(o,"utf-8"))}catch{}if(a[i.fromAgent]&&a[i.fromAgent]>=i.timestamp)continue;let c=w5(i);t.push(c),a[i.fromAgent]=i.timestamp,ra(o,JSON.stringify(a,null,2),"utf-8")}catch{}}return t}function w5(e){let t=Date.now(),n=ii(),r=0,s=0,i=0,o=0,a=[],c=Jn(),l=new Map(c.map(u=>[u.id,u]));for(let u of e.facts)try{if(u.signature&&u.signature!==$5(u)){o++,a.push(`Bad signature on ${u.id}`);continue}let d=l.get(u.id);if(d){let f=Hke(d.vectorClock||{},u.vectorClock||{});f==="before"?(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent}}),s++):f==="concurrent"&&(i++,u.confidence>d.confidence&&(Nr(d.id),us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,metadata:{...u.metadata,syncedFrom:e.fromAgent,mergedClock:zke(d.vectorClock||{},u.vectorClock||{})}}),s++))}else{let f=u.vectorClock||{[e.fromAgent]:1};us(u.content,{category:u.category,confidence:u.confidence,source:"consolidated",tier:u.tier,tags:[...u.tags||[],`from:${e.fromAgent.slice(-8)}`],metadata:{...u.metadata,syncedFrom:e.fromAgent,vectorClock:f,scope:u.scope}}),r++}}catch(d){a.push(`Error merging ${u.id}: ${d.message}`),o++}return $g({factsReceived:n.factsReceived+r+s}),{added:r,updated:s,conflicts:i,rejected:o,totalReceived:e.facts.length,errors:a,fromAgent:e.fromAgent,durationMs:Date.now()-t}}function Vke(e=300*1e3,t="auto"){rl&&clearInterval(rl),$g({syncMode:t}),rl=setInterval(()=>{try{L1(),A0(),(t==="realtime"||t==="auto")&&O1({minConfidence:.75,minImportance:.6,maxFacts:50})}catch{}},e),rl.unref()}function Jke(){rl&&(clearInterval(rl),rl=null),$g({syncMode:"manual"})}function Wke(){if(kg)return;Jr();let e=ii(),t=Mt(Gd,e.id);Hd(t,{recursive:!0});try{kg=Bke(t,n=>{n==="rename"&&setTimeout(()=>A0(),100)})}catch{}}function Kke(){kg&&(kg.close(),kg=null)}function Yke(){if(Jr(),!Vr(F1))return C5(wg),wg;try{let e=JSON.parse(sl(F1,"utf-8"));return zd={...wg,...e},zd}catch{return wg}}function C5(e){return Jr(),zd={...zd,...e},ra(F1,JSON.stringify(zd,null,2),"utf-8"),zd}function Qke(){Jr();let e=ii(),t=k5(),n=t.filter(o=>x5(o.id)==="online").length,r=Mt(Gd,e.id),s=0;Vr(r)&&(s=il(r).filter(o=>o.endsWith(".json")).length);let i=0;return Vr(Qi)&&(i=il(Qi).filter(o=>o.endsWith(".json")).length),{myAgent:e,knownAgents:t.length,onlineAgents:n,totalFactsShared:e.factsShared,totalFactsReceived:e.factsReceived,inboxPending:s,sharedQueueSize:i,syncMode:e.syncMode}}function Zke(){Jr();for(let e of[Yi,Gd,Qi])if(Vr(e))for(let t of il(e))try{xg(Mt(e,t))}catch{}if(Vr(nl))try{xg(nl)}catch{}_r=null}function Xke(){Jr();let e=Date.now()-10080*60*1e3;for(let t of[Qi,Yi])if(Vr(t))for(let n of il(t))try{let r=Mt(t,n);jke(r).mtimeMs<e&&xg(r)}catch{}}async function exe(){L1();let e=O1({minConfidence:.75,minImportance:.6}),t=A0(),n=t.reduce((r,s)=>r+s.added+s.updated,0);return{shared:e.sharedCount,received:n,results:t}}var ol,Yi,Gd,Qi,nl,F1,_r,rl,kg,wg,zd,B1=w(()=>{"use strict";xu();ol=Mt(Nke(),".aiaca","team-memory"),Yi=Mt(ol,"agents"),Gd=Mt(ol,"inbox"),Qi=Mt(ol,"shared"),nl=Mt(ol,"identity.json"),F1=Mt(ol,"config.json");_r=null;rl=null;kg=null;wg={enabled:!1,mode:"manual",intervalMs:300*1e3,shareScope:"team",minConfidence:.75,minImportance:.6,maxFactsPerSync:50,enableFileWatcher:!1},zd={...wg}});var N5={};$(N5,{analyzeProject:()=>U1,categorizeCommits:()=>M5,extractSymbols:()=>H1,generateAPIDocs:()=>D5,generateAllDocs:()=>bxe,generateArchitecture:()=>L5,generateChangelog:()=>F5,generateDoc:()=>O5,generateReadme:()=>N1,getDocSuggestion:()=>vxe,getGitChangelog:()=>I5,renderFileTree:()=>Vd});import{existsSync as qt,readFileSync as q1,writeFileSync as T0,readdirSync as txe,statSync as nxe}from"fs";import{join as pt,basename as _5,extname as rxe,relative as Cg,dirname as sxe}from"path";import{execSync as ixe}from"child_process";import{globSync as R5}from"glob";function U1(e){let t=axe(e),n=cxe(e),r=lxe(e,t),s=P5(e,e),i=uxe(e,t);return{name:t?.name||_5(e),description:t?.description,version:t?.version,language:n,framework:r,dependencies:t?.dependencies?Object.keys(t.dependencies):[],devDependencies:t?.devDependencies?Object.keys(t.devDependencies):[],scripts:t?.scripts||{},fileTree:s,entryPoint:t?.main||dxe(e,n),hasTests:!!i,testFramework:i}}function axe(e){let t=pt(e,"package.json");if(!qt(t))return null;try{return JSON.parse(q1(t,"utf-8"))}catch{return null}}function cxe(e){return qt(pt(e,"package.json"))?"JavaScript/TypeScript":qt(pt(e,"Cargo.toml"))?"Rust":qt(pt(e,"go.mod"))?"Go":qt(pt(e,"pyproject.toml"))||qt(pt(e,"requirements.txt"))?"Python":qt(pt(e,"pom.xml"))||qt(pt(e,"build.gradle"))?"Java":qt(pt(e,"Gemfile"))?"Ruby":qt(pt(e,"*.csproj"))?"C#":"Unknown"}function lxe(e,t){if(!t?.dependencies&&!t?.devDependencies)return;let n={...t.dependencies,...t.devDependencies};if(n.react)return"React";if(n.vue)return"Vue";if(n["@angular/core"])return"Angular";if(n.svelte)return"Svelte";if(n.next)return"Next.js";if(n.nuxt)return"Nuxt";if(n.express)return"Express";if(n.fastify)return"Fastify";if(n["@nestjs/core"])return"NestJS";if(n.ink)return"Ink (CLI)"}function uxe(e,t){if(!t)return;let n={...t.dependencies,...t.devDependencies};if(n.jest)return"Jest";if(n.vitest)return"Vitest";if(n.mocha)return"Mocha";if(n.cypress)return"Cypress";if(n.playwright)return"Playwright";if(qt(pt(e,"pytest.ini"))||qt(pt(e,"pyproject.toml")))return"pytest"}function dxe(e,t){let n=["src/index.ts","src/index.js","src/main.ts","index.ts","index.js","main.py","main.go","src/main.rs"];for(let r of n)if(qt(pt(e,r)))return r}function P5(e,t,n=0,r=4){let s=_5(t)||t,i=nxe(t);if(!i.isDirectory())return{name:s,type:"file",path:Cg(e,t),size:i.size};let o={name:s,type:"dir",path:Cg(e,t),children:[]};if(n>=r)return o;try{let a=txe(t);for(let c of a){if(c.startsWith(".")&&!A5.has(c)||oxe.has(c))continue;let l=pt(t,c);try{let u=P5(e,l,n+1,r);A5.has(c)&&(u.important=!0),o.children.push(u)}catch{}}}catch{}return o}function H1(e){if(!qt(e))return[];let t=rxe(e);if(![".ts",".tsx",".js",".jsx",".mjs"].includes(t))return[];let n=q1(e,"utf-8"),r=[];for(let[s,i]of Object.entries(fxe)){i.lastIndex=0;let o;for(;(o=i.exec(n))!==null;){let a=n.slice(0,o.index).split(`
1888
1918
  `).length,c=pxe(s,o,e,a,n);c&&r.push(c)}}return gxe(r)}function pxe(e,t,n,r,s){let i=!!t[2]?.includes("export"),o,a=t[0].trim().replace(/\s+/g," ").slice(0,200);switch(e){case"function":o=t[4];break;case"arrowFunction":o=t[3];break;case"class":o=t[4];break;case"interface":o=t[3];break;case"type":o=t[3];break;case"enum":o=t[3];break;case"const":o=t[3];break}if(!o)return null;let c=mxe(s,t.index);return{name:o,kind:e==="arrowFunction"?"function":e==="method"?"method":e,file:n,line:r,signature:a,isExported:i,isAsync:!!t[3]?.includes("async")||!!t[5]?.includes("async"),jsdoc:c}}function mxe(e,t){let r=e.slice(0,t).split(`
1889
1919
  `),s=[];for(let i=r.length-1;i>=0;i--){let o=r[i].trim();if(!(o===""&&s.length===0))if(o.startsWith("//")||o.startsWith("*")||o.startsWith("/**")||o.startsWith("*/"))s.unshift(o.replace(/^[/*]+\s?/,"").replace(/\s*\*\/$/,""));else break}return s.length>0?s.join(`
1890
1920
  `).trim():void 0}function gxe(e){let t=new Set;return e.filter(n=>{let r=`${n.file}:${n.name}:${n.kind}`;return t.has(r)?!1:(t.add(r),!0)})}function Vd(e,t="",n=!0){let r=[],s=t===""?"":n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",i=e.important?" \u2B50":"";if(r.push(`${t}${s}${e.name}${e.type==="dir"?"/":""}${i}`),e.children&&e.children.length>0){let o=t+(t===""?"":n?" ":"\u2502 ");for(let a=0;a<e.children.length;a++){let c=a===e.children.length-1;r.push(Vd(e.children[a],o,c))}}return r.join(`
1891
- `)}function Iq(e,t){try{let n=t?`${t}..HEAD`:"-30";return ixe(`git log ${n} --pretty=format:"%h|%s|%an|%ar"`,{cwd:e,encoding:"utf-8",timeout:5e3}).trim().split(`
1892
- `).filter(Boolean)}catch{return[]}}function Mq(e){let t={Features:[],"Bug Fixes":[],Performance:[],Documentation:[],Refactoring:[],Tests:[],Other:[]};for(let n of e){let[r,s,i,o]=n.split("|"),a=`${s} (${r})`;/^(feat|feature)[:\(]/i.test(s)?t.Features.push(a):/^(fix|bugfix)[:\(]/i.test(s)?t["Bug Fixes"].push(a):/^perf[:\(]/i.test(s)?t.Performance.push(a):/^docs?[:\(]/i.test(s)?t.Documentation.push(a):/^refactor[:\(]/i.test(s)?t.Refactoring.push(a):/^test[:\(]/i.test(s)?t.Tests.push(a):t.Other.push(a)}return t}async function N1(e,t){let n=Date.now(),r=U1(e.cwd),s,i=0;return t&&e.detail!=="brief"?(s=await hxe(r,e,t),i++):s=Eq(r,e),e.outputPath&&T0(e.outputPath,s,"utf-8"),{type:"readme",content:s,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:jq(r.fileTree),symbolsAnalyzed:0,metadata:{aiCalls:i,confidence:i>0?.95:.8,sections:Bq(s)}}}function Eq(e,t){let n=[];if(n.push(`# ${e.name}`),n.push(""),e.description&&n.push(e.description,""),e.version&&n.push(`**Version:** ${e.version}`,""),n.push("## Tech Stack"),n.push(`- **Language:** ${e.language}`),e.framework&&n.push(`- **Framework:** ${e.framework}`),e.testFramework&&n.push(`- **Testing:** ${e.testFramework}`),n.push(""),e.dependencies.length>0&&(n.push("## Dependencies"),n.push(e.dependencies.slice(0,15).map(r=>`- ${r}`).join(`
1921
+ `)}function I5(e,t){try{let n=t?`${t}..HEAD`:"-30";return ixe(`git log ${n} --pretty=format:"%h|%s|%an|%ar"`,{cwd:e,encoding:"utf-8",timeout:5e3}).trim().split(`
1922
+ `).filter(Boolean)}catch{return[]}}function M5(e){let t={Features:[],"Bug Fixes":[],Performance:[],Documentation:[],Refactoring:[],Tests:[],Other:[]};for(let n of e){let[r,s,i,o]=n.split("|"),a=`${s} (${r})`;/^(feat|feature)[:\(]/i.test(s)?t.Features.push(a):/^(fix|bugfix)[:\(]/i.test(s)?t["Bug Fixes"].push(a):/^perf[:\(]/i.test(s)?t.Performance.push(a):/^docs?[:\(]/i.test(s)?t.Documentation.push(a):/^refactor[:\(]/i.test(s)?t.Refactoring.push(a):/^test[:\(]/i.test(s)?t.Tests.push(a):t.Other.push(a)}return t}async function N1(e,t){let n=Date.now(),r=U1(e.cwd),s,i=0;return t&&e.detail!=="brief"?(s=await hxe(r,e,t),i++):s=E5(r,e),e.outputPath&&T0(e.outputPath,s,"utf-8"),{type:"readme",content:s,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:j5(r.fileTree),symbolsAnalyzed:0,metadata:{aiCalls:i,confidence:i>0?.95:.8,sections:B5(s)}}}function E5(e,t){let n=[];if(n.push(`# ${e.name}`),n.push(""),e.description&&n.push(e.description,""),e.version&&n.push(`**Version:** ${e.version}`,""),n.push("## Tech Stack"),n.push(`- **Language:** ${e.language}`),e.framework&&n.push(`- **Framework:** ${e.framework}`),e.testFramework&&n.push(`- **Testing:** ${e.testFramework}`),n.push(""),e.dependencies.length>0&&(n.push("## Dependencies"),n.push(e.dependencies.slice(0,15).map(r=>`- ${r}`).join(`
1893
1923
  `)),e.dependencies.length>15&&n.push(`- *...and ${e.dependencies.length-15} more*`),n.push("")),Object.keys(e.scripts).length>0){n.push("## Scripts"),n.push("```bash");for(let[r,s]of Object.entries(e.scripts))n.push(`npm run ${r} # ${s}`);n.push("```"),n.push("")}return t.includeTOC&&n.splice(2,0,"## Table of Contents","","- [Tech Stack](#tech-stack)","- [Dependencies](#dependencies)","- [Scripts](#scripts)","- [Project Structure](#project-structure)",""),n.push("## Project Structure"),n.push("```"),n.push(Vd(e.fileTree).slice(0,3e3)),n.push("```"),n.push(""),n.push("## Getting Started"),n.push("```bash"),e.language.includes("JavaScript")?n.push("npm install",e.scripts.dev?"npm run dev":"npm start"):e.language==="Python"?n.push("pip install -r requirements.txt",`python ${e.entryPoint||"main.py"}`):e.language==="Rust"?n.push("cargo build","cargo run"):e.language==="Go"&&n.push("go mod download","go run ."),n.push("```"),n.join(`
1894
- `)}async function hxe(e,t,n){let r=Eq(e,t),s=t.detail||"standard",i="";e.entryPoint&&qt(pt(t.cwd,e.entryPoint))&&(i=q1(pt(t.cwd,e.entryPoint),"utf-8").slice(0,3e3));let o=`Generate a professional README.md for this project.
1924
+ `)}async function hxe(e,t,n){let r=E5(e,t),s=t.detail||"standard",i="";e.entryPoint&&qt(pt(t.cwd,e.entryPoint))&&(i=q1(pt(t.cwd,e.entryPoint),"utf-8").slice(0,3e3));let o=`Generate a professional README.md for this project.
1895
1925
 
1896
1926
  PROJECT INFO:
1897
1927
  - Name: ${e.name}
@@ -1922,9 +1952,9 @@ ${s==="comprehensive"?`
1922
1952
  10. Contributing
1923
1953
  11. License`:""}
1924
1954
 
1925
- Use proper Markdown. Be specific to this project, not generic. Output ONLY the README content, no explanations.`;try{return(await n.sendMessage([{role:"user",content:o,timestamp:new Date().toISOString()}],"You are a technical writing expert. Generate clean, professional README files.",[],void 0)).content.trim()}catch{return r}}async function Dq(e,t){let n=Date.now(),r=e.files||Rq("src/**/*.{ts,tsx,js,jsx}",{cwd:e.cwd,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**"]}),s=[];for(let o of r.slice(0,50)){let a=pt(e.cwd,o),c=H1(a);s.push(...c.filter(l=>l.isExported))}let i=await yxe(s,e,t);return e.outputPath&&T0(e.outputPath,i,"utf-8"),{type:"api",content:i,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:r.length,symbolsAnalyzed:s.length,metadata:{aiCalls:t?1:0,confidence:.85,sections:["API Reference"]}}}async function yxe(e,t,n){let r=["# API Reference",""],s=new Map;for(let i of e){let o=Cg(t.cwd,i.file);s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`## \`${i}\``),r.push("");for(let a of o){let c=a.kind==="function"?"\u0192":a.kind==="class"?"C":a.kind==="interface"?"I":a.kind==="type"?"T":"\u2022";r.push(`### ${c} \`${a.name}\``),r.push(""),r.push(`**Kind:** ${a.kind}${a.isAsync?" (async)":""}${a.isExported?" \xB7 exported":""}`),r.push(`**Location:** \`${i}:${a.line}\``),r.push(""),r.push("```typescript"),r.push(a.signature),r.push("```"),r.push(""),a.jsdoc&&(r.push(a.jsdoc),r.push("")),r.push("---"),r.push("")}}return r.join(`
1926
- `)}async function Fq(e,t){let n=Date.now(),r=Iq(e.cwd),s=Mq(r),i=["# Changelog","",`## ${new Date().toISOString().slice(0,10)}`,""];for(let[a,c]of Object.entries(s))if(c.length!==0){i.push(`### ${a}`);for(let l of c)i.push(`- ${l}`);i.push("")}let o=i.join(`
1927
- `);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"changelog",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:0,symbolsAnalyzed:0,metadata:{aiCalls:0,confidence:.9,sections:Object.keys(s)}}}async function Lq(e,t){let n=Date.now(),r=U1(e.cwd),s=Rq("src/**/*.{ts,tsx,js,jsx,py}",{cwd:e.cwd,ignore:["**/*.test.*","**/node_modules/**"]}).slice(0,30),i=[];for(let c of s)i.push(...H1(pt(e.cwd,c)).filter(l=>l.isExported));let o="",a=0;if(t){let c=`Generate an architecture document for this project.
1955
+ Use proper Markdown. Be specific to this project, not generic. Output ONLY the README content, no explanations.`;try{return(await n.sendMessage([{role:"user",content:o,timestamp:new Date().toISOString()}],"You are a technical writing expert. Generate clean, professional README files.",[],void 0)).content.trim()}catch{return r}}async function D5(e,t){let n=Date.now(),r=e.files||R5("src/**/*.{ts,tsx,js,jsx}",{cwd:e.cwd,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**"]}),s=[];for(let o of r.slice(0,50)){let a=pt(e.cwd,o),c=H1(a);s.push(...c.filter(l=>l.isExported))}let i=await yxe(s,e,t);return e.outputPath&&T0(e.outputPath,i,"utf-8"),{type:"api",content:i,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:r.length,symbolsAnalyzed:s.length,metadata:{aiCalls:t?1:0,confidence:.85,sections:["API Reference"]}}}async function yxe(e,t,n){let r=["# API Reference",""],s=new Map;for(let i of e){let o=Cg(t.cwd,i.file);s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`## \`${i}\``),r.push("");for(let a of o){let c=a.kind==="function"?"\u0192":a.kind==="class"?"C":a.kind==="interface"?"I":a.kind==="type"?"T":"\u2022";r.push(`### ${c} \`${a.name}\``),r.push(""),r.push(`**Kind:** ${a.kind}${a.isAsync?" (async)":""}${a.isExported?" \xB7 exported":""}`),r.push(`**Location:** \`${i}:${a.line}\``),r.push(""),r.push("```typescript"),r.push(a.signature),r.push("```"),r.push(""),a.jsdoc&&(r.push(a.jsdoc),r.push("")),r.push("---"),r.push("")}}return r.join(`
1956
+ `)}async function F5(e,t){let n=Date.now(),r=I5(e.cwd),s=M5(r),i=["# Changelog","",`## ${new Date().toISOString().slice(0,10)}`,""];for(let[a,c]of Object.entries(s))if(c.length!==0){i.push(`### ${a}`);for(let l of c)i.push(`- ${l}`);i.push("")}let o=i.join(`
1957
+ `);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"changelog",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:0,symbolsAnalyzed:0,metadata:{aiCalls:0,confidence:.9,sections:Object.keys(s)}}}async function L5(e,t){let n=Date.now(),r=U1(e.cwd),s=R5("src/**/*.{ts,tsx,js,jsx,py}",{cwd:e.cwd,ignore:["**/*.test.*","**/node_modules/**"]}).slice(0,30),i=[];for(let c of s)i.push(...H1(pt(e.cwd,c)).filter(l=>l.isExported));let o="",a=0;if(t){let c=`Generate an architecture document for this project.
1928
1958
 
1929
1959
  PROJECT: ${r.name}
1930
1960
  LANGUAGE: ${r.language}
@@ -1945,9 +1975,9 @@ Generate ARCHITECTURE.md covering:
1945
1975
  5. Extension points
1946
1976
  6. Design decisions
1947
1977
 
1948
- Use Markdown. Output only the document content.`;try{o=(await t.sendMessage([{role:"user",content:c,timestamp:new Date().toISOString()}],"You are a software architect. Generate clear architecture documentation.",[],void 0)).content.trim(),a=1}catch{o=Tq(r,i,e.cwd)}}else o=Tq(r,i,e.cwd);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"architecture",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:s.length,symbolsAnalyzed:i.length,metadata:{aiCalls:a,confidence:a>0?.9:.75,sections:Bq(o)}}}function Tq(e,t,n){let r=["# Architecture","","## Overview",`${e.name} is a ${e.language} ${e.framework?`${e.framework} `:""}application.`,"","## Module Organization","```",Vd(e.fileTree),"```","","## Key Components"],s=new Map;for(let i of t){let o=sxe(Cg(n,i.file));s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`### \`${i}/\``),r.push(`Contains ${o.length} exported symbol(s):`);for(let a of o.slice(0,10))r.push(`- **${a.kind}** \`${a.name}\``);r.push("")}return r.join(`
1949
- `)}async function Oq(e,t){switch(e.type){case"readme":return N1(e,t);case"api":case"reference":return Dq(e,t);case"architecture":case"overview":return Lq(e,t);case"changelog":return Fq(e,t);default:return N1(e,t)}}async function bxe(e,t){let n=["readme","api","architecture","changelog"],r=[];for(let s of n)try{let i=await Oq({type:s,cwd:e,detail:"standard"},t);r.push(i)}catch{}return r}function jq(e){return e.type==="file"?1:(e.children||[]).reduce((t,n)=>t+jq(n),0)}function Bq(e){let t=[];for(let n of e.split(`
1950
- `))n.startsWith("## ")&&t.push(n.slice(3).trim());return t}function vxe(e){return qt(pt(e,"README.md"))?qt(pt(e,"CHANGELOG.md"))?!qt(pt(e,"docs/architecture.md"))&&!qt(pt(e,"ARCHITECTURE.md"))?"architecture":!qt(pt(e,"docs/api.md"))&&!qt(pt(e,"API.md"))?"api":null:"changelog":"readme"}var oxe,Aq,fxe,qq=w(()=>{"use strict";oxe=new Set(["node_modules",".git","dist","build",".next","target","venv",".venv","__pycache__",".cache"]),Aq=new Set(["README.md","package.json","tsconfig.json","Cargo.toml","pyproject.toml","requirements.txt","go.mod","index.ts","index.js","main.py","main.go","main.rs","src/index.ts","src/main.ts"]);fxe={function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(<[^>]+>)?\s*\(([^)]*)\)(\s*:\s*([^{]+))?/gm,arrowFunction:/^(\s*)(export\s+)?const\s+(\w+)\s*(:\s*[^=]+)?\s*=\s*(async\s+)?(\([^)]*\)|[^=]+)\s*=>/gm,class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[^{]+)?/gm,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s*<[^>]+>)?(\s+extends\s+[^{]+)?/gm,type:/^(\s*)(export\s+)?type\s+(\w+)(\s*<[^>]+>)?\s*=/gm,enum:/^(\s*)(export\s+)?enum\s+(\w+)/gm,const:/^(\s*)(export\s+)?const\s+(\w+)\s*[:=]/gm}});async function Jd(e,t={}){let n={...Sxe,...t},r=null;for(let s=0;s<=n.maxRetries;s++)try{return await e()}catch(i){r=i;let o=i.status||i.statusCode||i.code;if(!(n.retryableStatuses.includes(o)||i.message?.includes("ECONNRESET")||i.message?.includes("ETIMEDOUT")||i.message?.includes("overloaded"))||s===n.maxRetries)throw i;let c=Math.random()*.3+.85,l=Math.min(n.baseDelayMs*Math.pow(2,s)*c,n.maxDelayMs),u=i.headers?.["retry-after"],d=u?parseInt(u)*1e3:l;n.onRetry?.(s+1,i,d),await wxe(d)}throw r}function wxe(e){return new Promise(t=>setTimeout(t,e))}var Sxe,z1=w(()=>{"use strict";Sxe={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,retryableStatuses:[429,500,502,503,529]}});import kxe from"@anthropic-ai/sdk";var _0,Uq=w(()=>{"use strict";z1();w0();_0=class{constructor(t,n){this.apiKey=t;this.model=n;this.client=new kxe({apiKey:t,maxRetries:0})}apiKey;model;name="claude";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=t.map(u=>({role:u.role,content:u.content})),a=r.map(u=>({name:u.name,description:u.description,input_schema:{type:"object",properties:Object.fromEntries(u.parameters.map(d=>[d.name,{type:d.type,description:d.description}])),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}));if(s){let u=await this.streamWithRetry(o,n,a,s);return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let c=s||(()=>{}),l=await Jd(()=>this.doSend(o,n,a),{onRetry:(u,d,f)=>{c({type:"error",error:`Retry ${u} in ${Math.round(f/1e3)}s: ${d.message}`})}});return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n,r){let s=await this.client.messages.create({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),i=s.content.filter(a=>a.type==="text").map(a=>a.text).join(""),o=s.content.filter(a=>a.type==="tool_use").map(a=>{let c=a;return{id:c.id,name:c.name,input:c.input}});return{content:i,toolCalls:o,usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens}}}async streamWithRetry(t,n,r,s){return Jd(()=>this.doStream(t,n,r,s),{onRetry:(i,o,a)=>{s({type:"error",error:`Retry ${i} in ${Math.round(a/1e3)}s (${o.message})`})}})}async doStream(t,n,r,s){let i=this.client.messages.stream({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),o="",a=[],c=null;for await(let u of i)if(u.type==="content_block_start"){let d=u.content_block;d.type==="tool_use"&&(c={id:d.id,name:d.name,input:{}},s({type:"tool_call_start",toolCall:c}))}else if(u.type==="content_block_delta"){let d=u.delta;d.type==="text_delta"?(o+=d.text,s({type:"text",text:d.text})):d.type==="input_json_delta"&&c&&s({type:"tool_call_delta",text:d.partial_json})}else u.type==="content_block_stop"&&c&&(a.push(c),s({type:"tool_call_end",toolCall:c}),c=null);let l=await i.finalMessage();for(let u of l.content)if(u.type==="tool_use"){let d=a.find(f=>f.id===u.id);d&&(d.input=u.input)}return s({type:"done"}),{content:o,toolCalls:a,usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens}}}}});import{GoogleGenAI as xxe}from"@google/genai";var R0,Hq=w(()=>{"use strict";z1();Lm();w0();R0=class{constructor(t,n){this.apiKey=t;this.model=n;let r=process.stderr.write.bind(process.stderr);process.stderr.write=((s,...i)=>(typeof s=="string"?s:s?.toString?.()||"").includes("API key should be set when using the Gemini API")?!0:r(s,...i));try{this.client=new xxe({apiKey:t||"missing"})}finally{process.stderr.write=r}}apiKey;model;name="gemini";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=r.length>0?[{functionDeclarations:r.map(u=>({name:u.name,description:u.description,parameters:{type:"OBJECT",properties:Object.fromEntries(u.parameters.map(d=>{let f={type:d.type.toUpperCase(),description:d.description};if(d.type==="array"||d.type.toUpperCase()==="ARRAY"){let p=d.items;f.items=p?{type:String(p.type||"string").toUpperCase()}:{type:"STRING"}}return(d.type==="object"||d.type.toUpperCase()==="OBJECT")&&!d.properties&&(delete f.type,f.type="OBJECT",f.properties=d.properties||{}),[d.name,f]})),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}))}]:[],a=t.map((u,d)=>{let f=[{text:u.content}];if(u.role==="user"&&d===t.length-1&&VA()){for(let p of zA())f.push({inlineData:{mimeType:p.mimeType,data:p.base64}});GA()}return{role:u.role==="assistant"?"model":"user",parts:f}}),c={systemInstruction:n,tools:o};if(s){let u=await Jd(()=>this.doStream(a,c,s),{onRetry:(d,f,p)=>s({type:"error",error:`Retry ${d} in ${Math.round(p/1e3)}s (${f.message})`})});return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let l=await Jd(()=>this.doSend(a,c));return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n){let r=await this.client.models.generateContent({model:this.model,config:n,contents:t}),s="",i=[],o=r.candidates||[];for(let a of o){let c=a?.content?.parts||[];for(let l of c)typeof l?.text=="string"&&l.text&&(s+=l.text),l?.functionCall&&i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:l.functionCall.name,input:l.functionCall.args||{}})}if(!s&&i.length===0){try{s=r.text||""}catch{}if(r.functionCalls)for(let a of r.functionCalls)i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:a.name,input:a.args||{}})}return{content:s,toolCalls:i,usage:r.usageMetadata?{inputTokens:r.usageMetadata.promptTokenCount||0,outputTokens:r.usageMetadata.candidatesTokenCount||0}:void 0}}async doStream(t,n,r){let s=await this.client.models.generateContentStream({model:this.model,config:n,contents:t}),i="",o=[];for await(let a of s){let c="",l=a.candidates||[];for(let u of l){let d=u?.content?.parts||[];for(let f of d)if(typeof f?.text=="string"&&f.text&&(c+=f.text),f?.functionCall){let p={id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:f.functionCall.name,input:f.functionCall.args||{}};o.push(p),r({type:"tool_call_start",toolCall:p}),r({type:"tool_call_end",toolCall:p})}}c&&(i+=c,r({type:"text",text:c}))}return r({type:"done"}),{content:i,toolCalls:o,usage:void 0}}}});var sa={};$(sa,{createProvider:()=>Wd});function Wd(e,t,n){switch(e){case"claude":return new _0(t,n);case"gemini":return new R0(t,n);default:throw new Error(`Unknown provider: ${e}`)}}var Zi=w(()=>{"use strict";Uq();Hq()});var I0={};$(I0,{checkAndDreamIfIdle:()=>Wq,formatBrief:()=>Jxe,formatCycleAsMarkdown:()=>Vxe,getDreamConfig:()=>Gxe,getDreamHistory:()=>qxe,getDreamStats:()=>Hxe,getLastDream:()=>Uxe,recordActivity:()=>jxe,runDreamCycle:()=>Jq,setDreamConfig:()=>zxe,startAutoDreamScheduler:()=>Bxe,stopAutoDreamScheduler:()=>Nxe});import{existsSync as zq,mkdirSync as $xe,readFileSync as Gq,writeFileSync as Vq}from"fs";import{join as J1}from"path";import{homedir as Cxe}from"os";function K1(){$xe(W1,{recursive:!0})}function Txe(){if(K1(),!!zq(G1))try{Rr=JSON.parse(Gq(G1,"utf-8"))}catch{}}function _xe(){K1();let e=Rr.slice(-50);Vq(G1,JSON.stringify(e,null,2),"utf-8")}async function Rxe(){let e=t$(),t=Jn(),n=new Map;for(let s of t){let i=s.content.toLowerCase().trim();n.has(i)||n.set(i,[]),n.get(i).push(s)}let r=0;for(let s of n.values())if(!(s.length<2)){s.sort((i,o)=>o.importance-i.importance);for(let i of s.slice(1))Nr(i.id)&&r++}return{duplicatesRemoved:r,factsPromoted:e.promoted,factsPruned:e.removed,importanceRecalibrated:t.length}}async function Pxe(e){let t=Jn();if(t.length<5)return{};let n=[],r=0,s=new Map;for(let o of t)s.has(o.category)||s.set(o.category,[]),s.get(o.category).push(o);for(let[o,a]of s){if(a.length<2)continue;let c=Ixe(a);for(let l of c){if(l.length<2)continue;let u=Exe(l),d=l.map(p=>p.id);for(let p of l)Nr(p.id);let f=us(u,{category:o,confidence:Math.max(...l.map(p=>p.confidence)),source:"consolidated",tier:"long_term"});n.push({from:l.map(p=>p.content),to:u,mergedFactId:f.id})}}let i=t.filter(o=>o.contradicts&&o.contradicts.length>0);for(let o of i)if(o.contradicts)for(let a of o.contradicts){let c=t.find(u=>u.id===a);if(!c)continue;let l=new Date(o.createdAt).getTime()>new Date(c.createdAt).getTime();l&&o.confidence>=c.confidence?Nr(c.id)&&r++:!l&&c.confidence>o.confidence&&Nr(o.id)&&r++}return{factsMerged:n,contradictionsResolved:r}}function Ixe(e){let t=[],n=new Set;for(let r of e){if(n.has(r.id))continue;let s=[r];n.add(r.id);for(let i of e){if(n.has(i.id))continue;let o=Mxe(r.tokens,i.tokens);o>.5&&o<.95&&(s.push(i),n.add(i.id))}s.length>1&&t.push(s)}return t}function Mxe(e,t){let n=new Set(e),r=new Set(t),s=new Set([...n].filter(o=>r.has(o))),i=new Set([...n,...r]);return i.size===0?0:s.size/i.size}function Exe(e){e.sort((s,i)=>i.content.length-s.content.length);let t=e[0].content,r=e.slice(1).map(s=>s.content).filter(s=>!t.toLowerCase().includes(s.toLowerCase().slice(0,30)));return r.length===0?t:`${t} (also: ${r.slice(0,2).join("; ")})`}async function Dxe(e){let t=Jn();if(t.length<8)return{};let n=[...t].sort((o,a)=>a.importance-o.importance).slice(0,30),r=[],s=[],i=0;if(Wr.enableInsightGeneration&&i<Wr.maxAICallsPerDream){let o=await Fxe(n,e);r.push(...o),i++;for(let a of o.filter(c=>c.confidence>=.8))us(a.content,{category:a.category,confidence:a.confidence,source:"inferred",tier:"long_term",metadata:{dreamGenerated:!0,basedOn:a.basedOn}})}if(Wr.enablePatternDiscovery&&i<Wr.maxAICallsPerDream){let o=await Lxe(n,e);s.push(...o),i++}return{insightsGenerated:r,patternsDiscovered:s}}async function Fxe(e,t){let r=`Analyze these memory facts and generate 3-5 high-level INSIGHTS that:
1978
+ Use Markdown. Output only the document content.`;try{o=(await t.sendMessage([{role:"user",content:c,timestamp:new Date().toISOString()}],"You are a software architect. Generate clear architecture documentation.",[],void 0)).content.trim(),a=1}catch{o=T5(r,i,e.cwd)}}else o=T5(r,i,e.cwd);return e.outputPath&&T0(e.outputPath,o,"utf-8"),{type:"architecture",content:o,outputPath:e.outputPath,generatedAt:new Date().toISOString(),durationMs:Date.now()-n,filesAnalyzed:s.length,symbolsAnalyzed:i.length,metadata:{aiCalls:a,confidence:a>0?.9:.75,sections:B5(o)}}}function T5(e,t,n){let r=["# Architecture","","## Overview",`${e.name} is a ${e.language} ${e.framework?`${e.framework} `:""}application.`,"","## Module Organization","```",Vd(e.fileTree),"```","","## Key Components"],s=new Map;for(let i of t){let o=sxe(Cg(n,i.file));s.has(o)||s.set(o,[]),s.get(o).push(i)}for(let[i,o]of s){r.push(`### \`${i}/\``),r.push(`Contains ${o.length} exported symbol(s):`);for(let a of o.slice(0,10))r.push(`- **${a.kind}** \`${a.name}\``);r.push("")}return r.join(`
1979
+ `)}async function O5(e,t){switch(e.type){case"readme":return N1(e,t);case"api":case"reference":return D5(e,t);case"architecture":case"overview":return L5(e,t);case"changelog":return F5(e,t);default:return N1(e,t)}}async function bxe(e,t){let n=["readme","api","architecture","changelog"],r=[];for(let s of n)try{let i=await O5({type:s,cwd:e,detail:"standard"},t);r.push(i)}catch{}return r}function j5(e){return e.type==="file"?1:(e.children||[]).reduce((t,n)=>t+j5(n),0)}function B5(e){let t=[];for(let n of e.split(`
1980
+ `))n.startsWith("## ")&&t.push(n.slice(3).trim());return t}function vxe(e){return qt(pt(e,"README.md"))?qt(pt(e,"CHANGELOG.md"))?!qt(pt(e,"docs/architecture.md"))&&!qt(pt(e,"ARCHITECTURE.md"))?"architecture":!qt(pt(e,"docs/api.md"))&&!qt(pt(e,"API.md"))?"api":null:"changelog":"readme"}var oxe,A5,fxe,q5=w(()=>{"use strict";oxe=new Set(["node_modules",".git","dist","build",".next","target","venv",".venv","__pycache__",".cache"]),A5=new Set(["README.md","package.json","tsconfig.json","Cargo.toml","pyproject.toml","requirements.txt","go.mod","index.ts","index.js","main.py","main.go","main.rs","src/index.ts","src/main.ts"]);fxe={function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(<[^>]+>)?\s*\(([^)]*)\)(\s*:\s*([^{]+))?/gm,arrowFunction:/^(\s*)(export\s+)?const\s+(\w+)\s*(:\s*[^=]+)?\s*=\s*(async\s+)?(\([^)]*\)|[^=]+)\s*=>/gm,class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[^{]+)?/gm,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s*<[^>]+>)?(\s+extends\s+[^{]+)?/gm,type:/^(\s*)(export\s+)?type\s+(\w+)(\s*<[^>]+>)?\s*=/gm,enum:/^(\s*)(export\s+)?enum\s+(\w+)/gm,const:/^(\s*)(export\s+)?const\s+(\w+)\s*[:=]/gm}});async function Jd(e,t={}){let n={...Sxe,...t},r=null;for(let s=0;s<=n.maxRetries;s++)try{return await e()}catch(i){r=i;let o=i.status||i.statusCode||i.code;if(!(n.retryableStatuses.includes(o)||i.message?.includes("ECONNRESET")||i.message?.includes("ETIMEDOUT")||i.message?.includes("overloaded"))||s===n.maxRetries)throw i;let c=Math.random()*.3+.85,l=Math.min(n.baseDelayMs*Math.pow(2,s)*c,n.maxDelayMs),u=i.headers?.["retry-after"],d=u?parseInt(u)*1e3:l;n.onRetry?.(s+1,i,d),await wxe(d)}throw r}function wxe(e){return new Promise(t=>setTimeout(t,e))}var Sxe,z1=w(()=>{"use strict";Sxe={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,retryableStatuses:[429,500,502,503,529]}});import kxe from"@anthropic-ai/sdk";var _0,U5=w(()=>{"use strict";z1();w0();_0=class{constructor(t,n){this.apiKey=t;this.model=n;this.client=new kxe({apiKey:t,maxRetries:0})}apiKey;model;name="claude";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=t.map(u=>({role:u.role,content:u.content})),a=r.map(u=>({name:u.name,description:u.description,input_schema:{type:"object",properties:Object.fromEntries(u.parameters.map(d=>[d.name,{type:d.type,description:d.description}])),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}));if(s){let u=await this.streamWithRetry(o,n,a,s);return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let c=s||(()=>{}),l=await Jd(()=>this.doSend(o,n,a),{onRetry:(u,d,f)=>{c({type:"error",error:`Retry ${u} in ${Math.round(f/1e3)}s: ${d.message}`})}});return el()&&Xc({provider:"claude",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n,r){let s=await this.client.messages.create({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),i=s.content.filter(a=>a.type==="text").map(a=>a.text).join(""),o=s.content.filter(a=>a.type==="tool_use").map(a=>{let c=a;return{id:c.id,name:c.name,input:c.input}});return{content:i,toolCalls:o,usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens}}}async streamWithRetry(t,n,r,s){return Jd(()=>this.doStream(t,n,r,s),{onRetry:(i,o,a)=>{s({type:"error",error:`Retry ${i} in ${Math.round(a/1e3)}s (${o.message})`})}})}async doStream(t,n,r,s){let i=this.client.messages.stream({model:this.model,max_tokens:128e3,system:n,messages:t,tools:r}),o="",a=[],c=null;for await(let u of i)if(u.type==="content_block_start"){let d=u.content_block;d.type==="tool_use"&&(c={id:d.id,name:d.name,input:{}},s({type:"tool_call_start",toolCall:c}))}else if(u.type==="content_block_delta"){let d=u.delta;d.type==="text_delta"?(o+=d.text,s({type:"text",text:d.text})):d.type==="input_json_delta"&&c&&s({type:"tool_call_delta",text:d.partial_json})}else u.type==="content_block_stop"&&c&&(a.push(c),s({type:"tool_call_end",toolCall:c}),c=null);let l=await i.finalMessage();for(let u of l.content)if(u.type==="tool_use"){let d=a.find(f=>f.id===u.id);d&&(d.input=u.input)}return s({type:"done"}),{content:o,toolCalls:a,usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens}}}}});import{GoogleGenAI as xxe}from"@google/genai";var R0,H5=w(()=>{"use strict";z1();Lm();w0();R0=class{constructor(t,n){this.apiKey=t;this.model=n;let r=process.stderr.write.bind(process.stderr);process.stderr.write=((s,...i)=>(typeof s=="string"?s:s?.toString?.()||"").includes("API key should be set when using the Gemini API")?!0:r(s,...i));try{this.client=new xxe({apiKey:t||"missing"})}finally{process.stderr.write=r}}apiKey;model;name="gemini";client;async sendMessage(t,n,r,s){if(vg()){let u=bg({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:""});if(u){if(s&&u.content){for(let d of u.content.match(/.{1,40}/g)||[u.content])s({type:"text",text:d});s({type:"done"})}return{content:u.content,toolCalls:u.toolCalls,usage:u.usage}}}let i=Date.now(),o=r.length>0?[{functionDeclarations:r.map(u=>({name:u.name,description:u.description,parameters:{type:"OBJECT",properties:Object.fromEntries(u.parameters.map(d=>{let f={type:d.type.toUpperCase(),description:d.description};if(d.type==="array"||d.type.toUpperCase()==="ARRAY"){let p=d.items;f.items=p?{type:String(p.type||"string").toUpperCase()}:{type:"STRING"}}return(d.type==="object"||d.type.toUpperCase()==="OBJECT")&&!d.properties&&(delete f.type,f.type="OBJECT",f.properties=d.properties||{}),[d.name,f]})),required:u.parameters.filter(d=>d.required).map(d=>d.name)}}))}]:[],a=t.map((u,d)=>{let f=[{text:u.content}];if(u.role==="user"&&d===t.length-1&&VA()){for(let p of zA())f.push({inlineData:{mimeType:p.mimeType,data:p.base64}});GA()}return{role:u.role==="assistant"?"model":"user",parts:f}}),c={systemInstruction:n,tools:o};if(s){let u=await Jd(()=>this.doStream(a,c,s),{onRetry:(d,f,p)=>s({type:"error",error:`Retry ${d} in ${Math.round(p/1e3)}s (${f.message})`})});return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(d=>d.name),timestamp:new Date().toISOString()},{content:u.content,toolCalls:u.toolCalls,usage:u.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),u}let l=await Jd(()=>this.doSend(a,c));return el()&&Xc({provider:"gemini",model:this.model,systemPrompt:n,messages:t,tools:r.map(u=>u.name),timestamp:new Date().toISOString()},{content:l.content,toolCalls:l.toolCalls,usage:l.usage,durationMs:Date.now()-i,timestamp:new Date().toISOString()}),l}async doSend(t,n){let r=await this.client.models.generateContent({model:this.model,config:n,contents:t}),s="",i=[],o=r.candidates||[];for(let a of o){let c=a?.content?.parts||[];for(let l of c)typeof l?.text=="string"&&l.text&&(s+=l.text),l?.functionCall&&i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:l.functionCall.name,input:l.functionCall.args||{}})}if(!s&&i.length===0){try{s=r.text||""}catch{}if(r.functionCalls)for(let a of r.functionCalls)i.push({id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:a.name,input:a.args||{}})}return{content:s,toolCalls:i,usage:r.usageMetadata?{inputTokens:r.usageMetadata.promptTokenCount||0,outputTokens:r.usageMetadata.candidatesTokenCount||0}:void 0}}async doStream(t,n,r){let s=await this.client.models.generateContentStream({model:this.model,config:n,contents:t}),i="",o=[];for await(let a of s){let c="",l=a.candidates||[];for(let u of l){let d=u?.content?.parts||[];for(let f of d)if(typeof f?.text=="string"&&f.text&&(c+=f.text),f?.functionCall){let p={id:`gemini_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:f.functionCall.name,input:f.functionCall.args||{}};o.push(p),r({type:"tool_call_start",toolCall:p}),r({type:"tool_call_end",toolCall:p})}}c&&(i+=c,r({type:"text",text:c}))}return r({type:"done"}),{content:i,toolCalls:o,usage:void 0}}}});var sa={};$(sa,{createProvider:()=>Wd});function Wd(e,t,n){switch(e){case"claude":return new _0(t,n);case"gemini":return new R0(t,n);default:throw new Error(`Unknown provider: ${e}`)}}var Zi=w(()=>{"use strict";U5();H5()});var I0={};$(I0,{checkAndDreamIfIdle:()=>W5,formatBrief:()=>Jxe,formatCycleAsMarkdown:()=>Vxe,getDreamConfig:()=>Gxe,getDreamHistory:()=>qxe,getDreamStats:()=>Hxe,getLastDream:()=>Uxe,recordActivity:()=>jxe,runDreamCycle:()=>J5,setDreamConfig:()=>zxe,startAutoDreamScheduler:()=>Bxe,stopAutoDreamScheduler:()=>Nxe});import{existsSync as z5,mkdirSync as $xe,readFileSync as G5,writeFileSync as V5}from"fs";import{join as J1}from"path";import{homedir as Cxe}from"os";function K1(){$xe(W1,{recursive:!0})}function Txe(){if(K1(),!!z5(G1))try{Rr=JSON.parse(G5(G1,"utf-8"))}catch{}}function _xe(){K1();let e=Rr.slice(-50);V5(G1,JSON.stringify(e,null,2),"utf-8")}async function Rxe(){let e=t$(),t=Jn(),n=new Map;for(let s of t){let i=s.content.toLowerCase().trim();n.has(i)||n.set(i,[]),n.get(i).push(s)}let r=0;for(let s of n.values())if(!(s.length<2)){s.sort((i,o)=>o.importance-i.importance);for(let i of s.slice(1))Nr(i.id)&&r++}return{duplicatesRemoved:r,factsPromoted:e.promoted,factsPruned:e.removed,importanceRecalibrated:t.length}}async function Pxe(e){let t=Jn();if(t.length<5)return{};let n=[],r=0,s=new Map;for(let o of t)s.has(o.category)||s.set(o.category,[]),s.get(o.category).push(o);for(let[o,a]of s){if(a.length<2)continue;let c=Ixe(a);for(let l of c){if(l.length<2)continue;let u=Exe(l),d=l.map(p=>p.id);for(let p of l)Nr(p.id);let f=us(u,{category:o,confidence:Math.max(...l.map(p=>p.confidence)),source:"consolidated",tier:"long_term"});n.push({from:l.map(p=>p.content),to:u,mergedFactId:f.id})}}let i=t.filter(o=>o.contradicts&&o.contradicts.length>0);for(let o of i)if(o.contradicts)for(let a of o.contradicts){let c=t.find(u=>u.id===a);if(!c)continue;let l=new Date(o.createdAt).getTime()>new Date(c.createdAt).getTime();l&&o.confidence>=c.confidence?Nr(c.id)&&r++:!l&&c.confidence>o.confidence&&Nr(o.id)&&r++}return{factsMerged:n,contradictionsResolved:r}}function Ixe(e){let t=[],n=new Set;for(let r of e){if(n.has(r.id))continue;let s=[r];n.add(r.id);for(let i of e){if(n.has(i.id))continue;let o=Mxe(r.tokens,i.tokens);o>.5&&o<.95&&(s.push(i),n.add(i.id))}s.length>1&&t.push(s)}return t}function Mxe(e,t){let n=new Set(e),r=new Set(t),s=new Set([...n].filter(o=>r.has(o))),i=new Set([...n,...r]);return i.size===0?0:s.size/i.size}function Exe(e){e.sort((s,i)=>i.content.length-s.content.length);let t=e[0].content,r=e.slice(1).map(s=>s.content).filter(s=>!t.toLowerCase().includes(s.toLowerCase().slice(0,30)));return r.length===0?t:`${t} (also: ${r.slice(0,2).join("; ")})`}async function Dxe(e){let t=Jn();if(t.length<8)return{};let n=[...t].sort((o,a)=>a.importance-o.importance).slice(0,30),r=[],s=[],i=0;if(Wr.enableInsightGeneration&&i<Wr.maxAICallsPerDream){let o=await Fxe(n,e);r.push(...o),i++;for(let a of o.filter(c=>c.confidence>=.8))us(a.content,{category:a.category,confidence:a.confidence,source:"inferred",tier:"long_term",metadata:{dreamGenerated:!0,basedOn:a.basedOn}})}if(Wr.enablePatternDiscovery&&i<Wr.maxAICallsPerDream){let o=await Lxe(n,e);s.push(...o),i++}return{insightsGenerated:r,patternsDiscovered:s}}async function Fxe(e,t){let r=`Analyze these memory facts and generate 3-5 high-level INSIGHTS that:
1951
1981
  1. Are not directly stated in any single fact
1952
1982
  2. Combine multiple facts to derive a higher-level understanding
1953
1983
  3. Would be useful for the AI in future sessions
@@ -1990,9 +2020,9 @@ Cycle results:
1990
2020
 
1991
2021
  Insights: ${e.insightsGenerated.slice(0,3).map(s=>s.content).join("; ")}
1992
2022
 
1993
- Write in first person, as if the AI is reflecting on its own consolidation. Be concise.`;try{return(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are an AI reflecting on memory consolidation. Be concise and insightful.",[],void 0)).content.trim().slice(0,400)}catch{return""}}async function Jq(e={}){if(Ag)throw new Error("Dream cycle already in progress");Ag=!0;let t=`dream_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,n=Date.now(),r=Jn().length,s=[],i={duplicatesRemoved:0,factsPruned:0,factsPromoted:0,factsMerged:[],insightsGenerated:[],patternsDiscovered:[],contradictionsResolved:0,importanceRecalibrated:0},o=0;try{let l=await Rxe();if(i={...i,...l},s.push("light_sleep"),r>=Wr.minFactsForDream){let u=await Pxe(e.provider);i={...i,...u},s.push("deep_sleep")}if(!e.skipREM&&e.provider&&r>=8){let u=await Dxe(e.provider);i.insightsGenerated=u.insightsGenerated||[],i.patternsDiscovered=u.patternsDiscovered||[],o+=(u.insightsGenerated?.length?1:0)+(u.patternsDiscovered?.length?1:0),s.push("rem"),Wr.enableNarrativeSynthesis&&e.provider&&(i.insightsGenerated.length>0||i.patternsDiscovered.length>0)&&(i.narrative=await Oxe(i,e.provider),o++)}}finally{Ag=!1}let a=Jn().length,c={id:t,startedAt:new Date(n).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-n,triggeredBy:e.triggeredBy||"manual",phasesRun:s,results:i,metadata:{factsAtStart:r,factsAtEnd:a,aiCallsMade:o}};return Rr.push(c),_xe(),K1(),Vq(V1,JSON.stringify(c,null,2),"utf-8"),c}function jxe(){P0=Date.now()}async function Wq(e){if(Date.now()-P0<Wr.idleThresholdMs||Ag)return null;let n=Rr[Rr.length-1];return n&&Date.now()-new Date(n.startedAt).getTime()<1800*1e3?null:Jq({provider:e,triggeredBy:"idle"})}function Bxe(e,t=1800*1e3){al&&clearInterval(al),al=setInterval(()=>{Wq(e).catch(()=>{})},t),al.unref()}function Nxe(){al&&(clearInterval(al),al=null)}function qxe(e=10){return Rr.slice(-e).reverse()}function Uxe(){if(!zq(V1))return null;try{return JSON.parse(Gq(V1,"utf-8"))}catch{return null}}function Hxe(){let e=Rr.length,t=Rr.reduce((o,a)=>o+a.durationMs,0),n=Rr.reduce((o,a)=>o+a.results.duplicatesRemoved+a.results.factsPruned+a.results.factsMerged.length+a.results.contradictionsResolved,0),r=Rr.reduce((o,a)=>o+a.results.insightsGenerated.length,0),s=Rr.reduce((o,a)=>o+a.results.patternsDiscovered.length,0),i=Rr[Rr.length-1];return{totalCycles:e,avgDurationMs:e>0?Math.round(t/e):0,totalFactsConsolidated:n,totalInsightsGenerated:r,totalPatternsDiscovered:s,isCurrentlyDreaming:Ag,lastDreamAt:i?.completedAt,nextScheduledIdleDream:P0+Wr.idleThresholdMs>Date.now()?new Date(P0+Wr.idleThresholdMs).toISOString():void 0}}function zxe(e){Wr={...Wr,...e}}function Gxe(){return{...Wr}}function Vxe(e){let t=[];if(t.push(`# \u{1F319} Dream Cycle ${e.id.slice(-8)}`),t.push(""),t.push(`**Triggered by:** ${e.triggeredBy} | **Duration:** ${(e.durationMs/1e3).toFixed(1)}s`),t.push(`**Phases:** ${e.phasesRun.join(" \u2192 ")}`),t.push(`**Memories:** ${e.metadata.factsAtStart} \u2192 ${e.metadata.factsAtEnd}`),t.push(""),e.results.narrative&&(t.push("## Reflection"),t.push(`*${e.results.narrative}*`),t.push("")),t.push("## Consolidation Results"),t.push(`- \u{1F5D1} Duplicates removed: ${e.results.duplicatesRemoved}`),t.push(`- \u2B06 Promoted to long-term: ${e.results.factsPromoted}`),t.push(`- \u2702 Pruned: ${e.results.factsPruned}`),t.push(`- \u{1F517} Merged groups: ${e.results.factsMerged.length}`),t.push(`- \u2696 Contradictions resolved: ${e.results.contradictionsResolved}`),t.push(""),e.results.insightsGenerated.length>0){t.push("## \u2728 New Insights");for(let n of e.results.insightsGenerated)t.push(`- **[${n.category}]** ${n.content} *(confidence: ${(n.confidence*100).toFixed(0)}%)*`);t.push("")}if(e.results.patternsDiscovered.length>0){t.push("## \u{1F50D} Patterns Discovered");for(let n of e.results.patternsDiscovered)t.push(`- **${n.type}**: ${n.description} (${n.occurrences} occurrences)`)}return t.join(`
1994
- `)}function Jxe(e){let t=e.results;return`\u{1F319} Dream cycle: ${t.duplicatesRemoved+t.factsPromoted+t.factsPruned+t.factsMerged.length+t.contradictionsResolved} memory operations, ${t.insightsGenerated.length} insights, ${t.patternsDiscovered.length} patterns (${(e.durationMs/1e3).toFixed(1)}s)`}var Axe,Wr,W1,G1,V1,Ag,Rr,P0,al,M0=w(()=>{"use strict";xu();Axe={idleThresholdMs:600*1e3,minFactsForDream:5,maxAICallsPerDream:3,enableInsightGeneration:!0,enablePatternDiscovery:!0,enableNarrativeSynthesis:!0},Wr={...Axe},W1=J1(Cxe(),".aiaca","dreams"),G1=J1(W1,"history.json"),V1=J1(W1,"last.json");Ag=!1,Rr=[];Txe();P0=Date.now(),al=null});var sU={};$(sU,{buildTimeline:()=>Zq,classifyOutcome:()=>Qq,compactToolUse:()=>Zxe,detectBottlenecks:()=>Yq,detectPatterns:()=>Kq,extractInvocations:()=>E0,formatAsBullets:()=>tU,formatAsMarkdown:()=>eU,formatAsNarrative:()=>nU,formatAsStructured:()=>rU,summarizeHeuristic:()=>Kd,summarizeToolUse:()=>Xxe,summarizeWithAI:()=>Xq});function E0(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!(r.role!=="assistant"||!r.toolCalls))for(let s of r.toolCalls){let i=e[n+1],o,a=!0,c;if(i&&i.role==="user"){let l=new RegExp(`<tool_result name="${s.name}"(?:\\s+error="(true|false)")?>([\\s\\S]*?)</tool_result>`,"i"),u=i.content.match(l);u&&(a=u[1]!=="true",o=u[2].trim(),(!a||/^Error:|Exit code: [1-9]/.test(o))&&(a=!1,c=o.split(`
1995
- `)[0]))}t.push({name:s.name,input:s.input,output:o,success:a,errorMessage:c,timestamp:r.timestamp,turnIndex:n})}}return t}function Kq(e){let t=[],n=e.map(u=>u.name),r=e.filter(u=>["file_read","grep","glob"].includes(u.name)).length,s=e.filter(u=>["file_write","file_edit"].includes(u.name)).length;r>=3&&s===0&&t.push({type:"investigation",description:`Exploring code (${r} reads/searches with no modifications)`,confidence:Math.min(1,r/5),toolSequence:n.filter(u=>["file_read","grep","glob"].includes(u))});let i=["file_read","file_edit","bash"],o=0;for(let u=0;u<=n.length-3;u++)i.every(d=>n.slice(u,u+3).includes(d))&&o++;o>=2&&t.push({type:"iteration",description:`Iterative development cycle (${o} read-edit-test cycles)`,confidence:Math.min(1,o/3),toolSequence:i});let a=e.filter(u=>!u.success);a.length>=2&&t.push({type:"fix_loop",description:`Debugging session (${a.length} errors encountered)`,confidence:Math.min(1,a.length/3),toolSequence:a.map(u=>u.name)});let c=e.filter(u=>u.name==="bash"&&/\b(test|jest|pytest|vitest|cargo test)\b/.test(String(u.input.command||"")));c.length>=2&&t.push({type:"test_loop",description:`Test-driven cycle (${c.length} test runs)`,confidence:Math.min(1,c.length/3),toolSequence:c.map(u=>u.name)}),n.includes("web_search")&&n.includes("file_write")&&t.push({type:"workflow",description:"Research \u2192 implement workflow",confidence:.8,toolSequence:["web_search","web_fetch","file_write"].filter(u=>n.includes(u))});let l=e.filter(u=>["grep","glob","file_read"].includes(u.name)).length;return l>=5&&s<l/3&&t.push({type:"exploration",description:`Codebase exploration (${l} search/read operations)`,confidence:.85,toolSequence:n.filter(u=>["grep","glob","file_read"].includes(u))}),t}function Yq(e){let t=new Map;for(let n of e){if(!n.durationMs)continue;let r=t.get(n.name)||{total:0,count:0};r.total+=n.durationMs,r.count++,t.set(n.name,r)}return Array.from(t.entries()).map(([n,r])=>({tool:n,totalDurationMs:r.total,callCount:r.count,avgDurationMs:Math.round(r.total/r.count)})).sort((n,r)=>r.totalDurationMs-n.totalDurationMs).slice(0,5)}function Qq(e,t){if(e.length===0)return"unknown";let n=e.filter(o=>!o.success).length/e.length,r=t?.content?.toLowerCase()||"",s=/\b(done|completed|finished|successfully|works|fixed|created)\b/,i=/\b(failed|cannot|unable|error|stuck)\b/;return n>.5?"failure":n>0&&s.test(r)?"partial_success":s.test(r)?"success":i.test(r)?"failure":n===0?"success":"partial_success"}function Zq(e){return e.map(t=>({turnIndex:t.turnIndex,tool:t.name,action:Wxe(t),result:t.success?"success":"failure",durationMs:t.durationMs}))}function Wxe(e){let t=e.input;switch(e.name){case"bash":case"powershell":return`$ ${String(t.command||"").slice(0,60)}`;case"file_read":return`read ${t.path}`;case"file_write":return`wrote ${t.path}`;case"file_edit":return`edited ${t.path}`;case"grep":return`grep "${t.pattern}"`;case"glob":return`glob "${t.pattern}"`;case"web_search":return`searched: ${t.query}`;case"web_fetch":return`fetched ${t.url}`;case"doc_create":return`created doc ${t.path}`;case"image_read":return`analyzed image ${t.path}`;default:return`${e.name}(${JSON.stringify(t).slice(0,40)})`}}function Kd(e,t="turn"){let n=[...new Set(e.filter(g=>g.name==="file_read").map(g=>String(g.input.path)))].filter(Boolean),r=[...new Set(e.filter(g=>g.name==="file_edit").map(g=>String(g.input.path)))].filter(Boolean),s=[...new Set(e.filter(g=>g.name==="file_write"||g.name==="doc_create").map(g=>String(g.input.path)))].filter(Boolean),i=e.filter(g=>g.name==="bash"||g.name==="powershell").map(g=>String(g.input.command||"")),o=e.filter(g=>g.name==="web_fetch").map(g=>String(g.input.url||"")),a=e.filter(g=>!g.success),c=new Map;for(let g of a){let h=`${g.name}:${g.errorMessage||"unknown"}`;c.has(h)?c.get(h).attemptCount++:c.set(h,{tool:g.name,message:g.errorMessage||"Unknown error",recovered:!1,attemptCount:1})}let l=Kq(e),u=Zq(e),d=Yq(e),f=e.reduce((g,h)=>g+(h.durationMs||0),0),p=[];s.length&&p.push(`Created ${s.length} file(s): ${s.slice(0,3).join(", ")}${s.length>3?"...":""}`),r.length&&p.push(`Modified ${r.length} file(s): ${r.slice(0,3).join(", ")}${r.length>3?"...":""}`),n.length&&p.push(`Read ${n.length} file(s)`),i.length&&p.push(`Ran ${i.length} command(s)`),o.length&&p.push(`Visited ${o.length} URL(s)`),a.length&&p.push(`Encountered ${a.length} error(s)`);for(let g of l)p.push(`Pattern: ${g.description}`);let m=Kxe({filesCreated:s,filesWritten:r,filesRead:n,commandsRun:i,errors:a,patterns:l});return{level:t,outcome:Qq(e),totalCalls:e.length,successfulCalls:e.filter(g=>g.success).length,failedCalls:a.length,uniqueTools:[...new Set(e.map(g=>g.name))],filesRead:n,filesModified:r,filesCreated:s,commandsRun:i,websVisited:o,errorsEncountered:Array.from(c.values()),patterns:l,timeline:u,totalDurationMs:f,bottlenecks:d,narrative:m,bulletPoints:p,metadata:{messagesAnalyzed:e.length,confidenceScore:e.length>0?.9:.5}}}function Kxe(e){let t=[];return e.patterns.length>0&&t.push(`This was a ${e.patterns[0].type.replace("_"," ")} session.`),e.filesCreated.length>0&&t.push(`Created ${e.filesCreated.length} file${e.filesCreated.length>1?"s":""} (${e.filesCreated.slice(0,2).map(n=>n.split("/").pop()).join(", ")}${e.filesCreated.length>2?`, +${e.filesCreated.length-2} more`:""}).`),e.filesWritten.length>0&&t.push(`Modified ${e.filesWritten.length} file${e.filesWritten.length>1?"s":""}.`),e.commandsRun.length>0&&t.push(`Executed ${e.commandsRun.length} shell command${e.commandsRun.length>1?"s":""}.`),e.errors.length>0&&t.push(`Hit ${e.errors.length} error${e.errors.length>1?"s":""} during execution.`),t.join(" ")||"No significant tool activity."}async function Xq(e,t,n,r={}){let s=Kd(e,r.level||"turn");if(e.length===0)return s;let i=e.slice(-30).map((c,l)=>`${l+1}. ${c.name}(${Yxe(c.input)}) \u2192 ${c.success?"OK":"FAIL: "+c.errorMessage}`).join(`
2023
+ Write in first person, as if the AI is reflecting on its own consolidation. Be concise.`;try{return(await t.sendMessage([{role:"user",content:r,timestamp:new Date().toISOString()}],"You are an AI reflecting on memory consolidation. Be concise and insightful.",[],void 0)).content.trim().slice(0,400)}catch{return""}}async function J5(e={}){if(Ag)throw new Error("Dream cycle already in progress");Ag=!0;let t=`dream_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,n=Date.now(),r=Jn().length,s=[],i={duplicatesRemoved:0,factsPruned:0,factsPromoted:0,factsMerged:[],insightsGenerated:[],patternsDiscovered:[],contradictionsResolved:0,importanceRecalibrated:0},o=0;try{let l=await Rxe();if(i={...i,...l},s.push("light_sleep"),r>=Wr.minFactsForDream){let u=await Pxe(e.provider);i={...i,...u},s.push("deep_sleep")}if(!e.skipREM&&e.provider&&r>=8){let u=await Dxe(e.provider);i.insightsGenerated=u.insightsGenerated||[],i.patternsDiscovered=u.patternsDiscovered||[],o+=(u.insightsGenerated?.length?1:0)+(u.patternsDiscovered?.length?1:0),s.push("rem"),Wr.enableNarrativeSynthesis&&e.provider&&(i.insightsGenerated.length>0||i.patternsDiscovered.length>0)&&(i.narrative=await Oxe(i,e.provider),o++)}}finally{Ag=!1}let a=Jn().length,c={id:t,startedAt:new Date(n).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-n,triggeredBy:e.triggeredBy||"manual",phasesRun:s,results:i,metadata:{factsAtStart:r,factsAtEnd:a,aiCallsMade:o}};return Rr.push(c),_xe(),K1(),V5(V1,JSON.stringify(c,null,2),"utf-8"),c}function jxe(){P0=Date.now()}async function W5(e){if(Date.now()-P0<Wr.idleThresholdMs||Ag)return null;let n=Rr[Rr.length-1];return n&&Date.now()-new Date(n.startedAt).getTime()<1800*1e3?null:J5({provider:e,triggeredBy:"idle"})}function Bxe(e,t=1800*1e3){al&&clearInterval(al),al=setInterval(()=>{W5(e).catch(()=>{})},t),al.unref()}function Nxe(){al&&(clearInterval(al),al=null)}function qxe(e=10){return Rr.slice(-e).reverse()}function Uxe(){if(!z5(V1))return null;try{return JSON.parse(G5(V1,"utf-8"))}catch{return null}}function Hxe(){let e=Rr.length,t=Rr.reduce((o,a)=>o+a.durationMs,0),n=Rr.reduce((o,a)=>o+a.results.duplicatesRemoved+a.results.factsPruned+a.results.factsMerged.length+a.results.contradictionsResolved,0),r=Rr.reduce((o,a)=>o+a.results.insightsGenerated.length,0),s=Rr.reduce((o,a)=>o+a.results.patternsDiscovered.length,0),i=Rr[Rr.length-1];return{totalCycles:e,avgDurationMs:e>0?Math.round(t/e):0,totalFactsConsolidated:n,totalInsightsGenerated:r,totalPatternsDiscovered:s,isCurrentlyDreaming:Ag,lastDreamAt:i?.completedAt,nextScheduledIdleDream:P0+Wr.idleThresholdMs>Date.now()?new Date(P0+Wr.idleThresholdMs).toISOString():void 0}}function zxe(e){Wr={...Wr,...e}}function Gxe(){return{...Wr}}function Vxe(e){let t=[];if(t.push(`# \u{1F319} Dream Cycle ${e.id.slice(-8)}`),t.push(""),t.push(`**Triggered by:** ${e.triggeredBy} | **Duration:** ${(e.durationMs/1e3).toFixed(1)}s`),t.push(`**Phases:** ${e.phasesRun.join(" \u2192 ")}`),t.push(`**Memories:** ${e.metadata.factsAtStart} \u2192 ${e.metadata.factsAtEnd}`),t.push(""),e.results.narrative&&(t.push("## Reflection"),t.push(`*${e.results.narrative}*`),t.push("")),t.push("## Consolidation Results"),t.push(`- \u{1F5D1} Duplicates removed: ${e.results.duplicatesRemoved}`),t.push(`- \u2B06 Promoted to long-term: ${e.results.factsPromoted}`),t.push(`- \u2702 Pruned: ${e.results.factsPruned}`),t.push(`- \u{1F517} Merged groups: ${e.results.factsMerged.length}`),t.push(`- \u2696 Contradictions resolved: ${e.results.contradictionsResolved}`),t.push(""),e.results.insightsGenerated.length>0){t.push("## \u2728 New Insights");for(let n of e.results.insightsGenerated)t.push(`- **[${n.category}]** ${n.content} *(confidence: ${(n.confidence*100).toFixed(0)}%)*`);t.push("")}if(e.results.patternsDiscovered.length>0){t.push("## \u{1F50D} Patterns Discovered");for(let n of e.results.patternsDiscovered)t.push(`- **${n.type}**: ${n.description} (${n.occurrences} occurrences)`)}return t.join(`
2024
+ `)}function Jxe(e){let t=e.results;return`\u{1F319} Dream cycle: ${t.duplicatesRemoved+t.factsPromoted+t.factsPruned+t.factsMerged.length+t.contradictionsResolved} memory operations, ${t.insightsGenerated.length} insights, ${t.patternsDiscovered.length} patterns (${(e.durationMs/1e3).toFixed(1)}s)`}var Axe,Wr,W1,G1,V1,Ag,Rr,P0,al,M0=w(()=>{"use strict";xu();Axe={idleThresholdMs:600*1e3,minFactsForDream:5,maxAICallsPerDream:3,enableInsightGeneration:!0,enablePatternDiscovery:!0,enableNarrativeSynthesis:!0},Wr={...Axe},W1=J1(Cxe(),".aiaca","dreams"),G1=J1(W1,"history.json"),V1=J1(W1,"last.json");Ag=!1,Rr=[];Txe();P0=Date.now(),al=null});var sU={};$(sU,{buildTimeline:()=>Z5,classifyOutcome:()=>Q5,compactToolUse:()=>Zxe,detectBottlenecks:()=>Y5,detectPatterns:()=>K5,extractInvocations:()=>E0,formatAsBullets:()=>tU,formatAsMarkdown:()=>eU,formatAsNarrative:()=>nU,formatAsStructured:()=>rU,summarizeHeuristic:()=>Kd,summarizeToolUse:()=>Xxe,summarizeWithAI:()=>X5});function E0(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!(r.role!=="assistant"||!r.toolCalls))for(let s of r.toolCalls){let i=e[n+1],o,a=!0,c;if(i&&i.role==="user"){let l=new RegExp(`<tool_result name="${s.name}"(?:\\s+error="(true|false)")?>([\\s\\S]*?)</tool_result>`,"i"),u=i.content.match(l);u&&(a=u[1]!=="true",o=u[2].trim(),(!a||/^Error:|Exit code: [1-9]/.test(o))&&(a=!1,c=o.split(`
2025
+ `)[0]))}t.push({name:s.name,input:s.input,output:o,success:a,errorMessage:c,timestamp:r.timestamp,turnIndex:n})}}return t}function K5(e){let t=[],n=e.map(u=>u.name),r=e.filter(u=>["file_read","grep","glob"].includes(u.name)).length,s=e.filter(u=>["file_write","file_edit"].includes(u.name)).length;r>=3&&s===0&&t.push({type:"investigation",description:`Exploring code (${r} reads/searches with no modifications)`,confidence:Math.min(1,r/5),toolSequence:n.filter(u=>["file_read","grep","glob"].includes(u))});let i=["file_read","file_edit","bash"],o=0;for(let u=0;u<=n.length-3;u++)i.every(d=>n.slice(u,u+3).includes(d))&&o++;o>=2&&t.push({type:"iteration",description:`Iterative development cycle (${o} read-edit-test cycles)`,confidence:Math.min(1,o/3),toolSequence:i});let a=e.filter(u=>!u.success);a.length>=2&&t.push({type:"fix_loop",description:`Debugging session (${a.length} errors encountered)`,confidence:Math.min(1,a.length/3),toolSequence:a.map(u=>u.name)});let c=e.filter(u=>u.name==="bash"&&/\b(test|jest|pytest|vitest|cargo test)\b/.test(String(u.input.command||"")));c.length>=2&&t.push({type:"test_loop",description:`Test-driven cycle (${c.length} test runs)`,confidence:Math.min(1,c.length/3),toolSequence:c.map(u=>u.name)}),n.includes("web_search")&&n.includes("file_write")&&t.push({type:"workflow",description:"Research \u2192 implement workflow",confidence:.8,toolSequence:["web_search","web_fetch","file_write"].filter(u=>n.includes(u))});let l=e.filter(u=>["grep","glob","file_read"].includes(u.name)).length;return l>=5&&s<l/3&&t.push({type:"exploration",description:`Codebase exploration (${l} search/read operations)`,confidence:.85,toolSequence:n.filter(u=>["grep","glob","file_read"].includes(u))}),t}function Y5(e){let t=new Map;for(let n of e){if(!n.durationMs)continue;let r=t.get(n.name)||{total:0,count:0};r.total+=n.durationMs,r.count++,t.set(n.name,r)}return Array.from(t.entries()).map(([n,r])=>({tool:n,totalDurationMs:r.total,callCount:r.count,avgDurationMs:Math.round(r.total/r.count)})).sort((n,r)=>r.totalDurationMs-n.totalDurationMs).slice(0,5)}function Q5(e,t){if(e.length===0)return"unknown";let n=e.filter(o=>!o.success).length/e.length,r=t?.content?.toLowerCase()||"",s=/\b(done|completed|finished|successfully|works|fixed|created)\b/,i=/\b(failed|cannot|unable|error|stuck)\b/;return n>.5?"failure":n>0&&s.test(r)?"partial_success":s.test(r)?"success":i.test(r)?"failure":n===0?"success":"partial_success"}function Z5(e){return e.map(t=>({turnIndex:t.turnIndex,tool:t.name,action:Wxe(t),result:t.success?"success":"failure",durationMs:t.durationMs}))}function Wxe(e){let t=e.input;switch(e.name){case"bash":case"powershell":return`$ ${String(t.command||"").slice(0,60)}`;case"file_read":return`read ${t.path}`;case"file_write":return`wrote ${t.path}`;case"file_edit":return`edited ${t.path}`;case"grep":return`grep "${t.pattern}"`;case"glob":return`glob "${t.pattern}"`;case"web_search":return`searched: ${t.query}`;case"web_fetch":return`fetched ${t.url}`;case"doc_create":return`created doc ${t.path}`;case"image_read":return`analyzed image ${t.path}`;default:return`${e.name}(${JSON.stringify(t).slice(0,40)})`}}function Kd(e,t="turn"){let n=[...new Set(e.filter(g=>g.name==="file_read").map(g=>String(g.input.path)))].filter(Boolean),r=[...new Set(e.filter(g=>g.name==="file_edit").map(g=>String(g.input.path)))].filter(Boolean),s=[...new Set(e.filter(g=>g.name==="file_write"||g.name==="doc_create").map(g=>String(g.input.path)))].filter(Boolean),i=e.filter(g=>g.name==="bash"||g.name==="powershell").map(g=>String(g.input.command||"")),o=e.filter(g=>g.name==="web_fetch").map(g=>String(g.input.url||"")),a=e.filter(g=>!g.success),c=new Map;for(let g of a){let h=`${g.name}:${g.errorMessage||"unknown"}`;c.has(h)?c.get(h).attemptCount++:c.set(h,{tool:g.name,message:g.errorMessage||"Unknown error",recovered:!1,attemptCount:1})}let l=K5(e),u=Z5(e),d=Y5(e),f=e.reduce((g,h)=>g+(h.durationMs||0),0),p=[];s.length&&p.push(`Created ${s.length} file(s): ${s.slice(0,3).join(", ")}${s.length>3?"...":""}`),r.length&&p.push(`Modified ${r.length} file(s): ${r.slice(0,3).join(", ")}${r.length>3?"...":""}`),n.length&&p.push(`Read ${n.length} file(s)`),i.length&&p.push(`Ran ${i.length} command(s)`),o.length&&p.push(`Visited ${o.length} URL(s)`),a.length&&p.push(`Encountered ${a.length} error(s)`);for(let g of l)p.push(`Pattern: ${g.description}`);let m=Kxe({filesCreated:s,filesWritten:r,filesRead:n,commandsRun:i,errors:a,patterns:l});return{level:t,outcome:Q5(e),totalCalls:e.length,successfulCalls:e.filter(g=>g.success).length,failedCalls:a.length,uniqueTools:[...new Set(e.map(g=>g.name))],filesRead:n,filesModified:r,filesCreated:s,commandsRun:i,websVisited:o,errorsEncountered:Array.from(c.values()),patterns:l,timeline:u,totalDurationMs:f,bottlenecks:d,narrative:m,bulletPoints:p,metadata:{messagesAnalyzed:e.length,confidenceScore:e.length>0?.9:.5}}}function Kxe(e){let t=[];return e.patterns.length>0&&t.push(`This was a ${e.patterns[0].type.replace("_"," ")} session.`),e.filesCreated.length>0&&t.push(`Created ${e.filesCreated.length} file${e.filesCreated.length>1?"s":""} (${e.filesCreated.slice(0,2).map(n=>n.split("/").pop()).join(", ")}${e.filesCreated.length>2?`, +${e.filesCreated.length-2} more`:""}).`),e.filesWritten.length>0&&t.push(`Modified ${e.filesWritten.length} file${e.filesWritten.length>1?"s":""}.`),e.commandsRun.length>0&&t.push(`Executed ${e.commandsRun.length} shell command${e.commandsRun.length>1?"s":""}.`),e.errors.length>0&&t.push(`Hit ${e.errors.length} error${e.errors.length>1?"s":""} during execution.`),t.join(" ")||"No significant tool activity."}async function X5(e,t,n,r={}){let s=Kd(e,r.level||"turn");if(e.length===0)return s;let i=e.slice(-30).map((c,l)=>`${l+1}. ${c.name}(${Yxe(c.input)}) \u2192 ${c.success?"OK":"FAIL: "+c.errorMessage}`).join(`
1996
2026
  `),a=`Analyze this tool execution sequence and produce a high-quality summary.
1997
2027
 
1998
2028
  USER'S ORIGINAL TASK: ${t.find(c=>c.role==="user"&&!c.content.startsWith("<tool_result"))?.content?.slice(0,300)||"Unknown task"}
@@ -2016,7 +2046,7 @@ Write a 2-3 sentence narrative summary that:
2016
2046
 
2017
2047
  Return ONLY the narrative paragraph. No preamble, no markdown, no bullet points.`;try{let l=(await n.sendMessage([{role:"user",content:a,timestamp:new Date().toISOString()}],"You are a precise technical summarizer. Output a single paragraph.",[],void 0)).content.trim().slice(0,1e3);return{...s,narrative:l,metadata:{...s.metadata,confidenceScore:.95}}}catch{return s}}function Yxe(e){return Object.keys(e).slice(0,2).map(n=>{let r=String(e[n]||"").slice(0,40);return`${n}: ${r}`}).join(", ")}function eU(e){let t=["## Tool Use Summary",""];if(t.push(`**Outcome:** ${Qxe(e.outcome)}`),t.push(`**Calls:** ${e.totalCalls} (${e.successfulCalls} \u2713, ${e.failedCalls} \u2717)`),t.push(`**Tools used:** ${e.uniqueTools.join(", ")}`),e.totalDurationMs>0&&t.push(`**Total time:** ${(e.totalDurationMs/1e3).toFixed(1)}s`),t.push(""),t.push("### Narrative"),t.push(e.narrative),t.push(""),(e.filesCreated.length||e.filesModified.length||e.filesRead.length)&&(t.push("### Files"),e.filesCreated.length&&t.push(`- **Created:** ${e.filesCreated.join(", ")}`),e.filesModified.length&&t.push(`- **Modified:** ${e.filesModified.join(", ")}`),e.filesRead.length&&t.push(`- **Read:** ${e.filesRead.slice(0,5).join(", ")}${e.filesRead.length>5?`... +${e.filesRead.length-5}`:""}`),t.push("")),e.commandsRun.length){t.push("### Commands");for(let n of e.commandsRun.slice(0,5))t.push(`- \`${n}\``);t.push("")}if(e.errorsEncountered.length){t.push("### Errors");for(let n of e.errorsEncountered)t.push(`- **${n.tool}**: ${n.message}${n.attemptCount>1?` (${n.attemptCount} attempts)`:""}`);t.push("")}if(e.patterns.length){t.push("### Patterns Detected");for(let n of e.patterns)t.push(`- **${n.type}**: ${n.description} (${Math.round(n.confidence*100)}% confidence)`);t.push("")}if(e.bottlenecks.length&&e.bottlenecks[0].totalDurationMs>1e3){t.push("### Performance");for(let n of e.bottlenecks.slice(0,3))t.push(`- **${n.tool}**: ${n.callCount} calls, ${(n.totalDurationMs/1e3).toFixed(1)}s total (avg ${n.avgDurationMs}ms)`)}return t.join(`
2018
2048
  `)}function tU(e){return e.bulletPoints.map(t=>`\u2022 ${t}`).join(`
2019
- `)}function nU(e){return e.narrative}function rU(e){return JSON.stringify({outcome:e.outcome,totalCalls:e.totalCalls,successfulCalls:e.successfulCalls,failedCalls:e.failedCalls,files:{created:e.filesCreated,modified:e.filesModified,read:e.filesRead.slice(0,10)},commands:e.commandsRun.slice(0,10),errors:e.errorsEncountered,patterns:e.patterns.map(t=>({type:t.type,confidence:t.confidence})),durationMs:e.totalDurationMs},null,2)}function Qxe(e){return{success:"\u2705 Success",partial_success:"\u26A0\uFE0F Partial",failure:"\u274C Failed",in_progress:"\u{1F504} In progress",unknown:"\u2754 Unknown"}[e]}function Zxe(e){let t=Kd(e),n=[];return t.filesCreated.length&&n.push(`created ${t.filesCreated.length} file(s)`),t.filesModified.length&&n.push(`modified ${t.filesModified.length} file(s)`),t.commandsRun.length&&n.push(`ran ${t.commandsRun.length} command(s)`),t.failedCalls>0&&n.push(`${t.failedCalls} error(s)`),`[Tool summary: ${n.join(", ")||"no significant activity"}]`}async function Xxe(e,t={}){let n=E0(e),r=t.useAI&&t.provider?await Xq(n,e,t.provider,t):Kd(n,t.level||"turn"),s;switch(t.format){case"narrative":s=nU(r);break;case"bulleted":s=tU(r);break;case"structured":s=rU(r);break;default:s=eU(r)}return{summary:r,formatted:s}}var Y1=w(()=>{"use strict"});var gU={};$(gU,{analyzeFailures:()=>dU,assessGoalAchievement:()=>aU,compareAgents:()=>f$e,extractDecisions:()=>lU,extractDeliverables:()=>cU,extractReasoning:()=>uU,formatAsMarkdown:()=>p$e,formatBrief:()=>m$e,generateHandoffNotes:()=>fU,generateVerificationSuggestions:()=>pU,inferAgentRole:()=>oU,loadAgentSummary:()=>a$e,saveAgentSummary:()=>o$e,summarizeAgentHeuristic:()=>mU,summarizeAgentWithAI:()=>d$e});import{existsSync as e$e,mkdirSync as t$e,readFileSync as n$e,writeFileSync as r$e}from"fs";import{join as Q1}from"path";import{homedir as s$e}from"os";function i$e(){t$e(Z1,{recursive:!0})}function o$e(e){i$e();let t=Q1(Z1,`${e.agentId}.json`);return r$e(t,JSON.stringify(e,null,2),"utf-8"),t}function a$e(e){let t=Q1(Z1,`${e}.json`);if(!e$e(t))return null;try{return JSON.parse(n$e(t,"utf-8"))}catch{return null}}function oU(e,t){let n=e.toLowerCase(),r=t.map(s=>s.name);return/\b(test|jest|pytest|spec)\b/.test(n)?"tester":/\b(review|audit|critique|analyze)\b/.test(n)?"reviewer":/\b(fix|bug|error|debug)\b/.test(n)?"fixer":/\b(research|find|search|investigate)\b/.test(n)?"researcher":/\b(explore|understand|examine)\b/.test(n)||r.filter(s=>["grep","glob","file_read"].includes(s)).length/Math.max(1,r.length)>.7?"explorer":r.includes("file_write")||r.includes("file_edit")?"implementer":"general"}function aU(e,t,n){let r=[],s=[];/\b(done|completed|finished|successfully|works|ready)\b/i.test(n)&&r.push("Agent reported task completion");let i=t.length===0?0:t.filter(u=>u.success).length/t.length;i>.9&&r.push(`High tool success rate (${Math.round(i*100)}%)`);let o=e.toLowerCase();if(/create|write|make/.test(o)){let u=t.filter(d=>d.name==="file_write"||d.name==="doc_create").filter(d=>d.success).length;u>0?r.push(`Created ${u} file(s)`):s.push("Task asked to create files but none were created")}if(/test/.test(o)){let u=t.filter(d=>d.name==="bash"&&/test/.test(String(d.input.command||""))).filter(d=>d.success).length;u>0&&r.push(`Ran ${u} successful test command(s)`)}if(/fix|bug/.test(o)){let u=t.filter(d=>d.name==="file_edit").filter(d=>d.success).length;u>0&&r.push(`Made ${u} edit(s) to fix the issue`)}/\b(failed|cannot|unable|stuck|gave up)\b/i.test(n)&&s.push("Agent indicated failure"),i<.5&&t.length>2&&s.push(`Low tool success rate (${Math.round(i*100)}%)`);let a=t.filter(u=>!u.success).length;a>=3&&s.push(`${a} tool errors encountered`);let c=r.length/Math.max(1,r.length+s.length),l=c>.6;return{goal:e,achieved:l,partialAchievement:l?void 0:r.length>0?"Some progress made but goal not fully achieved":void 0,evidenceOfSuccess:r,evidenceAgainst:s,confidence:c}}function cU(e){let t=[],n=new Set;for(let r of e){if(!r.success)continue;let s=String(r.input.path||"");if(r.name==="file_write"&&s&&!n.has(s))n.add(s),t.push({type:iU(s),description:`Created ${s}`,path:s,status:"created"});else if(r.name==="file_edit"&&s){let i=t.find(o=>o.path===s);i?i.status="modified":(t.push({type:iU(s),description:`Modified ${s}`,path:s,status:"modified"}),n.add(s))}else r.name==="doc_create"&&s?t.push({type:"doc",description:`Created document ${s}`,path:s,status:"created"}):r.name==="bash"&&/test/.test(String(r.input.command||""))&&t.push({type:"test",description:`Test run: ${String(r.input.command).slice(0,60)}`,status:"verified"})}return t}function iU(e){return/\.(test|spec)\./.test(e)?"test":/\.(md|rst|txt)$/i.test(e)?"doc":/\.(json|yaml|yml|toml|ini|env)$/i.test(e)?"config":"file"}function lU(e){let t=[],n=[/\bI('ll| will| chose to| decided to| went with) ([^.!?]+)[.!?]/gi,/\bUsing ([^.!?]+) (because|since|as) ([^.!?]+)[.!?]/gi,/\bI'?m? ([^.!?]+) (instead of|over|rather than) ([^.!?]+)[.!?]/gi];for(let r of e)if(r.role==="assistant")for(let s of n)for(let i of r.content.matchAll(s)){let o=i[2]||i[1],a=i[3]||"";o&&o.length<200&&t.push({description:o.trim().slice(0,200),rationale:a.trim().slice(0,200)||"No rationale stated",reversibility:c$e(o)})}return t.slice(0,10)}function c$e(e){let t=e.toLowerCase();return/delete|remove|drop|destroy/.test(t)||/install|migrate|upgrade/.test(t)?"difficult":(/edit|modify|update|change/.test(t),"reversible")}function uU(e){let t=[],n=[/\bbecause ([^.!?]+)[.!?]/i,/\bso that ([^.!?]+)[.!?]/i,/\bin order to ([^.!?]+)[.!?]/i,/\bfirst,?\s+([^.!?]+)[.!?]/i,/\bnext,?\s+([^.!?]+)[.!?]/i,/\bThe (issue|problem|root cause) is ([^.!?]+)[.!?]/i];for(let r of e)if(r.role==="assistant")for(let s of n){let i=r.content.match(s);i&&i[1]&&i[1].length<200&&t.push(i[1].trim())}return[...new Set(t)].slice(0,8)}function dU(e){let t=[],n=new Map;for(let r=0;r<e.length;r++){let s=e[r];if(s.success)continue;let i=`${s.name}:${s.errorMessage||"unknown"}`;if(n.has(i))n.get(i).count++;else{let o=!1,a;for(let c=r+1;c<Math.min(e.length,r+4);c++)if(e[c].name===s.name&&e[c].success){o=!0,a=`Retried ${s.name} successfully`;break}n.set(i,{count:1,recovered:o,recoveryAction:a})}}for(let[r,s]of n){let[i,...o]=r.split(":");t.push({point:i,cause:o.join(":")||"Unknown",recovered:s.recovered,recoveryAction:s.recoveryAction})}return t.slice(0,5)}function fU(e){let t=[];if(e.outcome==="failed"&&t.push("\u26A0\uFE0F Task did not complete \u2014 review failures before retrying"),e.outcome==="partial"&&t.push("Task partially complete \u2014 see deliverables for what was finished"),e.deliverables&&e.deliverables.some(n=>n.status==="unverified")){let n=e.deliverables.filter(r=>r.status==="unverified");t.push(`${n.length} deliverable(s) not verified \u2014 recommend testing`)}if(e.failures&&e.failures.some(n=>!n.recovered)){let n=e.failures.filter(r=>!r.recovered);t.push(`Unresolved errors: ${n.map(r=>r.cause.slice(0,50)).join("; ")}`)}return e.commandsRun&&e.commandsRun.some(n=>/install|migrate/.test(n))&&t.push("Environment changes were made (installs/migrations) \u2014 verify state"),e.filesModified&&e.filesModified.length>5&&t.push(`Many files modified (${e.filesModified.length}) \u2014 review diff before committing`),t}function pU(e,t){let n=[],r=e.some(a=>a.status==="created"&&a.type==="file"),s=e.some(a=>a.status==="modified"),i=e.some(a=>a.type==="test"),o=t.some(a=>/\b(test|jest|pytest|vitest)\b/.test(a));return(r||s)&&(!i&&!o&&n.push("Run the test suite to verify changes"),n.push("Review the diff before committing")),r&&n.push("Verify new files have proper imports/exports"),t.some(a=>/install/.test(a))&&n.push("Verify package.json/requirements.txt is updated"),e.some(a=>a.type==="config")&&n.push("Verify config changes work in target environment"),n}function mU(e,t,n,r){let s=E0(r),i=Kd(s),o=oU(n,s),a=[...r].reverse().find(x=>x.role==="assistant"&&x.content.trim())?.content||"",c=aU(n,s,a),l=cU(s),u=lU(r),d=uU(r),f=dU(s),p="unclear";c.achieved&&c.confidence>.7?p="completed":c.achieved?p="partial":f.length>=3?p="failed":l.length>0&&(p="partial");let m=r[0]?.timestamp||new Date().toISOString(),g=r[r.length-1]?.timestamp||new Date().toISOString(),h=new Date(g).getTime()-new Date(m).getTime(),v={outcome:p,deliverables:l,failures:f,commandsRun:i.commandsRun,filesModified:i.filesModified},y=fU(v),b=pU(l,i.commandsRun),k=l$e(o,n,p,l,f),S=u$e(o,n,p,i,l,u,f);return{agentId:e,agentName:t,role:o,task:n,outcome:p,startedAt:m,completedAt:g,durationMs:h,iterations:r.filter(x=>x.role==="assistant").length,toolCallCount:s.length,goalAchievement:c,deliverables:l,decisions:u,reasoning:d,failures:f,handoffNotes:y,filesCreated:i.filesCreated,filesModified:i.filesModified,filesRead:i.filesRead,commandsRun:i.commandsRun,errorsEncountered:i.errorsEncountered.map(x=>x.message),patterns:i.patterns,confidenceScore:.85,verificationSuggestions:b,executiveSummary:k,technicalSummary:S,metadata:{messagesAnalyzed:r.length}}}function l$e(e,t,n,r,s){let i={completed:"completed",partial:"partially completed",failed:"failed",aborted:"was aborted",unclear:"finished unclear"},o=r.filter(l=>l.status==="created").length,a=r.filter(l=>l.status==="modified").length,c=s.length>0?` Hit ${s.length} error(s).`:"";return`${e.charAt(0).toUpperCase()+e.slice(1)} agent ${i[n]} the task${o||a?` \u2014 created ${o}, modified ${a} file(s)`:""}.${c}`}function u$e(e,t,n,r,s,i,o){let a=[];if(a.push(`Acting as a ${e}, the agent ${n==="completed"?"completed":"attempted"} the task: "${t.slice(0,100)}".`),r.totalCalls>0&&a.push(`Used ${r.uniqueTools.length} unique tools across ${r.totalCalls} calls.`),s.length>0&&a.push(`Delivered ${s.length} item(s): ${s.slice(0,3).map(c=>c.description).join("; ")}.`),i.length>0&&a.push(`Made ${i.length} key decision(s).`),o.length>0){let c=o.filter(l=>l.recovered).length;a.push(`Encountered ${o.length} failure(s)${c>0?` (${c} recovered)`:""}.`)}return a.join(" ")}async function d$e(e,t,n,r,s){let i=mU(e,t,n,r);if(r.length<3)return i;let o=r.slice(-15).filter(c=>!c.content.startsWith("<tool_result")).map(c=>`[${c.role}] ${c.content.slice(0,400)}`).join(`
2049
+ `)}function nU(e){return e.narrative}function rU(e){return JSON.stringify({outcome:e.outcome,totalCalls:e.totalCalls,successfulCalls:e.successfulCalls,failedCalls:e.failedCalls,files:{created:e.filesCreated,modified:e.filesModified,read:e.filesRead.slice(0,10)},commands:e.commandsRun.slice(0,10),errors:e.errorsEncountered,patterns:e.patterns.map(t=>({type:t.type,confidence:t.confidence})),durationMs:e.totalDurationMs},null,2)}function Qxe(e){return{success:"\u2705 Success",partial_success:"\u26A0\uFE0F Partial",failure:"\u274C Failed",in_progress:"\u{1F504} In progress",unknown:"\u2754 Unknown"}[e]}function Zxe(e){let t=Kd(e),n=[];return t.filesCreated.length&&n.push(`created ${t.filesCreated.length} file(s)`),t.filesModified.length&&n.push(`modified ${t.filesModified.length} file(s)`),t.commandsRun.length&&n.push(`ran ${t.commandsRun.length} command(s)`),t.failedCalls>0&&n.push(`${t.failedCalls} error(s)`),`[Tool summary: ${n.join(", ")||"no significant activity"}]`}async function Xxe(e,t={}){let n=E0(e),r=t.useAI&&t.provider?await X5(n,e,t.provider,t):Kd(n,t.level||"turn"),s;switch(t.format){case"narrative":s=nU(r);break;case"bulleted":s=tU(r);break;case"structured":s=rU(r);break;default:s=eU(r)}return{summary:r,formatted:s}}var Y1=w(()=>{"use strict"});var gU={};$(gU,{analyzeFailures:()=>dU,assessGoalAchievement:()=>aU,compareAgents:()=>f$e,extractDecisions:()=>lU,extractDeliverables:()=>cU,extractReasoning:()=>uU,formatAsMarkdown:()=>p$e,formatBrief:()=>m$e,generateHandoffNotes:()=>fU,generateVerificationSuggestions:()=>pU,inferAgentRole:()=>oU,loadAgentSummary:()=>a$e,saveAgentSummary:()=>o$e,summarizeAgentHeuristic:()=>mU,summarizeAgentWithAI:()=>d$e});import{existsSync as e$e,mkdirSync as t$e,readFileSync as n$e,writeFileSync as r$e}from"fs";import{join as Q1}from"path";import{homedir as s$e}from"os";function i$e(){t$e(Z1,{recursive:!0})}function o$e(e){i$e();let t=Q1(Z1,`${e.agentId}.json`);return r$e(t,JSON.stringify(e,null,2),"utf-8"),t}function a$e(e){let t=Q1(Z1,`${e}.json`);if(!e$e(t))return null;try{return JSON.parse(n$e(t,"utf-8"))}catch{return null}}function oU(e,t){let n=e.toLowerCase(),r=t.map(s=>s.name);return/\b(test|jest|pytest|spec)\b/.test(n)?"tester":/\b(review|audit|critique|analyze)\b/.test(n)?"reviewer":/\b(fix|bug|error|debug)\b/.test(n)?"fixer":/\b(research|find|search|investigate)\b/.test(n)?"researcher":/\b(explore|understand|examine)\b/.test(n)||r.filter(s=>["grep","glob","file_read"].includes(s)).length/Math.max(1,r.length)>.7?"explorer":r.includes("file_write")||r.includes("file_edit")?"implementer":"general"}function aU(e,t,n){let r=[],s=[];/\b(done|completed|finished|successfully|works|ready)\b/i.test(n)&&r.push("Agent reported task completion");let i=t.length===0?0:t.filter(u=>u.success).length/t.length;i>.9&&r.push(`High tool success rate (${Math.round(i*100)}%)`);let o=e.toLowerCase();if(/create|write|make/.test(o)){let u=t.filter(d=>d.name==="file_write"||d.name==="doc_create").filter(d=>d.success).length;u>0?r.push(`Created ${u} file(s)`):s.push("Task asked to create files but none were created")}if(/test/.test(o)){let u=t.filter(d=>d.name==="bash"&&/test/.test(String(d.input.command||""))).filter(d=>d.success).length;u>0&&r.push(`Ran ${u} successful test command(s)`)}if(/fix|bug/.test(o)){let u=t.filter(d=>d.name==="file_edit").filter(d=>d.success).length;u>0&&r.push(`Made ${u} edit(s) to fix the issue`)}/\b(failed|cannot|unable|stuck|gave up)\b/i.test(n)&&s.push("Agent indicated failure"),i<.5&&t.length>2&&s.push(`Low tool success rate (${Math.round(i*100)}%)`);let a=t.filter(u=>!u.success).length;a>=3&&s.push(`${a} tool errors encountered`);let c=r.length/Math.max(1,r.length+s.length),l=c>.6;return{goal:e,achieved:l,partialAchievement:l?void 0:r.length>0?"Some progress made but goal not fully achieved":void 0,evidenceOfSuccess:r,evidenceAgainst:s,confidence:c}}function cU(e){let t=[],n=new Set;for(let r of e){if(!r.success)continue;let s=String(r.input.path||"");if(r.name==="file_write"&&s&&!n.has(s))n.add(s),t.push({type:iU(s),description:`Created ${s}`,path:s,status:"created"});else if(r.name==="file_edit"&&s){let i=t.find(o=>o.path===s);i?i.status="modified":(t.push({type:iU(s),description:`Modified ${s}`,path:s,status:"modified"}),n.add(s))}else r.name==="doc_create"&&s?t.push({type:"doc",description:`Created document ${s}`,path:s,status:"created"}):r.name==="bash"&&/test/.test(String(r.input.command||""))&&t.push({type:"test",description:`Test run: ${String(r.input.command).slice(0,60)}`,status:"verified"})}return t}function iU(e){return/\.(test|spec)\./.test(e)?"test":/\.(md|rst|txt)$/i.test(e)?"doc":/\.(json|yaml|yml|toml|ini|env)$/i.test(e)?"config":"file"}function lU(e){let t=[],n=[/\bI('ll| will| chose to| decided to| went with) ([^.!?]+)[.!?]/gi,/\bUsing ([^.!?]+) (because|since|as) ([^.!?]+)[.!?]/gi,/\bI'?m? ([^.!?]+) (instead of|over|rather than) ([^.!?]+)[.!?]/gi];for(let r of e)if(r.role==="assistant")for(let s of n)for(let i of r.content.matchAll(s)){let o=i[2]||i[1],a=i[3]||"";o&&o.length<200&&t.push({description:o.trim().slice(0,200),rationale:a.trim().slice(0,200)||"No rationale stated",reversibility:c$e(o)})}return t.slice(0,10)}function c$e(e){let t=e.toLowerCase();return/delete|remove|drop|destroy/.test(t)||/install|migrate|upgrade/.test(t)?"difficult":(/edit|modify|update|change/.test(t),"reversible")}function uU(e){let t=[],n=[/\bbecause ([^.!?]+)[.!?]/i,/\bso that ([^.!?]+)[.!?]/i,/\bin order to ([^.!?]+)[.!?]/i,/\bfirst,?\s+([^.!?]+)[.!?]/i,/\bnext,?\s+([^.!?]+)[.!?]/i,/\bThe (issue|problem|root cause) is ([^.!?]+)[.!?]/i];for(let r of e)if(r.role==="assistant")for(let s of n){let i=r.content.match(s);i&&i[1]&&i[1].length<200&&t.push(i[1].trim())}return[...new Set(t)].slice(0,8)}function dU(e){let t=[],n=new Map;for(let r=0;r<e.length;r++){let s=e[r];if(s.success)continue;let i=`${s.name}:${s.errorMessage||"unknown"}`;if(n.has(i))n.get(i).count++;else{let o=!1,a;for(let c=r+1;c<Math.min(e.length,r+4);c++)if(e[c].name===s.name&&e[c].success){o=!0,a=`Retried ${s.name} successfully`;break}n.set(i,{count:1,recovered:o,recoveryAction:a})}}for(let[r,s]of n){let[i,...o]=r.split(":");t.push({point:i,cause:o.join(":")||"Unknown",recovered:s.recovered,recoveryAction:s.recoveryAction})}return t.slice(0,5)}function fU(e){let t=[];if(e.outcome==="failed"&&t.push("\u26A0\uFE0F Task did not complete \u2014 review failures before retrying"),e.outcome==="partial"&&t.push("Task partially complete \u2014 see deliverables for what was finished"),e.deliverables&&e.deliverables.some(n=>n.status==="unverified")){let n=e.deliverables.filter(r=>r.status==="unverified");t.push(`${n.length} deliverable(s) not verified \u2014 recommend testing`)}if(e.failures&&e.failures.some(n=>!n.recovered)){let n=e.failures.filter(r=>!r.recovered);t.push(`Unresolved errors: ${n.map(r=>r.cause.slice(0,50)).join("; ")}`)}return e.commandsRun&&e.commandsRun.some(n=>/install|migrate/.test(n))&&t.push("Environment changes were made (installs/migrations) \u2014 verify state"),e.filesModified&&e.filesModified.length>5&&t.push(`Many files modified (${e.filesModified.length}) \u2014 review diff before committing`),t}function pU(e,t){let n=[],r=e.some(a=>a.status==="created"&&a.type==="file"),s=e.some(a=>a.status==="modified"),i=e.some(a=>a.type==="test"),o=t.some(a=>/\b(test|jest|pytest|vitest)\b/.test(a));return(r||s)&&(!i&&!o&&n.push("Run the test suite to verify changes"),n.push("Review the diff before committing")),r&&n.push("Verify new files have proper imports/exports"),t.some(a=>/install/.test(a))&&n.push("Verify package.json/requirements.txt is updated"),e.some(a=>a.type==="config")&&n.push("Verify config changes work in target environment"),n}function mU(e,t,n,r){let s=E0(r),i=Kd(s),o=oU(n,s),a=[...r].reverse().find(x=>x.role==="assistant"&&x.content.trim())?.content||"",c=aU(n,s,a),l=cU(s),u=lU(r),d=uU(r),f=dU(s),p="unclear";c.achieved&&c.confidence>.7?p="completed":c.achieved?p="partial":f.length>=3?p="failed":l.length>0&&(p="partial");let m=r[0]?.timestamp||new Date().toISOString(),g=r[r.length-1]?.timestamp||new Date().toISOString(),h=new Date(g).getTime()-new Date(m).getTime(),v={outcome:p,deliverables:l,failures:f,commandsRun:i.commandsRun,filesModified:i.filesModified},y=fU(v),b=pU(l,i.commandsRun),k=l$e(o,n,p,l,f),S=u$e(o,n,p,i,l,u,f);return{agentId:e,agentName:t,role:o,task:n,outcome:p,startedAt:m,completedAt:g,durationMs:h,iterations:r.filter(x=>x.role==="assistant").length,toolCallCount:s.length,goalAchievement:c,deliverables:l,decisions:u,reasoning:d,failures:f,handoffNotes:y,filesCreated:i.filesCreated,filesModified:i.filesModified,filesRead:i.filesRead,commandsRun:i.commandsRun,errorsEncountered:i.errorsEncountered.map(x=>x.message),patterns:i.patterns,confidenceScore:.85,verificationSuggestions:b,executiveSummary:k,technicalSummary:S,metadata:{messagesAnalyzed:r.length}}}function l$e(e,t,n,r,s){let i={completed:"completed",partial:"partially completed",failed:"failed",aborted:"was aborted",unclear:"finished unclear"},o=r.filter(l=>l.status==="created").length,a=r.filter(l=>l.status==="modified").length,c=s.length>0?` Hit ${s.length} error(s).`:"";return`${e.charAt(0).toUpperCase()+e.slice(1)} agent ${i[n]} the task${o||a?` \u2014 created ${o}, modified ${a} file(s)`:""}.${c}`}function u$e(e,t,n,r,s,i,o){let a=[];if(a.push(`Acting as a ${e}, the agent ${n==="completed"?"completed":"attempted"} the task: "${t.slice(0,100)}".`),r.totalCalls>0&&a.push(`Used ${r.uniqueTools.length} unique tools across ${r.totalCalls} calls.`),s.length>0&&a.push(`Delivered ${s.length} item(s): ${s.slice(0,3).map(c=>c.description).join("; ")}.`),i.length>0&&a.push(`Made ${i.length} key decision(s).`),o.length>0){let c=o.filter(l=>l.recovered).length;a.push(`Encountered ${o.length} failure(s)${c>0?` (${c} recovered)`:""}.`)}return a.join(" ")}async function d$e(e,t,n,r,s){let i=mU(e,t,n,r);if(r.length<3)return i;let o=r.slice(-15).filter(c=>!c.content.startsWith("<tool_result")).map(c=>`[${c.role}] ${c.content.slice(0,400)}`).join(`
2020
2050
  `),a=`Analyze this agent's work and produce a deep summary.
2021
2051
 
2022
2052
  ORIGINAL TASK: ${n}
@@ -2066,21 +2096,21 @@ Each suggestion should be:
2066
2096
  `).slice(-e).map(n=>JSON.parse(n))}catch{return[]}}function Y$e(){sP=!0}function Q$e(){sP=!1}function Z$e(e,t,n={}){if(!sP)return null;Xi();let r=`dump_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,s=Pr(j0,`${r}.txt`);try{let i=["=== METADATA ===",JSON.stringify(n,null,2),"","=== SYSTEM PROMPT ===",e,"","=== MESSAGES ===",...t.map((o,a)=>`--- [${a}] ${o.role} ---
2067
2097
  ${o.content}
2068
2098
  `)].join(`
2069
- `);return O0(s,i,"utf-8"),s}catch{return null}}function EU(){return Xi(),B0(j0).filter(e=>e.endsWith(".txt")).map(e=>{try{let t=Pr(j0,e),n=N0(t);return{id:e.replace(".txt",""),path:t,sizeKB:Math.round(n.size/1024),createdAt:n.mtime.toISOString()}}catch{return null}}).filter(Boolean)}function FU(e){let t=Ig.get(e);return t?t.state==="open"&&Date.now()-t.lastFailure>DU?(t.state="half_open",!1):t.state==="open":!1}function LU(e){let t=Ig.get(e);t&&(t.successes++,t.failures=0,t.state==="half_open"&&(t.state="closed"))}function OU(e){let t=Ig.get(e)||{failures:0,successes:0,lastFailure:0,state:"closed"};t.failures++,t.lastFailure=Date.now(),t.failures>=X$e&&(t.state="open"),Ig.set(e,t)}function eCe(){return Object.fromEntries(Ig.entries())}async function tCe(e,t){let{cacheKey:n,cacheTTLMs:r,retryConfig:s,endpoint:i}=t;if(FU(i))throw new Error(`Circuit breaker open for ${i}. Try again in ${Math.round(DU/1e3)}s.`);if(n&&!IU()){let c=RU(n);if(c)return L0({timestamp:new Date().toISOString(),provider:"cache",model:"",type:"cache_hit",cacheKey:n}),c}let o=Date.now(),a=async()=>{try{let c=await _U(e,s);LU(i);let l=Date.now()-o;return L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"response",durationMs:l,inputTokens:c.usage?.inputTokens,outputTokens:c.usage?.outputTokens}),n&&PU(n,c,r),c}catch(c){throw OU(i),L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"error",error:c.message,durationMs:Date.now()-o}),c}};return n?MU(n,a):a()}function nCe(){Xi();let e=Date.now()-1440*60*1e3;for(let n of B0(oi))try{let r=Pr(oi,n);N0(r).mtimeMs<e&&Pg(r)}catch{}let t=EU().sort((n,r)=>r.createdAt.localeCompare(n.createdAt));for(let n of t.slice(50))try{Pg(n.path)}catch{}}var q0,oi,TU,j0,cl,E$e,vs,L$e,O$e,Mg,eP,F0,rP,V$e,sP,Ig,X$e,DU,H0=w(()=>{"use strict";q0=Pr(I$e(),".aiaca","api"),oi=Pr(q0,"cache"),TU=Pr(q0,"logs"),j0=Pr(q0,"dumps"),cl=Pr(TU,"api.log");E$e={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,jitter:!0,retryableStatuses:[408,425,429,500,502,503,504,529],retryableErrors:[/ECONNRESET/i,/ETIMEDOUT/i,/ENETUNREACH/i,/overloaded/i,/timeout/i,/socket hang up/i]};vs=new Map,L$e=100,O$e=300*1e3,Mg=!1;eP=!1;F0=new Map;rP=!1,V$e=10*1024*1024;sP=!1;Ig=new Map,X$e=5,DU=6e4});import{render as qCe}from"ink";import{useState as mt,useCallback as uP,useEffect as lH}from"react";import{Box as tr,Text as dl,useApp as jCe,useStdout as BCe,useInput as uH}from"ink";import{useState as bH,useEffect as vH}from"react";import{Box as to,Text as ir}from"ink";import{jsx as hr,jsxs as $s}from"react/jsx-runtime";var SH=[" \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551"," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"],eS=["#ff6b6b","#ee5a24","#f0932b","#6ab04c","#22a6b3","#7c3aed"];function wH({animated:e=!0,subtitle:t}){let[n,r]=bH(0);return vH(()=>{if(!e)return;let s=setInterval(()=>r(i=>(i+1)%eS.length),400);return()=>clearInterval(s)},[e]),$s(to,{flexDirection:"column",alignItems:"center",marginBottom:1,children:[SH.map((s,i)=>hr(ir,{color:eS[(i+n)%eS.length],children:s},i)),t&&hr(to,{marginTop:1,children:$s(ir,{color:"gray",italic:!0,children:[" ",t]})})]})}function pP({provider:e,model:t,cwd:n,gitBranch:r,version:s="1.0.0"}){return $s(to,{flexDirection:"column",children:[hr(wH,{subtitle:`AI Agentic Coding Assistant v${s}`}),$s(to,{borderStyle:"single",borderColor:"gray",paddingX:2,paddingY:0,flexDirection:"column",children:[$s(to,{gap:1,children:[hr(ir,{color:"gray",children:"Provider:"}),hr(ir,{color:"cyan",bold:!0,children:e}),$s(ir,{color:"gray",children:["(",t,")"]})]}),$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" CWD:"}),hr(ir,{children:n})]}),r&&$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" Git:"}),$s(ir,{color:"green",children:["\u2387 ",r]})]}),$s(to,{gap:1,marginTop:1,children:[hr(ir,{color:"gray",children:"Type your prompt or"}),hr(ir,{color:"yellow",children:"/help"}),hr(ir,{color:"gray",children:"for commands \u2022"}),hr(ir,{color:"yellow",children:"Ctrl+C"}),hr(ir,{color:"gray",children:"to exit"})]})]})]})}import HU,{useState as zU,useEffect as rCe}from"react";import{Box as Ss,Text as Ut,useStdin as sCe,useStdout as iCe}from"ink";tf();Mr();Xg();pS();cf();import{execSync as ia}from"child_process";import{existsSync as jU,writeFileSync as iP}from"fs";import{join as Eg}from"path";var iz={default:{name:"default",colors:{primary:"#7c3aed",secondary:"#06b6d4",success:"#22c55e",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6",muted:"#6b7280",text:"#f9fafb",border:"#374151",prompt:"#7c3aed",toolName:"#06b6d4",toolOutput:"#9ca3af",diffAdded:"#22c55e",diffRemoved:"#ef4444",agent:["#f59e0b","#06b6d4","#8b5cf6","#ec4899"]}},dark:{name:"dark",colors:{primary:"#a78bfa",secondary:"#67e8f9",success:"#4ade80",error:"#f87171",warning:"#fbbf24",info:"#60a5fa",muted:"#9ca3af",text:"#ffffff",border:"#4b5563",prompt:"#a78bfa",toolName:"#67e8f9",toolOutput:"#d1d5db",diffAdded:"#4ade80",diffRemoved:"#f87171",agent:["#fbbf24","#67e8f9","#c084fc","#f472b6"]}},light:{name:"light",colors:{primary:"#6d28d9",secondary:"#0891b2",success:"#16a34a",error:"#dc2626",warning:"#d97706",info:"#2563eb",muted:"#4b5563",text:"#111827",border:"#d1d5db",prompt:"#6d28d9",toolName:"#0891b2",toolOutput:"#6b7280",diffAdded:"#16a34a",diffRemoved:"#dc2626",agent:["#d97706","#0891b2","#7c3aed","#db2777"]}},ocean:{name:"ocean",colors:{primary:"#0ea5e9",secondary:"#14b8a6",success:"#10b981",error:"#f43f5e",warning:"#f59e0b",info:"#06b6d4",muted:"#64748b",text:"#f0f9ff",border:"#1e3a5f",prompt:"#0ea5e9",toolName:"#14b8a6",toolOutput:"#94a3b8",diffAdded:"#10b981",diffRemoved:"#f43f5e",agent:["#f59e0b","#14b8a6","#8b5cf6","#ec4899"]}}};function NP(){return Object.keys(iz)}Ls();mu();import{execSync as kwe}from"child_process";function H5(e){try{let t=kwe("git worktree list --porcelain",{cwd:e,encoding:"utf-8"}),n=[],r={};for(let s of t.split(`
2070
- `))s.startsWith("worktree ")?r={path:s.slice(9)}:s.startsWith("HEAD ")?r.head=s.slice(5):s.startsWith("branch ")?r.branch=s.slice(7).replace("refs/heads/",""):s==="bare"?r.isBare=!0:s===""&&(r.path&&n.push({path:r.path,branch:r.branch||"detached",head:r.head||"",isBare:!!r.isBare,isMain:n.length===0}),r={});return n}catch{return[]}}tA();import{existsSync as gFe,mkdirSync as G5,readdirSync as hFe,readFileSync as yFe,writeFileSync as xwe}from"fs";import{join as S1}from"path";import{homedir as $we}from"os";var z5=S1($we(),".aiaca","plugins"),w1=new Map;function Cwe(){return G5(z5,{recursive:!0}),z5}function V5(){return Array.from(w1.values())}function J5(e,t){let n=S1(Cwe(),e);G5(n,{recursive:!0});let r={name:e,version:"1.0.0",description:`Plugin: ${e}`};return xwe(S1(n,"manifest.json"),JSON.stringify(r,null,2),"utf-8"),`Plugin "${e}" installed at ${n}`}function W5(e){return w1.get(e)?(w1.delete(e),!0):!1}import{execSync as K5}from"child_process";var v0={enabled:!1,recording:!1,lastTranscript:""};function Awe(){try{return process.platform==="win32"?(K5("where whisper",{encoding:"utf-8",timeout:2e3}),!0):(K5("which whisper",{encoding:"utf-8",timeout:2e3}),!0)}catch{return!1}}function Y5(){return Awe()?(v0.enabled=!0,!0):!1}function Q5(){v0.enabled=!1,v0.recording=!1}function Z5(){return{...v0}}import{existsSync as $Fe,mkdirSync as CFe,readFileSync as AFe,writeFileSync as TFe}from"fs";import{join as Twe}from"path";import{homedir as _we}from"os";var IFe=Twe(_we(),".aiaca","recordings");function X5(e,t="markdown"){return t==="json"?JSON.stringify(e,null,2):e.map(n=>{let r=n.role==="user"?"**You**":"**AIACA**",s=n.timestamp.slice(11,19);return`### ${r} (${s})
2099
+ `);return O0(s,i,"utf-8"),s}catch{return null}}function EU(){return Xi(),B0(j0).filter(e=>e.endsWith(".txt")).map(e=>{try{let t=Pr(j0,e),n=N0(t);return{id:e.replace(".txt",""),path:t,sizeKB:Math.round(n.size/1024),createdAt:n.mtime.toISOString()}}catch{return null}}).filter(Boolean)}function FU(e){let t=Ig.get(e);return t?t.state==="open"&&Date.now()-t.lastFailure>DU?(t.state="half_open",!1):t.state==="open":!1}function LU(e){let t=Ig.get(e);t&&(t.successes++,t.failures=0,t.state==="half_open"&&(t.state="closed"))}function OU(e){let t=Ig.get(e)||{failures:0,successes:0,lastFailure:0,state:"closed"};t.failures++,t.lastFailure=Date.now(),t.failures>=X$e&&(t.state="open"),Ig.set(e,t)}function eCe(){return Object.fromEntries(Ig.entries())}async function tCe(e,t){let{cacheKey:n,cacheTTLMs:r,retryConfig:s,endpoint:i}=t;if(FU(i))throw new Error(`Circuit breaker open for ${i}. Try again in ${Math.round(DU/1e3)}s.`);if(n&&!IU()){let c=RU(n);if(c)return L0({timestamp:new Date().toISOString(),provider:"cache",model:"",type:"cache_hit",cacheKey:n}),c}let o=Date.now(),a=async()=>{try{let c=await _U(e,s);LU(i);let l=Date.now()-o;return L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"response",durationMs:l,inputTokens:c.usage?.inputTokens,outputTokens:c.usage?.outputTokens}),n&&PU(n,c,r),c}catch(c){throw OU(i),L0({timestamp:new Date().toISOString(),provider:i,model:"",type:"error",error:c.message,durationMs:Date.now()-o}),c}};return n?MU(n,a):a()}function nCe(){Xi();let e=Date.now()-1440*60*1e3;for(let n of B0(oi))try{let r=Pr(oi,n);N0(r).mtimeMs<e&&Pg(r)}catch{}let t=EU().sort((n,r)=>r.createdAt.localeCompare(n.createdAt));for(let n of t.slice(50))try{Pg(n.path)}catch{}}var q0,oi,TU,j0,cl,E$e,vs,L$e,O$e,Mg,eP,F0,rP,V$e,sP,Ig,X$e,DU,H0=w(()=>{"use strict";q0=Pr(I$e(),".aiaca","api"),oi=Pr(q0,"cache"),TU=Pr(q0,"logs"),j0=Pr(q0,"dumps"),cl=Pr(TU,"api.log");E$e={maxRetries:3,baseDelayMs:1e3,maxDelayMs:6e4,jitter:!0,retryableStatuses:[408,425,429,500,502,503,504,529],retryableErrors:[/ECONNRESET/i,/ETIMEDOUT/i,/ENETUNREACH/i,/overloaded/i,/timeout/i,/socket hang up/i]};vs=new Map,L$e=100,O$e=300*1e3,Mg=!1;eP=!1;F0=new Map;rP=!1,V$e=10*1024*1024;sP=!1;Ig=new Map,X$e=5,DU=6e4});import{render as qCe}from"ink";import{useState as mt,useCallback as uP,useEffect as lH}from"react";import{Box as tr,Text as dl,useApp as jCe,useStdout as BCe,useInput as uH}from"ink";import{useState as bH,useEffect as vH}from"react";import{Box as to,Text as ir}from"ink";import{jsx as hr,jsxs as $s}from"react/jsx-runtime";var SH=[" \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551"," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"],eS=["#ff6b6b","#ee5a24","#f0932b","#6ab04c","#22a6b3","#7c3aed"];function wH({animated:e=!0,subtitle:t}){let[n,r]=bH(0);return vH(()=>{if(!e)return;let s=setInterval(()=>r(i=>(i+1)%eS.length),400);return()=>clearInterval(s)},[e]),$s(to,{flexDirection:"column",alignItems:"center",marginBottom:1,children:[SH.map((s,i)=>hr(ir,{color:eS[(i+n)%eS.length],children:s},i)),t&&hr(to,{marginTop:1,children:$s(ir,{color:"gray",italic:!0,children:[" ",t]})})]})}function pP({provider:e,model:t,cwd:n,gitBranch:r,version:s="1.0.0"}){return $s(to,{flexDirection:"column",children:[hr(wH,{subtitle:`AI Agentic Coding Assistant v${s}`}),$s(to,{borderStyle:"single",borderColor:"gray",paddingX:2,paddingY:0,flexDirection:"column",children:[$s(to,{gap:1,children:[hr(ir,{color:"gray",children:"Provider:"}),hr(ir,{color:"cyan",bold:!0,children:e}),$s(ir,{color:"gray",children:["(",t,")"]})]}),$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" CWD:"}),hr(ir,{children:n})]}),r&&$s(to,{gap:1,children:[hr(ir,{color:"gray",children:" Git:"}),$s(ir,{color:"green",children:["\u2387 ",r]})]}),$s(to,{gap:1,marginTop:1,children:[hr(ir,{color:"gray",children:"Type your prompt or"}),hr(ir,{color:"yellow",children:"/help"}),hr(ir,{color:"gray",children:"for commands \u2022"}),hr(ir,{color:"yellow",children:"Ctrl+C"}),hr(ir,{color:"gray",children:"to exit"})]})]})]})}import HU,{useState as zU,useEffect as rCe}from"react";import{Box as Ss,Text as Ut,useStdin as sCe,useStdout as iCe}from"ink";tf();Mr();Xg();pS();cf();import{execSync as ia}from"child_process";import{existsSync as jU,writeFileSync as iP}from"fs";import{join as Eg}from"path";var iz={default:{name:"default",colors:{primary:"#7c3aed",secondary:"#06b6d4",success:"#22c55e",error:"#ef4444",warning:"#f59e0b",info:"#3b82f6",muted:"#6b7280",text:"#f9fafb",border:"#374151",prompt:"#7c3aed",toolName:"#06b6d4",toolOutput:"#9ca3af",diffAdded:"#22c55e",diffRemoved:"#ef4444",agent:["#f59e0b","#06b6d4","#8b5cf6","#ec4899"]}},dark:{name:"dark",colors:{primary:"#a78bfa",secondary:"#67e8f9",success:"#4ade80",error:"#f87171",warning:"#fbbf24",info:"#60a5fa",muted:"#9ca3af",text:"#ffffff",border:"#4b5563",prompt:"#a78bfa",toolName:"#67e8f9",toolOutput:"#d1d5db",diffAdded:"#4ade80",diffRemoved:"#f87171",agent:["#fbbf24","#67e8f9","#c084fc","#f472b6"]}},light:{name:"light",colors:{primary:"#6d28d9",secondary:"#0891b2",success:"#16a34a",error:"#dc2626",warning:"#d97706",info:"#2563eb",muted:"#4b5563",text:"#111827",border:"#d1d5db",prompt:"#6d28d9",toolName:"#0891b2",toolOutput:"#6b7280",diffAdded:"#16a34a",diffRemoved:"#dc2626",agent:["#d97706","#0891b2","#7c3aed","#db2777"]}},ocean:{name:"ocean",colors:{primary:"#0ea5e9",secondary:"#14b8a6",success:"#10b981",error:"#f43f5e",warning:"#f59e0b",info:"#06b6d4",muted:"#64748b",text:"#f0f9ff",border:"#1e3a5f",prompt:"#0ea5e9",toolName:"#14b8a6",toolOutput:"#94a3b8",diffAdded:"#10b981",diffRemoved:"#f43f5e",agent:["#f59e0b","#14b8a6","#8b5cf6","#ec4899"]}}};function NP(){return Object.keys(iz)}Ls();mu();import{execSync as kwe}from"child_process";function Hq(e){try{let t=kwe("git worktree list --porcelain",{cwd:e,encoding:"utf-8"}),n=[],r={};for(let s of t.split(`
2100
+ `))s.startsWith("worktree ")?r={path:s.slice(9)}:s.startsWith("HEAD ")?r.head=s.slice(5):s.startsWith("branch ")?r.branch=s.slice(7).replace("refs/heads/",""):s==="bare"?r.isBare=!0:s===""&&(r.path&&n.push({path:r.path,branch:r.branch||"detached",head:r.head||"",isBare:!!r.isBare,isMain:n.length===0}),r={});return n}catch{return[]}}tA();import{existsSync as gFe,mkdirSync as Gq,readdirSync as hFe,readFileSync as yFe,writeFileSync as xwe}from"fs";import{join as S1}from"path";import{homedir as $we}from"os";var zq=S1($we(),".aiaca","plugins"),w1=new Map;function Cwe(){return Gq(zq,{recursive:!0}),zq}function Vq(){return Array.from(w1.values())}function Jq(e,t){let n=S1(Cwe(),e);Gq(n,{recursive:!0});let r={name:e,version:"1.0.0",description:`Plugin: ${e}`};return xwe(S1(n,"manifest.json"),JSON.stringify(r,null,2),"utf-8"),`Plugin "${e}" installed at ${n}`}function Wq(e){return w1.get(e)?(w1.delete(e),!0):!1}import{execSync as Kq}from"child_process";var v0={enabled:!1,recording:!1,lastTranscript:""};function Awe(){try{return process.platform==="win32"?(Kq("where whisper",{encoding:"utf-8",timeout:2e3}),!0):(Kq("which whisper",{encoding:"utf-8",timeout:2e3}),!0)}catch{return!1}}function Yq(){return Awe()?(v0.enabled=!0,!0):!1}function Qq(){v0.enabled=!1,v0.recording=!1}function Zq(){return{...v0}}import{existsSync as $Fe,mkdirSync as CFe,readFileSync as AFe,writeFileSync as TFe}from"fs";import{join as Twe}from"path";import{homedir as _we}from"os";var IFe=Twe(_we(),".aiaca","recordings");function Xq(e,t="markdown"){return t==="json"?JSON.stringify(e,null,2):e.map(n=>{let r=n.role==="user"?"**You**":"**AIACA**",s=n.timestamp.slice(11,19);return`### ${r} (${s})
2071
2101
 
2072
2102
  ${n.content}
2073
2103
  `}).join(`
2074
2104
  ---
2075
2105
 
2076
- `)}function eq(e,t){let n=[],r=e.toLowerCase();for(let s=0;s<t.length;s++){let i=t[s].content.toLowerCase();if(i.includes(r)){let o=i.indexOf(r),a=Math.max(0,o-40),c=Math.min(i.length,o+e.length+40);n.push({index:s,preview:t[s].content.slice(a,c)})}}return n}KA();function tq(e){let t=`-- ${e.mode.toUpperCase()} --`,n=`Col ${e.cursor}`;return`${t} ${n}`}import{spawn as FFe}from"child_process";var Rwe=new Map;function nq(){return Array.from(Rwe.values())}Rp();var oP=[{name:"help",aliases:["h","?"],description:"Show available commands",handler:async()=>oP.map(e=>` /${e.name.padEnd(16)} ${e.description}`).join(`
2106
+ `)}function e5(e,t){let n=[],r=e.toLowerCase();for(let s=0;s<t.length;s++){let i=t[s].content.toLowerCase();if(i.includes(r)){let o=i.indexOf(r),a=Math.max(0,o-40),c=Math.min(i.length,o+e.length+40);n.push({index:s,preview:t[s].content.slice(a,c)})}}return n}KA();function t5(e){let t=`-- ${e.mode.toUpperCase()} --`,n=`Col ${e.cursor}`;return`${t} ${n}`}import{spawn as FFe}from"child_process";var Rwe=new Map;function n5(){return Array.from(Rwe.values())}Rp();var oP=[{name:"help",aliases:["h","?"],description:"Show available commands",handler:async()=>oP.map(e=>` /${e.name.padEnd(16)} ${e.description}`).join(`
2077
2107
  `)},{name:"clear",description:"Clear conversation history",handler:async(e,t)=>(t.clearHistory(),"History cleared.")},{name:"compact",description:"Compact conversation to save context",handler:async(e,t)=>{await t.compact()}},{name:"exit",aliases:["quit","q"],description:"Exit AIACA",handler:async(e,t)=>{try{let n=await Promise.resolve().then(()=>(Wu(),Ju));if(n.getConfig().enabled){let r=await n.purge("explicit_exit");r.success||console.error(`\u26A0\uFE0F Purge had warnings: ${r.warnings.join(", ")}`)}}catch{}t.exit()}},{name:"sessions",aliases:["session"],description:"List recent sessions",handler:async()=>{let e=Yg().slice(0,10);return e.length?e.map(t=>` ${t.id.slice(0,12)} | ${t.startedAt.slice(0,16)} | ${t.messageCount} msgs`).join(`
2078
2108
  `):"No sessions."}},{name:"login",description:"Set or update API credentials",handler:async()=>{let{runSetupWizard:e}=await Promise.resolve().then(()=>(hl(),rf));console.log(`
2079
2109
  Exiting AIACA to run the setup wizard...
2080
2110
  `),setTimeout(async()=>{await e({rerun:!0}),process.exit(0)},100)}},{name:"logout",description:"Remove saved credentials",handler:async()=>{let{clearCredentials:e,loadCredentials:t}=await Promise.resolve().then(()=>(hl(),rf)),n=t();return!n||!n.geminiApiKey&&!n.claudeApiKey?"No saved credentials to remove.":(e(),`\u2713 Credentials cleared from ~/.aiaca/credentials.json
2081
2111
  Run /login or set GEMINI_API_KEY / ANTHROPIC_API_KEY to re-authenticate.`)}},{name:"auth",description:"Show authentication status",usage:"/auth [status]",handler:async(e,t)=>{let{getAuthStatus:n}=await Promise.resolve().then(()=>(hl(),rf)),r=n("gemini"),s=n("claude");return["\u250C\u2500 AIACA Auth Status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","\u2502",`\u2502 Active provider: ${t.config.provider}`,"\u2502",`\u2502 Gemini ${r.isSet?"\u2713":"\u2717"} ${r.keyPreview.padEnd(16)} source: ${r.source}`,`\u2502 Claude ${s.isSet?"\u2713":"\u2717"} ${s.keyPreview.padEnd(16)} source: ${s.source}`,"\u2502","\u2502 Sources: env > ~/.aiaca/credentials.json > config.json","\u2502","\u2502 /login \u2014 set or update credentials","\u2502 /logout \u2014 remove saved credentials","\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"].join(`
2082
2112
  `)}},{name:"resume",description:"Resume a previous session",usage:"/resume [id]",handler:async(e,t)=>{if(!e.trim()){let r=Yg().slice(0,5);return r.length?r.map(s=>` ${s.id.slice(0,12)} | ${s.startedAt.slice(0,16)}`).join(`
2083
- `):"No sessions."}let n=Kg(e.trim());return n?(t.session.messages=n.messages,t.clearHistory(),`__RESUME__${JSON.stringify(n.messages)}`):"Not found."}},{name:"rename",description:"Rename current session",usage:"/rename <title>",handler:async(e,t)=>(t.session.title=e.trim()||void 0,`Session renamed: ${e.trim()}`)},{name:"export",description:"Export conversation as markdown",handler:async(e,t)=>{let n=X5(t.session.messages),r=Eg(t.session.cwd,`aiaca-export-${Date.now()}.md`);return iP(r,n,"utf-8"),`Exported to ${r}`}},{name:"copy",description:"Copy last assistant response to clipboard",handler:async(e,t)=>{let n=[...t.session.messages].reverse().find(r=>r.role==="assistant");if(!n)return"No response to copy.";try{return process.platform==="win32"?ia(`echo ${n.content.slice(0,8e3)} | clip`,{encoding:"utf-8"}):ia(`echo "${n.content.slice(0,8e3)}" | pbcopy`,{encoding:"utf-8"}),"Copied to clipboard."}catch{return"Clipboard not available."}}},{name:"share",description:"Export session for sharing",handler:async(e,t)=>{let n=JSON.stringify(t.session,null,2),r=Eg(t.session.cwd,`aiaca-share-${t.session.id.slice(0,8)}.json`);return iP(r,n,"utf-8"),`Session exported to ${r}`}},{name:"search",description:"Search conversation history",usage:"/search <query>",handler:async(e,t)=>{let n=eq(e.trim(),t.session.messages);return n.length?n.slice(0,5).map(r=>` [${r.index}] ...${r.preview}...`).join(`
2113
+ `):"No sessions."}let n=Kg(e.trim());return n?(t.session.messages=n.messages,t.clearHistory(),`__RESUME__${JSON.stringify(n.messages)}`):"Not found."}},{name:"rename",description:"Rename current session",usage:"/rename <title>",handler:async(e,t)=>(t.session.title=e.trim()||void 0,`Session renamed: ${e.trim()}`)},{name:"export",description:"Export conversation as markdown",handler:async(e,t)=>{let n=Xq(t.session.messages),r=Eg(t.session.cwd,`aiaca-export-${Date.now()}.md`);return iP(r,n,"utf-8"),`Exported to ${r}`}},{name:"copy",description:"Copy last assistant response to clipboard",handler:async(e,t)=>{let n=[...t.session.messages].reverse().find(r=>r.role==="assistant");if(!n)return"No response to copy.";try{return process.platform==="win32"?ia(`echo ${n.content.slice(0,8e3)} | clip`,{encoding:"utf-8"}):ia(`echo "${n.content.slice(0,8e3)}" | pbcopy`,{encoding:"utf-8"}),"Copied to clipboard."}catch{return"Clipboard not available."}}},{name:"share",description:"Export session for sharing",handler:async(e,t)=>{let n=JSON.stringify(t.session,null,2),r=Eg(t.session.cwd,`aiaca-share-${t.session.id.slice(0,8)}.json`);return iP(r,n,"utf-8"),`Session exported to ${r}`}},{name:"search",description:"Search conversation history",usage:"/search <query>",handler:async(e,t)=>{let n=e5(e.trim(),t.session.messages);return n.length?n.slice(0,5).map(r=>` [${r.index}] ...${r.preview}...`).join(`
2084
2114
  `):"No matches."}},{name:"rewind",description:"Remove last N messages",usage:"/rewind [count]",handler:async(e,t)=>{let n=parseInt(e)||2;return t.session.messages=t.session.messages.slice(0,-n),`Removed last ${n} messages.`}},{name:"model",aliases:["m"],description:"Switch provider/model",usage:"/model [provider] [model]",handler:async(e,t)=>{let n=["gemini-2.5-flash-lite","gemini-3.5-flash","gemini-3.1-pro-preview","gemini-3.1-flash-lite","gemini-3-flash-preview","gemini-2.5-flash","gemini-2.5-pro","gemma-4-31b-it","gemma-4-26b-a4b-it"],r=["claude-opus-4-8","claude-sonnet-4-6","claude-haiku-4-5","claude-opus-4-7","claude-opus-4-6","claude-sonnet-4-5","claude-opus-4-1-20250805","claude-sonnet-4-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229"];if(!e.trim())return`Current: ${t.config.provider} (${t.session.model})
2085
2115
 
2086
2116
  Gemini models:
@@ -2104,13 +2134,13 @@ Messages: ${t.session.messages.length}`}},{name:"files",description:"List files
2104
2134
  ${hg().map(e=>` ${e}`).join(`
2105
2135
  `)}`},{name:"tasks",description:"List background tasks",handler:async()=>{let e=Ao();return e.length?e.map(t=>` ${t.id.slice(0,12)} | ${t.state.padEnd(9)} | ${t.type} | ${(t.command||t.prompt||"").slice(0,40)}`).join(`
2106
2136
  `):"No tasks."}},{name:"mcp",description:"MCP server management",usage:"/mcp [list|init]",handler:async e=>{if(e.trim()==="init")return await eA(),"MCP servers initialized.";let t=XC();return t.length?t.map(n=>` ${n.name}: ${n.status} (${n.tools.length} tools)`).join(`
2107
- `):"No MCP servers. Use /mcp init"}},{name:"plugin",aliases:["plugins"],description:"Plugin management",usage:"/plugin [list|install|remove] [name]",handler:async e=>{let[t,...n]=e.trim().split(" "),r=n.join(" ");if(!t||t==="list"){let s=V5();return s.length?s.map(i=>` ${i.name} v${i.version} ${i.enabled?"\u2713":"\u2717"}`).join(`
2108
- `):"No plugins."}return t==="install"&&r?J5(r,""):t==="remove"&&r?W5(r)?`Removed: ${r}`:"Not found.":"Usage: /plugin [list|install|remove] [name]"}},{name:"hooks",description:"List registered hooks",handler:async(e,t)=>{let n=t.config.hooks;return n.length?n.map(r=>` ${r.event}: ${r.command||"handler"}`).join(`
2137
+ `):"No MCP servers. Use /mcp init"}},{name:"plugin",aliases:["plugins"],description:"Plugin management",usage:"/plugin [list|install|remove] [name]",handler:async e=>{let[t,...n]=e.trim().split(" "),r=n.join(" ");if(!t||t==="list"){let s=Vq();return s.length?s.map(i=>` ${i.name} v${i.version} ${i.enabled?"\u2713":"\u2717"}`).join(`
2138
+ `):"No plugins."}return t==="install"&&r?Jq(r,""):t==="remove"&&r?Wq(r)?`Removed: ${r}`:"Not found.":"Usage: /plugin [list|install|remove] [name]"}},{name:"hooks",description:"List registered hooks",handler:async(e,t)=>{let n=t.config.hooks;return n.length?n.map(r=>` ${r.event}: ${r.command||"handler"}`).join(`
2109
2139
  `):"No hooks configured."}},{name:"cron",description:"List cron jobs",handler:async()=>{let e=Ix();return e.length?e.map(t=>` ${t.name}: ${t.schedule} \u2192 ${t.command}`).join(`
2110
2140
  `):"No cron jobs."}},{name:"cost",aliases:["usage"],description:"Show session cost and usage",handler:async(e,t)=>{let n=t.costTracker.getSummary();return[`Cost: ${ma(n.totalCostUSD)} | Tokens: ${n.totalTokens.toLocaleString()} | Calls: ${n.apiCalls} | Duration: ${n.duration}`,...n.modelBreakdown.map(r=>` ${r.model}: ${ma(r.cost)} (${r.tokens.toLocaleString()} tokens)`)].join(`
2111
- `)}},{name:"plan",description:"Toggle plan mode (read-only)",handler:async(e,t)=>{let n=t.permissions.mode==="plan"?"ask":"plan";return t.setPermissionMode(n),n==="plan"?"\u{1F4CB} Plan mode ON":"\u270F\uFE0F Plan mode OFF"}},{name:"vim",description:"Toggle vim mode",handler:async()=>`Vim mode: ${tq({mode:"normal",cursor:0,buffer:"",register:"",count:0,commandBuffer:"",visualStart:0})}`},{name:"voice",description:"Toggle voice mode",handler:async()=>Z5().enabled?(Q5(),"Voice mode OFF"):Y5()?"Voice mode ON":"Voice not available (install whisper)"},{name:"worktree",aliases:["wt"],description:"List git worktrees",handler:async(e,t)=>{let n=H5(t.session.cwd);return n.length?n.map(r=>` ${r.branch.padEnd(20)} ${r.path}${r.isMain?" (main)":""}`).join(`
2112
- `):"No worktrees."}},{name:"lsp",description:"Show LSP server status",handler:async()=>{let e=nq();return e.length?e.map(t=>` ${t.name}: ${t.status} [${t.languages.join(", ")}]`).join(`
2113
- `):"No LSP servers running."}},{name:"version",description:"Show AIACA version",handler:async()=>"AIACA v1.0.0"},{name:"vcr",description:"Record/replay API sessions for testing",usage:"/vcr [list|record <name>|replay <name>|stop|stats <name>|delete <name>]",handler:async e=>{let{setMode:t,getMode:n,listCassettes:r,getCassetteStats:s,deleteCassette:i,getActiveCassette:o}=await Promise.resolve().then(()=>(w0(),aq)),a=e.trim().split(/\s+/),c=a[0]||"status",l=a.slice(1).join(" ");if(c==="status"){let u=n(),d=o();return`VCR mode: ${u}${d?`
2141
+ `)}},{name:"plan",description:"Toggle plan mode (read-only)",handler:async(e,t)=>{let n=t.permissions.mode==="plan"?"ask":"plan";return t.setPermissionMode(n),n==="plan"?"\u{1F4CB} Plan mode ON":"\u270F\uFE0F Plan mode OFF"}},{name:"vim",description:"Toggle vim mode",handler:async()=>`Vim mode: ${t5({mode:"normal",cursor:0,buffer:"",register:"",count:0,commandBuffer:"",visualStart:0})}`},{name:"voice",description:"Toggle voice mode",handler:async()=>Zq().enabled?(Qq(),"Voice mode OFF"):Yq()?"Voice mode ON":"Voice not available (install whisper)"},{name:"worktree",aliases:["wt"],description:"List git worktrees",handler:async(e,t)=>{let n=Hq(t.session.cwd);return n.length?n.map(r=>` ${r.branch.padEnd(20)} ${r.path}${r.isMain?" (main)":""}`).join(`
2142
+ `):"No worktrees."}},{name:"lsp",description:"Show LSP server status",handler:async()=>{let e=n5();return e.length?e.map(t=>` ${t.name}: ${t.status} [${t.languages.join(", ")}]`).join(`
2143
+ `):"No LSP servers running."}},{name:"version",description:"Show AIACA version",handler:async()=>"AIACA v1.0.0"},{name:"vcr",description:"Record/replay API sessions for testing",usage:"/vcr [list|record <name>|replay <name>|stop|stats <name>|delete <name>]",handler:async e=>{let{setMode:t,getMode:n,listCassettes:r,getCassetteStats:s,deleteCassette:i,getActiveCassette:o}=await Promise.resolve().then(()=>(w0(),a5)),a=e.trim().split(/\s+/),c=a[0]||"status",l=a.slice(1).join(" ");if(c==="status"){let u=n(),d=o();return`VCR mode: ${u}${d?`
2114
2144
  Active cassette: ${d.name} (${d.episodes.length} episodes)`:""}`}if(c==="list"){let u=r();return u.length===0?"No cassettes.":u.map(d=>` ${d.name.padEnd(20)} ${d.episodeCount} episodes, ${d.sizeKB}KB`).join(`
2115
2145
  `)}if(c==="record"&&l)return t("record",l),`Recording to "${l}"`;if(c==="replay"&&l)try{return t("replay",l),`Replaying from "${l}"`}catch(u){return u.message}if(c==="stop")return t("passthrough"),"VCR stopped (passthrough mode)";if(c==="stats"&&l){let u=s(l);return u?`Cassette "${l}":
2116
2146
  Episodes: ${u.episodes}
@@ -2461,7 +2491,7 @@ ${i.errors.map(o=>` - ${o}`).join(`
2461
2491
  `+i.slice(0,30).map(o=>` ${o.from}:${o.line}`).join(`
2462
2492
  `)}if(r==="deps"&&n[1]){!t.getCurrentProjectPath()&&t.isIndexed(s)&&t.loadProject(s);let i=t.getDependencies(n[1]);return i.length>0?i.join(`
2463
2493
  `):"No dependencies found."}return r==="clear"?t.clearIndex(s)?"Index cleared.":"No index to clear.":"Usage: /index [build|stats|search <query>|file <path>|refs <symbol>|deps <file>|clear|force]"}},{name:"orchestrate",aliases:["orch"],description:"Tool orchestration stats and configuration",usage:"/orchestrate [stats|config|mode <mode>|concurrency <n>|conflicts on|off|retries on|off|reset]",handler:async e=>{let t=await Promise.resolve().then(()=>(fT(),dT)),n=e.trim().split(/\s+/).filter(Boolean),r=n[0]||"stats";if(r==="stats"){let s=t.getAggregateStats();return s.totalRuns===0?"No orchestration runs recorded yet.":["Tool Orchestration Stats:",` Total runs: ${s.totalRuns}`,` Total tools executed: ${s.totalToolsExecuted}`,` Avg efficiency: ${(s.avgEfficiency*100).toFixed(1)}% (lower = better parallelism)`,` Avg parallelism: ${s.avgParallelism.toFixed(2)}`,` Total parallel savings: ${(s.totalSavingsMs/1e3).toFixed(1)}s`,"","Top Bottleneck Tools:",...s.topBottlenecks.map(i=>` ${i.count}x: ${i.tool}`)].join(`
2464
- `)}if(r==="config"){let s=t.getOrchestrationConfig();return JSON.stringify(s,null,2)}if(r==="mode"&&n[1])return t.setOrchestrationConfig({mode:n[1]}),`Orchestration mode set to: ${n[1]}`;if(r==="concurrency"&&n[1]){let s=parseInt(n[1],10);return!isFinite(s)||s<1?"Concurrency must be a positive integer":(t.setOrchestrationConfig({maxConcurrency:s}),`Max concurrency set to: ${s}`)}if(r==="conflicts"&&n[1]){let s=n[1]==="on";return t.setOrchestrationConfig({enableConflictDetection:s}),`Conflict detection: ${s?"on":"off"}`}if(r==="retries"&&n[1]){let s=n[1]==="on";return t.setOrchestrationConfig({enableRetries:s}),`Retries: ${s?"on":"off"}`}return r==="failure"&&n[1]?(t.setOrchestrationConfig({failureMode:n[1]}),`Failure mode: ${n[1]}`):r==="reset"?(t.resetConfig(),"Orchestration config reset to defaults."):"Usage: /orchestrate [stats|config|mode <mode>|concurrency <n>|conflicts on|off|retries on|off|failure <mode>|reset]"}},{name:"tip",aliases:["tips"],description:"Manage contextual tips system",usage:"/tip [show|browse|dismiss <id>|stats|prefs|reset|on|off|frequency <freq>]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(vq(),bq)),r=e.trim().split(/\s+/).filter(Boolean),s=r[0]||"show";if(s==="show"){let i=n.buildContext(t.session.messages,{sessionStartTime:new Date(t.session.startedAt).getTime(),totalCost:t.costTracker.totalCostUSD,contextTokens:t.costTracker.totalInputTokens+t.costTracker.totalOutputTokens}),o=n.checkContextualTriggers(i);return o?(n.recordTipShown(o.id,o.trigger),n.formatTip(o)):"No tip applicable right now."}if(s==="browse"){let i={};r[1]&&(i.category=r[1]),r[2]&&(i.difficulty=r[2]);let o=n.getAllTipsForBrowsing(i);return o.slice(0,25).map(a=>`[${a.difficulty}] [${a.category}] ${a.message}`).join(`
2494
+ `)}if(r==="config"){let s=t.getOrchestrationConfig();return JSON.stringify(s,null,2)}if(r==="mode"&&n[1])return t.setOrchestrationConfig({mode:n[1]}),`Orchestration mode set to: ${n[1]}`;if(r==="concurrency"&&n[1]){let s=parseInt(n[1],10);return!isFinite(s)||s<1?"Concurrency must be a positive integer":(t.setOrchestrationConfig({maxConcurrency:s}),`Max concurrency set to: ${s}`)}if(r==="conflicts"&&n[1]){let s=n[1]==="on";return t.setOrchestrationConfig({enableConflictDetection:s}),`Conflict detection: ${s?"on":"off"}`}if(r==="retries"&&n[1]){let s=n[1]==="on";return t.setOrchestrationConfig({enableRetries:s}),`Retries: ${s?"on":"off"}`}return r==="failure"&&n[1]?(t.setOrchestrationConfig({failureMode:n[1]}),`Failure mode: ${n[1]}`):r==="reset"?(t.resetConfig(),"Orchestration config reset to defaults."):"Usage: /orchestrate [stats|config|mode <mode>|concurrency <n>|conflicts on|off|retries on|off|failure <mode>|reset]"}},{name:"tip",aliases:["tips"],description:"Manage contextual tips system",usage:"/tip [show|browse|dismiss <id>|stats|prefs|reset|on|off|frequency <freq>]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(v5(),b5)),r=e.trim().split(/\s+/).filter(Boolean),s=r[0]||"show";if(s==="show"){let i=n.buildContext(t.session.messages,{sessionStartTime:new Date(t.session.startedAt).getTime(),totalCost:t.costTracker.totalCostUSD,contextTokens:t.costTracker.totalInputTokens+t.costTracker.totalOutputTokens}),o=n.checkContextualTriggers(i);return o?(n.recordTipShown(o.id,o.trigger),n.formatTip(o)):"No tip applicable right now."}if(s==="browse"){let i={};r[1]&&(i.category=r[1]),r[2]&&(i.difficulty=r[2]);let o=n.getAllTipsForBrowsing(i);return o.slice(0,25).map(a=>`[${a.difficulty}] [${a.category}] ${a.message}`).join(`
2465
2495
  `)+(o.length>25?`
2466
2496
  ... +${o.length-25} more (filter with /tip browse <category> <difficulty>)`:"")}if(s==="dismiss"&&r[1])return n.dismissTip(r[1]),`Dismissed tip: ${r[1]}`;if(s==="stats"){let i=n.getTipsStats();return["Tips Statistics:",` Total queries: ${i.totalQueries}`,` Total shows: ${i.totalShows}`,` Unique tips shown: ${i.uniqueTipsShown}`,` Dismissed: ${i.dismissedCount}`,` Helpful: ${i.helpfulCount}`,` Not helpful: ${i.notHelpfulCount}`,` Custom tips: ${i.customTipsCount}`,"","Top shown:",...i.topShownTips.slice(0,5).map(o=>` ${o.shows}x: ${o.message.slice(0,80)}`)].join(`
2467
2497
  `)}if(s==="prefs"){let i=n.getPreferences();return JSON.stringify(i,null,2)}return s==="reset"?(n.resetTips(),"Tip history reset (you may see tips again)"):s==="on"?(n.setPreferences({enabled:!0}),"Tips enabled."):s==="off"?(n.setPreferences({enabled:!1}),"Tips disabled."):s==="frequency"&&r[1]?(n.setPreferences({showFrequency:r[1]}),`Tip frequency set to: ${r[1]}`):s==="difficulty"&&r[1]?(n.setPreferences({minDifficulty:r[1]}),`Min difficulty set to: ${r[1]}`):"Usage: /tip [show|browse|dismiss <id>|stats|prefs|reset|on|off|frequency <freq>|difficulty <level>]"}},{name:"diagnose",aliases:["diag"],description:"Diagnostic tracking, performance metrics, and error reports",usage:"/diagnose [report|errors|metrics|logs|health|spans|export|level <log-level>|enable|disable|prune]",handler:async e=>{let t=await Promise.resolve().then(()=>(G$(),z$)),n=e.trim().split(/\s+/).filter(Boolean),r=n[0]||"report";if(r==="report"){let s=t.generateReport();return[`# Diagnostic Report \u2014 ${s.timestamp}`,"",`## Health: ${s.health.overall.toUpperCase()}`,...Object.entries(s.health.checks).map(([o,a])=>` ${a?.healthy?"\u2705":"\u274C"} ${o}: ${a?.message||"unknown"}`),"","## System",` CPUs: ${s.systemInfo.cpus}`,` Memory: ${s.systemInfo.memoryMB.free}MB free / ${s.systemInfo.memoryMB.total}MB (${s.systemInfo.memoryMB.usedPct.toFixed(1)}% used)`,` Uptime: ${Math.round(s.systemInfo.uptime)}s`,"","## Errors (top 5)",...s.topErrors.slice(0,5).map(o=>` ${o.count}x [${o.category}] ${o.message.slice(0,80)}`),"","## Top Metrics",` Counters: ${Object.keys(s.metrics.counters).length}`,` Gauges: ${Object.keys(s.metrics.gauges).length}`,` Histograms: ${Object.keys(s.metrics.histograms).length}`,` Active spans: ${s.activeSpans.length}`].join(`
@@ -2475,7 +2505,7 @@ ${i.errors.map(o=>` - ${o}`).join(`
2475
2505
  `)}if(r==="export"){let s=n[1]||`aiaca-diag-${Date.now()}.json`;return t.exportDiagnostics(s)?`Exported to ${s}`:"Export failed"}if(r==="level"){let s=n[1];return s?(t.setLogLevel(s),`Log level set to ${s}`):`Current level: ${t.getLogLevel()}`}return r==="enable"?(t.enableFileLogging(),t.enableConsoleOutput(),"Diagnostics enabled (file + console logging)"):r==="disable"?(t.disableFileLogging(),t.disableConsoleOutput(),"Diagnostics disabled"):r==="prune"?`Pruned ${t.pruneOldFiles(7)} old archive files`:"Usage: /diagnose [report|errors|metrics|logs|health|spans|export|level|enable|disable|prune]"}},{name:"team",description:"Manage team memory sync between agents",usage:"/team [status|sync|share|receive|agents|start|stop|config|clear]",handler:async e=>{let t=await Promise.resolve().then(()=>(B1(),j1)),n=e.trim().split(/\s+/).filter(Boolean),r=n[0]||"status";if(r==="status"){let s=t.getTeamSyncStats();return["Team Memory Sync:",` My agent: ${s.myAgent.name}`,` My ID: ${s.myAgent.id.slice(0,24)}...`,` Hostname: ${s.myAgent.hostname}`,` Sync mode: ${s.syncMode}`,` Known agents: ${s.knownAgents}`,` Online agents: ${s.onlineAgents}`,` Facts shared: ${s.totalFactsShared}`,` Facts received: ${s.totalFactsReceived}`,` Inbox pending: ${s.inboxPending}`,` Shared queue: ${s.sharedQueueSize}`].join(`
2476
2506
  `)}if(r==="agents"){let s=t.discoverAgents();return s.length===0?"No other agents discovered.":s.map(i=>{let o=t.getAgentPresence(i.id);return` ${o==="online"?"\u{1F7E2}":o==="recent"?"\u{1F7E1}":"\u26AA"} ${i.name} (${i.id.slice(0,16)}...) on ${i.hostname}`}).join(`
2477
2507
  `)}if(r==="sync"){let s=await t.manualSync();return`Sync complete: shared ${s.shared}, received ${s.received}`}if(r==="share")return`Shared ${t.shareMemories({minConfidence:.7,minImportance:.5}).sharedCount} memories.`;if(r==="receive"){let s=t.receiveMemories();return s.length===0?"No memories to receive.":s.map(i=>`From ${i.fromAgent?.slice(0,12)}...: +${i.added} added, ${i.updated} updated, ${i.conflicts} conflicts`).join(`
2478
- `)}if(r==="start"){let s=t.loadTeamConfig();return t.startAutoSync(s.intervalMs,"auto"),s.enableFileWatcher&&t.startFileWatcher(),`Auto-sync started (every ${Math.round(s.intervalMs/1e3)}s)`}if(r==="stop")return t.stopAutoSync(),t.stopFileWatcher(),"Auto-sync stopped.";if(r==="config"){let s=n[1],i=n.slice(2).join(" "),o=t.loadTeamConfig();if(!s)return JSON.stringify(o,null,2);if(i){let a={[s]:isNaN(Number(i))?i:Number(i)};return t.saveTeamConfig(a),`Set ${s} = ${i}`}return`${s} = ${o[s]}`}return r==="clear"?(t.clearTeamMemory(),"Team memory cleared. New identity will be created on next operation."):r==="prune"?(t.pruneOldData(),"Pruned data older than 7 days."):"Usage: /team [status|sync|share|receive|agents|start|stop|config|clear|prune]"}},{name:"docs",aliases:["doc"],description:"Generate documentation (Magic Docs)",usage:"/docs [readme|api|architecture|changelog|all] [--ai] [--write]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(qq(),Nq)),r=e.trim().split(/\s+/).filter(Boolean),s=r.find(p=>!p.startsWith("--"))||"readme",i=r.includes("--ai"),o=r.includes("--write"),a;if(i&&(a=(await Promise.resolve().then(()=>(Zi(),sa))).createProvider(t.config.provider,(await Promise.resolve().then(()=>(Mr(),Cs))).getApiKey(t.config),t.session.model)),s==="all")return(await n.generateAllDocs(t.session.cwd,a)).map(m=>`${m.type}: ${m.content.split(`
2508
+ `)}if(r==="start"){let s=t.loadTeamConfig();return t.startAutoSync(s.intervalMs,"auto"),s.enableFileWatcher&&t.startFileWatcher(),`Auto-sync started (every ${Math.round(s.intervalMs/1e3)}s)`}if(r==="stop")return t.stopAutoSync(),t.stopFileWatcher(),"Auto-sync stopped.";if(r==="config"){let s=n[1],i=n.slice(2).join(" "),o=t.loadTeamConfig();if(!s)return JSON.stringify(o,null,2);if(i){let a={[s]:isNaN(Number(i))?i:Number(i)};return t.saveTeamConfig(a),`Set ${s} = ${i}`}return`${s} = ${o[s]}`}return r==="clear"?(t.clearTeamMemory(),"Team memory cleared. New identity will be created on next operation."):r==="prune"?(t.pruneOldData(),"Pruned data older than 7 days."):"Usage: /team [status|sync|share|receive|agents|start|stop|config|clear|prune]"}},{name:"docs",aliases:["doc"],description:"Generate documentation (Magic Docs)",usage:"/docs [readme|api|architecture|changelog|all] [--ai] [--write]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(q5(),N5)),r=e.trim().split(/\s+/).filter(Boolean),s=r.find(p=>!p.startsWith("--"))||"readme",i=r.includes("--ai"),o=r.includes("--write"),a;if(i&&(a=(await Promise.resolve().then(()=>(Zi(),sa))).createProvider(t.config.provider,(await Promise.resolve().then(()=>(Mr(),Cs))).getApiKey(t.config),t.session.model)),s==="all")return(await n.generateAllDocs(t.session.cwd,a)).map(m=>`${m.type}: ${m.content.split(`
2479
2509
  `).length} lines (${m.durationMs}ms)`).join(`
2480
2510
  `);if(s==="suggest"){let p=n.getDocSuggestion(t.session.cwd);return p?`Suggested: /docs ${p}`:"All standard docs exist already."}let c={readme:"README.md",api:"API.md",architecture:"ARCHITECTURE.md",changelog:"CHANGELOG.md"},l=o?`${t.session.cwd}/${c[s]||`${s}.md`}`:void 0,u=await n.generateDoc({type:s,cwd:t.session.cwd,detail:"standard",outputPath:l,includeTOC:!0,includeExamples:!0},a),d=`Generated ${u.type} (${u.content.length} chars, ${u.durationMs}ms${u.metadata.aiCalls?", AI-enhanced":""})`,f=u.content.slice(0,800)+(u.content.length>800?`
2481
2511
 
@@ -2489,7 +2519,7 @@ ${f}`}},{name:"dream",description:"Run a memory consolidation cycle (REM-inspire
2489
2519
  `)}if(s==="clear")return n.clearAwayState(),"Away state cleared.";let o=n.getCurrentPeriod();if(!o)return"No away period detected. You're currently active.";let a;if(i){let c=(await Promise.resolve().then(()=>(Zi(),sa))).createProvider(t.config.provider,(await Promise.resolve().then(()=>(Mr(),Cs))).getApiKey(t.config),t.session.model);a=await n.summarizeWithAI(o,c)}else a=n.summarizeHeuristic(o);return s==="brief"?n.formatBrief(a):n.formatAsMarkdown(a)}},{name:"agentsummary",aliases:["asummary"],description:"Generate summary of agent/task work",usage:"/agentsummary [task-id|all|markdown|brief] [--ai]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(hU(),gU)),r=await Promise.resolve().then(()=>(mu(),Ax)),s=e.trim().split(/\s+/).filter(Boolean),i=s[0]||"all",o=s.includes("--ai");if(i==="all"){if(r.listTasks().length===0)return"No agent/task activity to summarize.";let f=t.session.messages.find(m=>m.role==="user"&&!m.content.startsWith("<tool_result"))?.content?.slice(0,200)||"Session work",p=n.summarizeAgentHeuristic(t.session.id,"main",f,t.session.messages);if(o){let m=(await Promise.resolve().then(()=>(Zi(),sa))).createProvider(t.config.provider,(await Promise.resolve().then(()=>(Mr(),Cs))).getApiKey(t.config),t.session.model);p=await n.summarizeAgentWithAI(t.session.id,"main",f,t.session.messages,m)}return n.saveAgentSummary(p),n.formatAsMarkdown(p)}let a=r.getTask(i);if(!a)return`Task ${i} not found.`;let c=a.command||a.prompt||"unknown",l=n.summarizeAgentHeuristic(a.id,"task-"+a.id.slice(0,8),c,[{role:"user",content:c,timestamp:a.createdAt},{role:"assistant",content:a.output||"",timestamp:a.completedAt||a.createdAt}]);return n.formatAsMarkdown(l)}},{name:"toolsummary",aliases:["tsummary","ts"],description:"Generate AI summary of tool use sequence",usage:"/toolsummary [markdown|narrative|bulleted|structured] [--ai]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(Y1(),sU)),r=e.trim().split(/\s+/).filter(Boolean),s=r.find(c=>!c.startsWith("--"))||"markdown",i=r.includes("--ai"),o;return i&&(o=(await Promise.resolve().then(()=>(Zi(),sa))).createProvider(t.config.provider,(await Promise.resolve().then(()=>(Mr(),Cs))).getApiKey(t.config),t.session.model)),(await n.summarizeToolUse(t.session.messages,{provider:o,format:s,useAI:i})).formatted}},{name:"suggest",description:"Get smart suggestions for what to do next",usage:"/suggest [pattern|speculative|stats|clear]",handler:async(e,t)=>{let n=await Promise.resolve().then(()=>(AU(),CU)),r=e.trim().toLowerCase()||"show";if(r==="stats"){let i=n.getPreferenceStats(),o=n.getCacheStats();return["Suggestion stats:",` Accepted: ${i.totalAccepted}`,` Rejected: ${i.totalRejected}`,` Top category: ${i.topCategory}`,` Cache entries: ${o.entries}`,"Top suggestions:",...i.topSuggestions.map(a=>` ${a.uses}x ${a.text}`)].join(`
2490
2520
  `)}if(r==="clear")return n.clearPreferences(),n.clearSpeculativeCache(),"Preferences and cache cleared.";if(r==="speculative"){let i=(await Promise.resolve().then(()=>(Zi(),sa))).createProvider(t.config.provider,(await Promise.resolve().then(()=>(Mr(),Cs))).getApiKey(t.config),t.session.model),o=await n.generateSpeculative(t.session.messages,{provider:i,maxSuggestions:5});return o.length===0?"No speculative suggestions generated.":o.map((a,c)=>` ${c+1}. [${a.category}] ${a.text} (${Math.round(a.confidence*100)}%)`).join(`
2491
2521
  `)}let s=n.getSuggestions(t.session.messages,{limit:5});return s.length===0?"No suggestions available right now.":s.map((i,o)=>` ${o+1}. [${i.category}] ${i.text} (${Math.round(i.confidence*100)}%)`).join(`
2492
- `)}},{name:"skill",aliases:["skills"],description:"Manage skills (search, install, list, registry)",usage:"/skill [list|search <query>|install <name>|uninstall <name>|registry|info <name>|stats]",handler:async e=>{let t=await Promise.resolve().then(()=>(v1(),B5)),n=e.trim().split(/\s+/),r=n[0]||"list",s=n.slice(1).join(" ");if(r==="list"){let i=t.listAllSkills();return i.length===0?"No skills available.":i.slice(0,20).map(o=>` [${o.source.padEnd(8)}] ${o.name.padEnd(20)} v${o.version} ${o.description.slice(0,50)}`).join(`
2522
+ `)}},{name:"skill",aliases:["skills"],description:"Manage skills (search, install, list, registry)",usage:"/skill [list|search <query>|install <name>|uninstall <name>|registry|info <name>|stats]",handler:async e=>{let t=await Promise.resolve().then(()=>(v1(),Bq)),n=e.trim().split(/\s+/),r=n[0]||"list",s=n.slice(1).join(" ");if(r==="list"){let i=t.listAllSkills();return i.length===0?"No skills available.":i.slice(0,20).map(o=>` [${o.source.padEnd(8)}] ${o.name.padEnd(20)} v${o.version} ${o.description.slice(0,50)}`).join(`
2493
2523
  `)+(i.length>20?`
2494
2524
  ... +${i.length-20} more`:"")}if(r==="search"&&s){let i=t.searchSkills(s,{limit:10});return i.length===0?`No skills match: ${s}`:i.map(o=>` [${o.source}] ${o.name} v${o.version}
2495
2525
  ${o.description}