smolerclaw 1.5.0 → 1.6.0

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/index.js +1410 -281
  2. package/package.json +57 -52
package/dist/index.js CHANGED
@@ -1,26 +1,26 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var LX=Object.defineProperty;var jX=($)=>$;function DX($,Z){this[$]=jX.bind(null,Z)}var oZ=($,Z)=>{for(var Y in Z)LX($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:DX.bind(Z,Y)})};var V1=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as IX,appendFileSync as SX,mkdirSync as vW,writeFileSync as wX,unlinkSync as kX}from"fs";import{join as G2}from"path";import{tmpdir as bX,homedir as yX}from"os";import{randomBytes as _X}from"crypto";function f0($,Z,Y){if(!F4)return;let Q=new Date().toISOString(),J=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
3
+ var ZG=Object.defineProperty;var YG=($)=>$;function QG($,Z){this[$]=YG.bind(null,Z)}var h9=($,Z)=>{for(var Y in Z)ZG($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:QG.bind(Z,Y)})};var H$=($,Z)=>()=>($&&(Z=$($=0)),Z);var b8=import.meta.require;import{existsSync as KG,appendFileSync as GG,mkdirSync as eO,writeFileSync as VG,unlinkSync as UG}from"fs";import{join as b7}from"path";import{tmpdir as qG,homedir as HG}from"os";import{randomBytes as WG}from"crypto";function g1($,Z,Y){if(!_8)return;let Q=new Date().toISOString(),z=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
4
4
  `:`[${Q}] [${$}] ${Z}
5
- `;try{SX(fX,J)}catch{}}function tZ($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function eZ($){let Z=$.replace(/\//g,"\\");return tZ(Z)}async function R4($){let Z=O4.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(IX($)){let Q={exists:!0,path:$};return O4.set($.toLowerCase(),Q),Q}return{exists:!1,error:`File not found: ${$}`}}let Y=`(Get-Command '${$}' -ErrorAction SilentlyContinue).Source`;try{let Q=await q$(Y,{timeout:5000});if(Q.exitCode===0&&Q.stdout.trim()){let z={exists:!0,path:Q.stdout.trim()};return O4.set($.toLowerCase(),z),z}let J={exists:!1,error:`'${$}' not found in PATH`};return O4.set($.toLowerCase(),J),J}catch(Q){return{exists:!1,error:Q instanceof Error?Q.message:String(Q)}}}async function q$($,Z={}){let{timeout:Y=q2,cwd:Q,debug:J=F4,sta:z=!1}=Z,X=performance.now(),K=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,V=["powershell",...sZ];if(z)V.push("-STA");if(V.push("-Command",K),J)f0("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:Y,cwd:Q,sta:z});let G;try{G=Bun.spawn(V,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(W){let B={stdout:"",stderr:`Failed to spawn PowerShell: ${W instanceof Error?W.message:String(W)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1};if(J)f0("ERROR","Failed to spawn process",{error:B.stderr});return B}let q=!1,U=setTimeout(()=>{q=!0;try{G.kill()}catch{}},Y);try{let[W,B]=await Promise.all([G.stdout instanceof ReadableStream?new Response(G.stdout).text():"",G.stderr instanceof ReadableStream?new Response(G.stderr).text():""]),M=await G.exited;clearTimeout(U);let N=Math.round(performance.now()-X),F={stdout:G1(W),stderr:G1(B),exitCode:q?-1:M,duration:N,timedOut:q};if(J)f0(F.exitCode===0?"INFO":"WARN","Command completed",{exitCode:F.exitCode,duration:N,timedOut:q,stdoutLength:F.stdout.length,stderrLength:F.stderr.length});return F}catch(W){clearTimeout(U);let B={stdout:"",stderr:`Execution error: ${W instanceof Error?W.message:String(W)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:q};if(J)f0("ERROR","Execution failed",{error:B.stderr,timedOut:q});return B}}async function $6($,Z={}){let Q=`& ${eZ($)}`;return q$(Q,Z)}async function Z6($,Z={}){let{timeout:Y=q2,cwd:Q,debug:J=F4,sta:z=!1}=Z,X=performance.now(),K=_X(4).toString("hex"),V=G2(bX(),`smolerclaw-${K}.ps1`),G=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
6
- ${$}`;try{wX(V,G,"utf-8")}catch(M){return{stdout:"",stderr:`Failed to write temp script: ${M instanceof Error?M.message:String(M)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}if(J)f0("INFO","Executing PowerShell via temp file",{tempPath:V,scriptLength:$.length,timeout:Y,sta:z});let q=["powershell",...sZ];if(z)q.push("-STA");q.push("-File",V);let U;try{U=Bun.spawn(q,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(M){return V2(V),{stdout:"",stderr:`Failed to spawn PowerShell: ${M instanceof Error?M.message:String(M)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let W=!1,B=setTimeout(()=>{W=!0;try{U.kill()}catch{}},Y);try{let[M,N]=await Promise.all([U.stdout instanceof ReadableStream?new Response(U.stdout).text():"",U.stderr instanceof ReadableStream?new Response(U.stderr).text():""]),F=await U.exited;clearTimeout(B),V2(V);let j=Math.round(performance.now()-X),p={stdout:G1(M),stderr:G1(N),exitCode:W?-1:F,duration:j,timedOut:W};if(J)f0(p.exitCode===0?"INFO":"WARN","File command completed",{exitCode:p.exitCode,duration:j,timedOut:W});return p}catch(M){return clearTimeout(B),V2(V),{stdout:"",stderr:`Execution error: ${M instanceof Error?M.message:String(M)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:W}}}function V2($){try{kX($)}catch{}}async function U2($,Z={}){let{timeout:Y=q2,cwd:Q,debug:J=F4}=Z,z=performance.now();if(J)f0("INFO","Executing command",{args:$,timeout:Y,cwd:Q});let X;try{X=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(G){return{stdout:"",stderr:`Failed to spawn: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-z),timedOut:!1}}let K=!1,V=setTimeout(()=>{K=!0;try{X.kill()}catch{}},Y);try{let[G,q]=await Promise.all([X.stdout instanceof ReadableStream?new Response(X.stdout).text():"",X.stderr instanceof ReadableStream?new Response(X.stderr).text():""]),U=await X.exited;return clearTimeout(V),{stdout:G1(G),stderr:G1(q),exitCode:K?-1:U,duration:Math.round(performance.now()-z),timedOut:K}}catch(G){return clearTimeout(V),{stdout:"",stderr:`Execution error: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-z),timedOut:K}}}async function H2($,Z={}){return q$($,{...Z,sta:!0})}async function u$($,Z,Y=[],Q={}){let J=["schtasks",`/${$}`,"/TN",Z,...Y],z=Q.timeout??1e4;return U2(J,{...Q,timeout:z})}async function W2($,Z,Y={}){let Q=tZ($),J=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return q$(J,Y)}async function Y6($,Z={}){let Y=eZ($);return q$(`Invoke-Item ${Y}`,Z)}async function U0($,Z,Y={}){let Q=rZ($),J=rZ(Z),z=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Q}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("smolerclaw").Show($toast)'].join("; "),X=Y.timeout??1e4;return q$(z,{...Y,timeout:X})}async function E4($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await q$(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function Q6($=15,Z={}){let Y=`Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First ${$} Name, @{N='Memory(MB)';E={[math]::Round($_.WorkingSet64/1MB,1)}}, MainWindowTitle | Format-Table -AutoSize | Out-String -Width 200`;return q$(Y,Z)}function G1($){let Z=$.replace(xX,"");if(Z.length>nZ)return Z.slice(0,nZ)+`
7
- ... (truncated, ${Z.length} total chars)`;return Z}function rZ($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function J6($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var q2=15000,nZ=1e5,xX,vX,fX,sZ,F4=!1,O4;var p$=V1(()=>{xX=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,vX=G2(yX(),".smolerclaw","logs"),fX=G2(vX,"windows-executor.log"),sZ=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];O4=new Map});import{existsSync as hX}from"fs";function q1(){if(L)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&hX($))return[$,"-c"];return["bash","-c"]}function X6(){if(L)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function gX($){if(L)return(await R4($)).exists;try{return(await U2(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function K6(){if(L4!==null)return L4;return L4=await gX("rg"),L4}function B2($){let Z=$.replace(/\\/g,"/");return p1.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var L,z6,cW,L4=null,p1;var o=V1(()=>{p$();L=process.platform==="win32",z6=process.platform==="darwin",cW=process.platform==="linux";p1=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as mX}from"events";class V6{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new mX,this.emitter.setMaxListeners($.maxListeners??20),this.debug=$.debug??!!process.env.DEBUG}on($,Z,Y={}){let Q={listener:Z,once:!1,async:Y.async??!1},J=this.listeners.get($)??[];if(J.push(Q),this.listeners.set($,J),this.debug)console.log(`[event-bus] Registered listener for '${$}'`);return()=>this.off($,Z)}once($,Z,Y={}){let Q={listener:Z,once:!0,async:Y.async??!1},J=this.listeners.get($)??[];if(J.push(Q),this.listeners.set($,J),this.debug)console.log(`[event-bus] Registered once listener for '${$}'`);return()=>this.off($,Z)}off($,Z){let Y=this.listeners.get($);if(!Y)return;let Q=Y.filter((J)=>J.listener!==Z);if(Q.length===0)this.listeners.delete($);else this.listeners.set($,Q);if(this.debug)console.log(`[event-bus] Removed listener from '${$}'`)}emit($,Z){let Y=this.listeners.get($);if(!Y||Y.length===0){if(this.debug)console.log(`[event-bus] No listeners for '${$}'`);return}if(this.debug)console.log(`[event-bus] Emitting '${$}' to ${Y.length} listener(s)`);let Q=[];for(let J of Y)try{let z=J.listener(Z);if(J.async&&z instanceof Promise)z.catch((X)=>{this.handleError(X,$,Z)});if(J.once)Q.push(J)}catch(z){this.handleError(z instanceof Error?z:Error(String(z)),$,Z)}if(Q.length>0){let J=Y.filter((z)=>!Q.includes(z));if(J.length===0)this.listeners.delete($);else this.listeners.set($,J)}}async emitAsync($,Z){let Y=this.listeners.get($);if(!Y||Y.length===0)return;if(this.debug)console.log(`[event-bus] Emitting async '${$}' to ${Y.length} listener(s)`);let Q=[],J=[];for(let z of Y)try{let X=z.listener(Z);if(X instanceof Promise)J.push(X.catch((K)=>{this.handleError(K instanceof Error?K:Error(String(K)),$,Z)}));if(z.once)Q.push(z)}catch(X){this.handleError(X instanceof Error?X:Error(String(X)),$,Z)}if(await Promise.all(J),Q.length>0){let z=Y.filter((X)=>!Q.includes(X));if(z.length===0)this.listeners.delete($);else this.listeners.set($,z)}}onError($){return this.errorHandlers.push($),()=>{let Z=this.errorHandlers.indexOf($);if(Z>=0)this.errorHandlers.splice(Z,1)}}listenerCount($){return this.listeners.get($)?.length??0}eventNames(){return Array.from(this.listeners.keys())}removeAllListeners($){if($)this.listeners.delete($);else this.listeners.clear();if(this.debug)console.log(`[event-bus] Removed all listeners${$?` for '${$}'`:""}`)}handleError($,Z,Y){if(this.debug||process.env.DEBUG)console.error(`[event-bus] Error in '${Z}' listener:`,$.message);for(let Q of this.errorHandlers)try{Q($,Z,Y)}catch{}}}function H0($){if(!M2)M2=new V6($);return M2}function s($,Z){r.emit($,Z)}var M2=null,r;var d$=V1(()=>{r=H0()});import{existsSync as c$,mkdirSync as C2,readFileSync as D4,writeFileSync as d1,renameSync as G6,statSync as uX}from"fs";import{join as C$,dirname as q6,relative as pX}from"path";import{createHash as dX,randomUUID as U6}from"crypto";function C6($,Z){if(l$=$,M6=Z,Z$=C$($,".backup"),lX(),O2=!0,h0=c$(C$(Z$,".git")),h0)N2=aX()}function c1(){return O2}function P($,Z){let Y=q6($);if(!c$(Y))C2(Y,{recursive:!0});let Q=C$(Y,`.smolerclaw-${U6().slice(0,8)}.tmp`);d1(Q,Z),G6(Q,$);let J=!1;if(O2){let X=iX($);if(X&&P4.includes(X))cX(X,Z),J=!0}let z={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:J,timestamp:Date.now()};r.emit("file:saved",z)}function N6($){return dX("sha256").update($).digest("hex")}function cX($,Z){let Y=N6(Z),Q=new Date().toISOString(),J=Buffer.byteLength(Z,"utf-8");W0=[...W0.filter((z)=>z.file!==$),{file:$,sha256:Y,size:J,updatedAt:Q}],oX()}function lX(){let $=C$(l$,W6);if(!c$($)){W0=[];return}try{let Z=JSON.parse(D4($,"utf-8"));if(Z.version!==H6){W0=[];return}W0=Z.checksums||[]}catch{W0=[]}}function oX(){if(!l$)return;let $=C$(l$,W6),Z={checksums:W0,version:H6},Y=C$(l$,`.vault-${U6().slice(0,8)}.tmp`);d1(Y,JSON.stringify(Z,null,2)),G6(Y,$)}function iX($){try{let Z=pX(l$,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function A4(){let $=[],Z=0;for(let Y of P4){let Q=C$(l$,Y),J=c$(Q);if(!J){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let z=0,X="";try{let G=uX(Q);z=G.size,X=G.mtime.toISOString()}catch{}let K=W0.find((G)=>G.file===Y),V=null;if(K)try{let G=D4(Q,"utf-8");if(V=N6(G)===K.sha256,!V)Z++}catch{V=!1,Z++}$.push({file:Y,exists:J,checksumValid:V,size:z,lastModified:X})}return{files:$,lastBackup:N2,backupEnabled:h0,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function T4($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${P4.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
8
- --- Arquivos ---`);for(let Q of $.files){if(!Q.exists){Z.push(` ${Q.file.padEnd(30)} (nao existe)`);continue}let J=(Q.size/1024).toFixed(1),z=Q.checksumValid===null?"?":Q.checksumValid?"OK":"CORROMPIDO",X=Q.lastModified?new Date(Q.lastModified).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${Q.file.padEnd(30)} ${J.padStart(8)} KB [${z}] ${X}`)}return Z.join(`
9
- `)}async function I4(){if(!l$)return"Error: vault not initialized.";if(!c$(Z$))C2(Z$,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
10
- `);if(d1(C$(Z$,".gitignore"),$),!c$(C$(Z$,".git"))){let Z=await B0(["git","init","-b",B6],Z$);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await B0(["git","config","user.email","vault@smolerclaw.local"],Z$),await B0(["git","config","user.name","smolerclaw-vault"],Z$)}return h0=!0,"Shadow backup inicializado."}async function U1($){if(!h0)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let K of P4){let V=C$(l$,K);if(!c$(V))continue;let G=C$(Z$,K),q=q6(G);if(!c$(q))C2(q,{recursive:!0});d1(G,D4(V,"utf-8"))}let Y=C$(M6,"config.json");if(c$(Y))d1(C$(Z$,"config.json"),D4(Y,"utf-8"));if(await B0(["git","add","-A"],Z$),!(await B0(["git","status","--porcelain"],Z$)).stdout.trim()){let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:"Nenhuma mudanca para backup",duration:Date.now()-Z,timestamp:Date.now()};return r.emit("task:completed",K),"Nenhuma mudanca para backup."}let J=$||`backup ${new Date().toISOString().slice(0,19)}`,z=await B0(["git","commit","-m",J],Z$);if(!z.ok){let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Commit falhou: ${z.stderr}`,duration:Date.now()-Z,timestamp:Date.now()};return r.emit("task:completed",K),`Backup commit falhou: ${z.stderr}`}N2=new Date().toISOString();let X={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:`Backup concluido: ${J}`,duration:Date.now()-Z,timestamp:Date.now()};return r.emit("task:completed",X),`Backup concluido: ${J}`}catch(Y){let Q=Y instanceof Error?Y.message:String(Y),J={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Backup falhou: ${Q}`,duration:Date.now()-Z,timestamp:Date.now()};return r.emit("task:completed",J),`Backup falhou: ${Q}`}}async function S4(){if(!h0)return"Backup nao ativado.";if(!(await B0(["git","remote","-v"],Z$)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await B0(["git","push","-u","origin",B6],Z$);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function aX(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:Z$,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function B0($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Q,J]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),z=await Y.exited;return{stdout:Q.trim(),stderr:J.trim(),ok:z===0}}function O6($=30){if(F2(),!h0)return;j4=setInterval(()=>{U1("auto-backup").catch(()=>{})},$*60*1000)}function F2(){if(j4)clearInterval(j4),j4=null}var H6=1,W6="vault-checksums.json",B6="smolerclaw-backup",P4,l$="",M6="",W0,Z$="",h0=!1,N2=null,O2=!1,j4=null;var g=V1(()=>{d$();P4=["config.json","memos.json","materials.json","decisions.json","tasks.json","finance.json","people.json","projects.json","work-sessions.json","opportunities.json","workflows.json","news-feeds.json","pitwall-baselines.json","rag/rag-index.json"],W0=[]});var L9={};oZ(L9,{searchInvestigations:()=>O9,openInvestigation:()=>H9,listInvestigations:()=>N9,initInvestigations:()=>U9,getInvestigation:()=>C9,generateReport:()=>F9,formatInvestigationList:()=>c7,formatInvestigationDetail:()=>R9,formatEvidenceDetail:()=>WG,collectEvidence:()=>W9,closeInvestigation:()=>M9,addFinding:()=>B9});import{existsSync as qY,mkdirSync as VG,readFileSync as GG}from"fs";import{join as qG}from"path";import{randomUUID as UG}from"crypto";function d7(){P(HY(),JSON.stringify(X$,null,2))}function HG(){let $=HY();if(!qY($)){X$=[];return}try{X$=JSON.parse(GG($,"utf-8"))}catch{X$=[]}}function U9($){if(UY=$,!qY($))VG($,{recursive:!0});HG()}function H9($,Z,Y,Q=[]){let J=new Date().toISOString(),z={id:E9(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((X)=>X.toLowerCase()),evidence:[],findings:[],created:J,updated:J};return X$=[...X$,z],d7(),z}function W9($,Z,Y,Q,J){let z=o8($);if(!z)return null;let X=Q.trim();if(X.length>GY)X=X.slice(0,GY)+`
11
- ...(truncated, ${Q.length} total chars)`;let K={id:E9(),source:Z,label:Y.trim(),content:X,path:J?.trim(),timestamp:new Date().toISOString()},V={...z,evidence:[...z.evidence,K],status:z.status==="aberta"?"em_andamento":z.status,updated:new Date().toISOString()};return X$=X$.map((G)=>G.id===z.id?V:G),d7(),K}function B9($,Z,Y,Q,J=[]){let z=o8($);if(!z)return null;let X=J.filter((G)=>z.evidence.some((q)=>q.id===G)),K={id:E9(),severity:Z,title:Y.trim(),description:Q.trim(),evidence_ids:X,timestamp:new Date().toISOString()},V={...z,findings:[...z.findings,K],updated:new Date().toISOString()};return X$=X$.map((G)=>G.id===z.id?V:G),d7(),K}function M9($,Z,Y){let Q=o8($);if(!Q)return null;let J={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return X$=X$.map((z)=>z.id===Q.id?J:z),d7(),J}function C9($){return o8($)}function N9($,Z,Y=20){let Q=[...X$];if($)Q=Q.filter((J)=>J.status===$);if(Z)Q=Q.filter((J)=>J.type===Z);return Q.sort((J,z)=>new Date(z.updated).getTime()-new Date(J.updated).getTime()).slice(0,Y)}function O9($){let Z=$.toLowerCase();return X$.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.hypothesis?.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))||Y.findings.some((Q)=>Q.title.toLowerCase().includes(Z))||Y.summary?.toLowerCase().includes(Z)).sort((Y,Q)=>new Date(Q.updated).getTime()-new Date(Y.updated).getTime())}function F9($){let Z=o8($);if(!Z)return null;let Y=[],Q=(X)=>new Date(X).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),J={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},z={critical:0,high:1,medium:2,low:3,info:4};if(Y.push(`# Investigacao: ${Z.title}`),Y.push(""),Y.push(`**Tipo:** ${J[Z.type]}`),Y.push(`**Status:** ${Z.status}`),Y.push(`**Abertura:** ${Q(Z.created)}`),Y.push(`**Ultima atualizacao:** ${Q(Z.updated)}`),Z.tags.length)Y.push(`**Tags:** ${Z.tags.join(", ")}`);if(Y.push(`**ID:** ${Z.id}`),Z.hypothesis)Y.push(""),Y.push("## Hipotese"),Y.push(Z.hypothesis);if(Z.evidence.length>0){Y.push(""),Y.push(`## Evidencias (${Z.evidence.length})`);for(let X of Z.evidence){let K=Q(X.timestamp);Y.push(""),Y.push(`### [${X.id}] ${X.label}`),Y.push(`- Fonte: ${X.source}${X.path?` (${X.path})`:""}`),Y.push(`- Coletada: ${K}`);let V=X.content.length>2000?X.content.slice(0,2000)+`
12
- ... (truncado)`:X.content;Y.push("```"),Y.push(V),Y.push("```")}}if(Z.findings.length>0){let X=[...Z.findings].sort((K,V)=>(z[K.severity]??4)-(z[V.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let K of X){let V=BY(K.severity);if(Y.push(""),Y.push(`### ${V} ${K.title}`),Y.push(K.description),K.evidence_ids.length>0)Y.push(`- Evidencias: ${K.evidence_ids.join(", ")}`)}}if(Z.summary)Y.push(""),Y.push("## Resumo"),Y.push(Z.summary);if(Z.recommendations)Y.push(""),Y.push("## Recomendacoes"),Y.push(Z.recommendations);return Y.join(`
13
- `)}function c7($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Y)=>{let Q=new Date(Y.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=WY(Y.status),z=Y.evidence.length,X=Y.findings.length,K=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${J} [${Q}] ${Y.title} (${Y.type}) \u2014 ${z} ev, ${X} concl${K} {${Y.id}}`});return`Investigacoes (${$.length}):
5
+ `;try{GG(NG,z)}catch{}}function c9($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function l9($){let Z=$.replace(/\//g,"\\");return c9(Z)}async function x8($){let Z=y8.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(KG($)){let Q={exists:!0,path:$};return y8.set($.toLowerCase(),Q),Q}return{exists:!1,error:`File not found: ${$}`}}let Y=`(Get-Command '${$}' -ErrorAction SilentlyContinue).Source`;try{let Q=await O0(Y,{timeout:5000});if(Q.exitCode===0&&Q.stdout.trim()){let J={exists:!0,path:Q.stdout.trim()};return y8.set($.toLowerCase(),J),J}let z={exists:!1,error:`'${$}' not found in PATH`};return y8.set($.toLowerCase(),z),z}catch(Q){return{exists:!1,error:Q instanceof Error?Q.message:String(Q)}}}async function O0($,Z={}){let{timeout:Y=y7,cwd:Q,debug:z=_8,sta:J=!1}=Z,X=performance.now(),K=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,G=["powershell",...d9];if(J)G.push("-STA");if(G.push("-Command",K),z)g1("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:Y,cwd:Q,sta:J});let V;try{V=Bun.spawn(G,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(H){let B={stdout:"",stderr:`Failed to spawn PowerShell: ${H instanceof Error?H.message:String(H)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1};if(z)g1("ERROR","Failed to spawn process",{error:B.stderr});return B}let U=!1,q=setTimeout(()=>{U=!0;try{V.kill()}catch{}},Y);try{let[H,B]=await Promise.all([V.stdout instanceof ReadableStream?new Response(V.stdout).text():"",V.stderr instanceof ReadableStream?new Response(V.stderr).text():""]),O=await V.exited;clearTimeout(q);let M=Math.round(performance.now()-X),C={stdout:W$(H),stderr:W$(B),exitCode:U?-1:O,duration:M,timedOut:U};if(z)g1(C.exitCode===0?"INFO":"WARN","Command completed",{exitCode:C.exitCode,duration:M,timedOut:U,stdoutLength:C.stdout.length,stderrLength:C.stderr.length});return C}catch(H){clearTimeout(q);let B={stdout:"",stderr:`Execution error: ${H instanceof Error?H.message:String(H)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:U};if(z)g1("ERROR","Execution failed",{error:B.stderr,timedOut:U});return B}}async function o9($,Z={}){let Q=`& ${l9($)}`;return O0(Q,Z)}async function i9($,Z={}){let{timeout:Y=y7,cwd:Q,debug:z=_8,sta:J=!1}=Z,X=performance.now(),K=WG(4).toString("hex"),G=b7(qG(),`smolerclaw-${K}.ps1`),V=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
6
+ ${$}`;try{VG(G,V,"utf-8")}catch(O){return{stdout:"",stderr:`Failed to write temp script: ${O instanceof Error?O.message:String(O)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}if(z)g1("INFO","Executing PowerShell via temp file",{tempPath:G,scriptLength:$.length,timeout:Y,sta:J});let U=["powershell",...d9];if(J)U.push("-STA");U.push("-File",G);let q;try{q=Bun.spawn(U,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(O){return f7(G),{stdout:"",stderr:`Failed to spawn PowerShell: ${O instanceof Error?O.message:String(O)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let H=!1,B=setTimeout(()=>{H=!0;try{q.kill()}catch{}},Y);try{let[O,M]=await Promise.all([q.stdout instanceof ReadableStream?new Response(q.stdout).text():"",q.stderr instanceof ReadableStream?new Response(q.stderr).text():""]),C=await q.exited;clearTimeout(B),f7(G);let F=Math.round(performance.now()-X),k={stdout:W$(O),stderr:W$(M),exitCode:H?-1:C,duration:F,timedOut:H};if(z)g1(k.exitCode===0?"INFO":"WARN","File command completed",{exitCode:k.exitCode,duration:F,timedOut:H});return k}catch(O){return clearTimeout(B),f7(G),{stdout:"",stderr:`Execution error: ${O instanceof Error?O.message:String(O)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:H}}}function f7($){try{UG($)}catch{}}async function _7($,Z={}){let{timeout:Y=y7,cwd:Q,debug:z=_8}=Z,J=performance.now();if(z)g1("INFO","Executing command",{args:$,timeout:Y,cwd:Q});let X;try{X=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(V){return{stdout:"",stderr:`Failed to spawn: ${V instanceof Error?V.message:String(V)}`,exitCode:1,duration:Math.round(performance.now()-J),timedOut:!1}}let K=!1,G=setTimeout(()=>{K=!0;try{X.kill()}catch{}},Y);try{let[V,U]=await Promise.all([X.stdout instanceof ReadableStream?new Response(X.stdout).text():"",X.stderr instanceof ReadableStream?new Response(X.stderr).text():""]),q=await X.exited;return clearTimeout(G),{stdout:W$(V),stderr:W$(U),exitCode:K?-1:q,duration:Math.round(performance.now()-J),timedOut:K}}catch(V){return clearTimeout(G),{stdout:"",stderr:`Execution error: ${V instanceof Error?V.message:String(V)}`,exitCode:1,duration:Math.round(performance.now()-J),timedOut:K}}}async function x7($,Z={}){return O0($,{...Z,sta:!0})}async function r0($,Z,Y=[],Q={}){let z=["schtasks",`/${$}`,"/TN",Z,...Y],J=Q.timeout??1e4;return _7(z,{...Q,timeout:J})}async function v7($,Z,Y={}){let Q=c9($),z=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return O0(z,Y)}async function r9($,Z={}){let Y=l9($);return O0(`Invoke-Item ${Y}`,Z)}async function B1($,Z,Y={}){let Q=p9($),z=p9(Z),J=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Q}</text><text id="2">${z}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("smolerclaw").Show($toast)'].join("; "),X=Y.timeout??1e4;return O0(J,{...Y,timeout:X})}async function v8($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await O0(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function n9($=15,Z={}){let Y=`Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First ${$} Name, @{N='Memory(MB)';E={[math]::Round($_.WorkingSet64/1MB,1)}}, MainWindowTitle | Format-Table -AutoSize | Out-String -Width 200`;return O0(Y,Z)}function W$($){let Z=$.replace(BG,"");if(Z.length>u9)return Z.slice(0,u9)+`
7
+ ... (truncated, ${Z.length} total chars)`;return Z}function p9($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function a9($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var y7=15000,u9=1e5,BG,OG,NG,d9,_8=!1,y8;var n0=H$(()=>{BG=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,OG=b7(HG(),".smolerclaw","logs"),NG=b7(OG,"windows-executor.log"),d9=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];y8=new Map});import{existsSync as MG}from"fs";function B$(){if(j)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&MG($))return[$,"-c"];return["bash","-c"]}function t9(){if(j)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function CG($){if(j)return(await x8($)).exists;try{return(await _7(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function e9(){if(h8!==null)return h8;return h8=await CG("rg"),h8}function h7($){let Z=$.replace(/\\/g,"/");return s$.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var j,s9,KN,h8=null,s$;var s=H$(()=>{n0();j=process.platform==="win32",s9=process.platform==="darwin",KN=process.platform==="linux";s$=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as EG}from"events";class $Y{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new EG,this.emitter.setMaxListeners($.maxListeners??20),this.debug=$.debug??!!process.env.DEBUG}on($,Z,Y={}){let Q={listener:Z,once:!1,async:Y.async??!1},z=this.listeners.get($)??[];if(z.push(Q),this.listeners.set($,z),this.debug)console.log(`[event-bus] Registered listener for '${$}'`);return()=>this.off($,Z)}once($,Z,Y={}){let Q={listener:Z,once:!0,async:Y.async??!1},z=this.listeners.get($)??[];if(z.push(Q),this.listeners.set($,z),this.debug)console.log(`[event-bus] Registered once listener for '${$}'`);return()=>this.off($,Z)}off($,Z){let Y=this.listeners.get($);if(!Y)return;let Q=Y.filter((z)=>z.listener!==Z);if(Q.length===0)this.listeners.delete($);else this.listeners.set($,Q);if(this.debug)console.log(`[event-bus] Removed listener from '${$}'`)}emit($,Z){let Y=this.listeners.get($);if(!Y||Y.length===0){if(this.debug)console.log(`[event-bus] No listeners for '${$}'`);return}if(this.debug)console.log(`[event-bus] Emitting '${$}' to ${Y.length} listener(s)`);let Q=[];for(let z of Y)try{let J=z.listener(Z);if(z.async&&J instanceof Promise)J.catch((X)=>{this.handleError(X,$,Z)});if(z.once)Q.push(z)}catch(J){this.handleError(J instanceof Error?J:Error(String(J)),$,Z)}if(Q.length>0){let z=Y.filter((J)=>!Q.includes(J));if(z.length===0)this.listeners.delete($);else this.listeners.set($,z)}}async emitAsync($,Z){let Y=this.listeners.get($);if(!Y||Y.length===0)return;if(this.debug)console.log(`[event-bus] Emitting async '${$}' to ${Y.length} listener(s)`);let Q=[],z=[];for(let J of Y)try{let X=J.listener(Z);if(X instanceof Promise)z.push(X.catch((K)=>{this.handleError(K instanceof Error?K:Error(String(K)),$,Z)}));if(J.once)Q.push(J)}catch(X){this.handleError(X instanceof Error?X:Error(String(X)),$,Z)}if(await Promise.all(z),Q.length>0){let J=Y.filter((X)=>!Q.includes(X));if(J.length===0)this.listeners.delete($);else this.listeners.set($,J)}}onError($){return this.errorHandlers.push($),()=>{let Z=this.errorHandlers.indexOf($);if(Z>=0)this.errorHandlers.splice(Z,1)}}listenerCount($){return this.listeners.get($)?.length??0}eventNames(){return Array.from(this.listeners.keys())}removeAllListeners($){if($)this.listeners.delete($);else this.listeners.clear();if(this.debug)console.log(`[event-bus] Removed all listeners${$?` for '${$}'`:""}`)}handleError($,Z,Y){if(this.debug||process.env.DEBUG)console.error(`[event-bus] Error in '${Z}' listener:`,$.message);for(let Q of this.errorHandlers)try{Q($,Z,Y)}catch{}}}function O1($){if(!g7)g7=new $Y($);return g7}function Q0($,Z){t.emit($,Z)}var g7=null,t;var u0=H$(()=>{t=O1()});import{existsSync as a0,mkdirSync as m7,readFileSync as m8,writeFileSync as t$,renameSync as ZY,statSync as RG}from"fs";import{join as A0,dirname as YY,relative as FG}from"path";import{createHash as LG,randomUUID as QY}from"crypto";function GY($,Z){if(s0=$,KY=Z,X0=A0($,".backup"),AG(),p7=!0,m1=a0(A0(X0,".git")),m1)u7=TG()}function e$(){return p7}function P($,Z){let Y=YY($);if(!a0(Y))m7(Y,{recursive:!0});let Q=A0(Y,`.smolerclaw-${QY().slice(0,8)}.tmp`);t$(Q,Z),ZY(Q,$);let z=!1;if(p7){let X=DG($);if(X&&u8.includes(X))jG(X,Z),z=!0}let J={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:z,timestamp:Date.now()};t.emit("file:saved",J)}function VY($){return LG("sha256").update($).digest("hex")}function jG($,Z){let Y=VY(Z),Q=new Date().toISOString(),z=Buffer.byteLength(Z,"utf-8");N1=[...N1.filter((J)=>J.file!==$),{file:$,sha256:Y,size:z,updatedAt:Q}],PG()}function AG(){let $=A0(s0,JY);if(!a0($)){N1=[];return}try{let Z=JSON.parse(m8($,"utf-8"));if(Z.version!==zY){N1=[];return}N1=Z.checksums||[]}catch{N1=[]}}function PG(){if(!s0)return;let $=A0(s0,JY),Z={checksums:N1,version:zY},Y=A0(s0,`.vault-${QY().slice(0,8)}.tmp`);t$(Y,JSON.stringify(Z,null,2)),ZY(Y,$)}function DG($){try{let Z=FG(s0,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function p8(){let $=[],Z=0;for(let Y of u8){let Q=A0(s0,Y),z=a0(Q);if(!z){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let J=0,X="";try{let V=RG(Q);J=V.size,X=V.mtime.toISOString()}catch{}let K=N1.find((V)=>V.file===Y),G=null;if(K)try{let V=m8(Q,"utf-8");if(G=VY(V)===K.sha256,!G)Z++}catch{G=!1,Z++}$.push({file:Y,exists:z,checksumValid:G,size:J,lastModified:X})}return{files:$,lastBackup:u7,backupEnabled:m1,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function d8($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${u8.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
8
+ --- Arquivos ---`);for(let Q of $.files){if(!Q.exists){Z.push(` ${Q.file.padEnd(30)} (nao existe)`);continue}let z=(Q.size/1024).toFixed(1),J=Q.checksumValid===null?"?":Q.checksumValid?"OK":"CORROMPIDO",X=Q.lastModified?new Date(Q.lastModified).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${Q.file.padEnd(30)} ${z.padStart(8)} KB [${J}] ${X}`)}return Z.join(`
9
+ `)}async function c8(){if(!s0)return"Error: vault not initialized.";if(!a0(X0))m7(X0,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
10
+ `);if(t$(A0(X0,".gitignore"),$),!a0(A0(X0,".git"))){let Z=await M1(["git","init","-b",XY],X0);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await M1(["git","config","user.email","vault@smolerclaw.local"],X0),await M1(["git","config","user.name","smolerclaw-vault"],X0)}return m1=!0,"Shadow backup inicializado."}async function O$($){if(!m1)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let K of u8){let G=A0(s0,K);if(!a0(G))continue;let V=A0(X0,K),U=YY(V);if(!a0(U))m7(U,{recursive:!0});t$(V,m8(G,"utf-8"))}let Y=A0(KY,"config.json");if(a0(Y))t$(A0(X0,"config.json"),m8(Y,"utf-8"));if(await M1(["git","add","-A"],X0),!(await M1(["git","status","--porcelain"],X0)).stdout.trim()){let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:"Nenhuma mudanca para backup",duration:Date.now()-Z,timestamp:Date.now()};return t.emit("task:completed",K),"Nenhuma mudanca para backup."}let z=$||`backup ${new Date().toISOString().slice(0,19)}`,J=await M1(["git","commit","-m",z],X0);if(!J.ok){let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Commit falhou: ${J.stderr}`,duration:Date.now()-Z,timestamp:Date.now()};return t.emit("task:completed",K),`Backup commit falhou: ${J.stderr}`}u7=new Date().toISOString();let X={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:`Backup concluido: ${z}`,duration:Date.now()-Z,timestamp:Date.now()};return t.emit("task:completed",X),`Backup concluido: ${z}`}catch(Y){let Q=Y instanceof Error?Y.message:String(Y),z={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Backup falhou: ${Q}`,duration:Date.now()-Z,timestamp:Date.now()};return t.emit("task:completed",z),`Backup falhou: ${Q}`}}async function l8(){if(!m1)return"Backup nao ativado.";if(!(await M1(["git","remote","-v"],X0)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await M1(["git","push","-u","origin",XY],X0);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function TG(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:X0,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function M1($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Q,z]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),J=await Y.exited;return{stdout:Q.trim(),stderr:z.trim(),ok:J===0}}function UY($=30){if(d7(),!m1)return;g8=setInterval(()=>{O$("auto-backup").catch(()=>{})},$*60*1000)}function d7(){if(g8)clearInterval(g8),g8=null}var zY=1,JY="vault-checksums.json",XY="smolerclaw-backup",u8,s0="",KY="",N1,X0="",m1=!1,u7=null,p7=!1,g8=null;var l=H$(()=>{u0();u8=["config.json","memos.json","materials.json","decisions.json","tasks.json","finance.json","people.json","projects.json","work-sessions.json","opportunities.json","workflows.json","news-feeds.json","pitwall-baselines.json","rag/rag-index.json"],N1=[]});var r6={};h9(r6,{searchInvestigations:()=>c6,openInvestigation:()=>h6,listInvestigations:()=>d6,initInvestigations:()=>v6,getInvestigation:()=>p6,generateReport:()=>l6,formatInvestigationList:()=>z5,formatInvestigationDetail:()=>o6,formatEvidenceDetail:()=>rU,collectEvidence:()=>g6,closeInvestigation:()=>u6,addFinding:()=>m6});import{existsSync as Qz,mkdirSync as dU,readFileSync as cU}from"fs";import{join as lU}from"path";import{randomUUID as oU}from"crypto";function Q5(){P(Jz(),JSON.stringify(q0,null,2))}function iU(){let $=Jz();if(!Qz($)){q0=[];return}try{q0=JSON.parse(cU($,"utf-8"))}catch{q0=[]}}function v6($){if(zz=$,!Qz($))dU($,{recursive:!0});iU()}function h6($,Z,Y,Q=[]){let z=new Date().toISOString(),J={id:i6(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((X)=>X.toLowerCase()),evidence:[],findings:[],created:z,updated:z};return q0=[...q0,J],Q5(),J}function g6($,Z,Y,Q,z){let J=$8($);if(!J)return null;let X=Q.trim();if(X.length>Yz)X=X.slice(0,Yz)+`
11
+ ...(truncated, ${Q.length} total chars)`;let K={id:i6(),source:Z,label:Y.trim(),content:X,path:z?.trim(),timestamp:new Date().toISOString()},G={...J,evidence:[...J.evidence,K],status:J.status==="aberta"?"em_andamento":J.status,updated:new Date().toISOString()};return q0=q0.map((V)=>V.id===J.id?G:V),Q5(),K}function m6($,Z,Y,Q,z=[]){let J=$8($);if(!J)return null;let X=z.filter((V)=>J.evidence.some((U)=>U.id===V)),K={id:i6(),severity:Z,title:Y.trim(),description:Q.trim(),evidence_ids:X,timestamp:new Date().toISOString()},G={...J,findings:[...J.findings,K],updated:new Date().toISOString()};return q0=q0.map((V)=>V.id===J.id?G:V),Q5(),K}function u6($,Z,Y){let Q=$8($);if(!Q)return null;let z={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return q0=q0.map((J)=>J.id===Q.id?z:J),Q5(),z}function p6($){return $8($)}function d6($,Z,Y=20){let Q=[...q0];if($)Q=Q.filter((z)=>z.status===$);if(Z)Q=Q.filter((z)=>z.type===Z);return Q.sort((z,J)=>new Date(J.updated).getTime()-new Date(z.updated).getTime()).slice(0,Y)}function c6($){let Z=$.toLowerCase();return q0.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.hypothesis?.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))||Y.findings.some((Q)=>Q.title.toLowerCase().includes(Z))||Y.summary?.toLowerCase().includes(Z)).sort((Y,Q)=>new Date(Q.updated).getTime()-new Date(Y.updated).getTime())}function l6($){let Z=$8($);if(!Z)return null;let Y=[],Q=(X)=>new Date(X).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),z={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},J={critical:0,high:1,medium:2,low:3,info:4};if(Y.push(`# Investigacao: ${Z.title}`),Y.push(""),Y.push(`**Tipo:** ${z[Z.type]}`),Y.push(`**Status:** ${Z.status}`),Y.push(`**Abertura:** ${Q(Z.created)}`),Y.push(`**Ultima atualizacao:** ${Q(Z.updated)}`),Z.tags.length)Y.push(`**Tags:** ${Z.tags.join(", ")}`);if(Y.push(`**ID:** ${Z.id}`),Z.hypothesis)Y.push(""),Y.push("## Hipotese"),Y.push(Z.hypothesis);if(Z.evidence.length>0){Y.push(""),Y.push(`## Evidencias (${Z.evidence.length})`);for(let X of Z.evidence){let K=Q(X.timestamp);Y.push(""),Y.push(`### [${X.id}] ${X.label}`),Y.push(`- Fonte: ${X.source}${X.path?` (${X.path})`:""}`),Y.push(`- Coletada: ${K}`);let G=X.content.length>2000?X.content.slice(0,2000)+`
12
+ ... (truncado)`:X.content;Y.push("```"),Y.push(G),Y.push("```")}}if(Z.findings.length>0){let X=[...Z.findings].sort((K,G)=>(J[K.severity]??4)-(J[G.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let K of X){let G=Kz(K.severity);if(Y.push(""),Y.push(`### ${G} ${K.title}`),Y.push(K.description),K.evidence_ids.length>0)Y.push(`- Evidencias: ${K.evidence_ids.join(", ")}`)}}if(Z.summary)Y.push(""),Y.push("## Resumo"),Y.push(Z.summary);if(Z.recommendations)Y.push(""),Y.push("## Recomendacoes"),Y.push(Z.recommendations);return Y.join(`
13
+ `)}function z5($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Y)=>{let Q=new Date(Y.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Xz(Y.status),J=Y.evidence.length,X=Y.findings.length,K=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${z} [${Q}] ${Y.title} (${Y.type}) \u2014 ${J} ev, ${X} concl${K} {${Y.id}}`});return`Investigacoes (${$.length}):
14
14
  ${Z.join(`
15
- `)}`}function R9($){let Z=(J)=>new Date(J).toLocaleDateString("pt-BR"),Y=WY($.status),Q=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Y}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)Q.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)Q.push(`Tags: ${$.tags.join(", ")}`);Q.push(`
16
- Evidencias: ${$.evidence.length}`);for(let J of $.evidence.slice(-5)){let z=J.content.slice(0,80).replace(/\n/g," ");Q.push(` [${J.id}] ${J.source}: ${J.label} \u2014 "${z}..."`)}if($.evidence.length>5)Q.push(` ... (${$.evidence.length-5} mais)`);Q.push(`
17
- Conclusoes: ${$.findings.length}`);for(let J of $.findings)Q.push(` ${BY(J.severity)} ${J.title}`);if($.summary)Q.push(`
15
+ `)}`}function o6($){let Z=(z)=>new Date(z).toLocaleDateString("pt-BR"),Y=Xz($.status),Q=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Y}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)Q.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)Q.push(`Tags: ${$.tags.join(", ")}`);Q.push(`
16
+ Evidencias: ${$.evidence.length}`);for(let z of $.evidence.slice(-5)){let J=z.content.slice(0,80).replace(/\n/g," ");Q.push(` [${z.id}] ${z.source}: ${z.label} \u2014 "${J}..."`)}if($.evidence.length>5)Q.push(` ... (${$.evidence.length-5} mais)`);Q.push(`
17
+ Conclusoes: ${$.findings.length}`);for(let z of $.findings)Q.push(` ${Kz(z.severity)} ${z.title}`);if($.summary)Q.push(`
18
18
  Resumo: ${$.summary}`);if($.recommendations)Q.push(`Recomendacoes: ${$.recommendations}`);return Q.join(`
19
- `)}function WG($){let Z=new Date($.timestamp).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"});return[`--- Evidencia {${$.id}} ---`,`Label: ${$.label}`,`Fonte: ${$.source}${$.path?` (${$.path})`:""}`,`Coletada: ${Z}`,"",$.content.length>3000?$.content.slice(0,3000)+`
19
+ `)}function rU($){let Z=new Date($.timestamp).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"});return[`--- Evidencia {${$.id}} ---`,`Label: ${$.label}`,`Fonte: ${$.source}${$.path?` (${$.path})`:""}`,`Coletada: ${Z}`,"",$.content.length>3000?$.content.slice(0,3000)+`
20
20
  ... (truncado)`:$.content].join(`
21
- `)}function o8($){let Z=$.toLowerCase().trim(),Y=X$.find((J)=>J.id===Z);if(Y)return Y;return X$.filter((J)=>J.title.toLowerCase().includes(Z)).sort((J,z)=>new Date(z.updated).getTime()-new Date(J.updated).getTime())[0]||null}function WY($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function BY($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function E9(){return UG().slice(0,8)}var UY="",X$,HY=()=>qG(UY,"investigations.json"),GY=50000;var i8=V1(()=>{g();X$=[]});var gQ={};oZ(gQ,{openUrl:()=>Z1,openFile:()=>s8,openApp:()=>$1,getSystemInfo:()=>Y1,getRunningApps:()=>t8,getOutlookEvents:()=>f$,getKnownApps:()=>o9,getDateTimeInfo:()=>Q1});function l9($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(aq.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function $1($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=c9[Y];if(!Q){let J=Object.keys(c9).join(", ");return`Unknown app: "${$}". Available: ${J}`}if(Z){let J=l9(Z,"argument");if(J)return J}if(!L)return"Error: this command is only available on Windows.";if(!Q.includes(":")){let J=await R4(Q);if(!J.exists)return`Error: ${Q} not found. ${J.error||""}`}try{let J=await W2(Q,Z);if(J.exitCode!==0&&J.stderr.trim())return`Error opening ${$}: ${J.stderr.trim()}`;if(J.timedOut)return`Error opening ${$}: timeout (application may have opened but response was delayed)`;return`Opened: ${$}`}catch(J){return`Error opening ${$}: ${J instanceof Error?J.message:String(J)}`}}async function Z1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=l9($,"URL");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await W2($);if(Y.exitCode!==0&&Y.stderr.trim())return`Error: ${Y.stderr.trim()}`;if(Y.timedOut)return"Error: timeout opening URL (browser may have opened but response was delayed)";return`Opened in browser: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function s8($){let Z=l9($,"file path");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await Y6($);if(Y.exitCode!==0&&Y.stderr.trim())return`Error: ${Y.stderr.trim()}`;if(Y.timedOut)return"Error: timeout opening file (application may have opened but response was delayed)";return`Opened: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function t8(){if(!L)return"Error: this command is only available on Windows.";try{let $=await Q6(15);if($.stderr.trim())return`Error: ${$.stderr.trim()}`;if($.timedOut)return"Error: timeout getting process list";return $.stdout.trim()||"No windowed applications running."}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async function Y1(){if(!L)return"Error: this command is only available on Windows.";let $=['$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average; "CPU: $cpu%"','$os = Get-CimInstance Win32_OperatingSystem; $total = [math]::Round($os.TotalVisibleMemorySize/1MB,1); $free = [math]::Round($os.FreePhysicalMemory/1MB,1); $used = $total - $free; "RAM: $used GB / $total GB (Free: $free GB)"','Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { $free = [math]::Round($_.FreeSpace/1GB,1); $total = [math]::Round($_.Size/1GB,1); "$($_.DeviceID) $free GB free / $total GB" }','$uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime; "Uptime: $($uptime.Days)d $($uptime.Hours)h $($uptime.Minutes)m"','$b = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue; if ($b) { "Battery: $($b.EstimatedChargeRemaining)%" } else { "Battery: N/A (desktop)" }'];try{let Z=await q$($.join("; "));if(!Z.stdout.trim()&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;if(Z.timedOut)return"Error: timeout getting system info";return Z.stdout.trim()||"System info unavailable."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function Q1(){let $=new Date,Z=[],Y=$.toLocaleDateString("pt-BR",{weekday:"long"}),Q=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),J=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Y}, ${Q} \u2014 ${J}`);let z=new Date($.valueOf());z.setDate(z.getDate()+3-(z.getDay()+6)%7);let X=new Date(z.getFullYear(),0,4),K=1+Math.round(((z.getTime()-X.getTime())/86400000-3+(X.getDay()+6)%7)/7);Z.push(`Semana ${K} do ano`);let V=$.getHours();if(V>=8&&V<18)Z.push("Status: horario comercial");else if(V>=18&&V<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
22
- `)}async function f$(){if(!L)return"Outlook integration only available on Windows.";let $=await nq();if($.success)return $.data;let Z=await rq();if(Z.success)return Z.data;return Z.data||$.data||"Calendario nao disponivel."}async function nq(){let $=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop",' $ns = $outlook.GetNamespace("MAPI")'," $cal = $ns.GetDefaultFolder(9)"," $today = (Get-Date).Date"," $tomorrow = $today.AddDays(1)"," $items = $cal.Items",' $items.Sort("[Start]")'," $items.IncludeRecurrences = $true",' $todayStr = $today.ToString("MM/dd/yyyy HH:mm")',' $tomorrowStr = $tomorrow.ToString("MM/dd/yyyy HH:mm")',` $filter = "[Start] >= '$todayStr' AND [Start] < '$tomorrowStr'"`," $events = $items.Restrict($filter)"," $results = @()"," foreach ($e in $events) {",' $start = ([DateTime]$e.Start).ToString("HH:mm")',' $end = ([DateTime]$e.End).ToString("HH:mm")',' $results += "$start-$end $($e.Subject)"'," }",' if ($results.Count -eq 0) { Write-Output "Nenhum evento hoje." }'," else { Write-Output ($results -join [char]10) }","} catch {"," Write-Error $_.Exception.Message"," exit 1","}"].join(`
23
- `);try{let Z=await q$($,{timeout:30000,sta:!0});if(Z.timedOut)return{success:!1,data:"Outlook timeout."};if(Z.exitCode===0&&Z.stdout.trim())return{success:!0,data:Z.stdout.trim()};return{success:!1,data:Z.stderr.trim()||"Outlook COM indisponivel."}}catch{return{success:!1,data:"Outlook COM indisponivel."}}}async function rq(){try{let Z=await Z6(`
21
+ `)}function $8($){let Z=$.toLowerCase().trim(),Y=q0.find((z)=>z.id===Z);if(Y)return Y;return q0.filter((z)=>z.title.toLowerCase().includes(Z)).sort((z,J)=>new Date(J.updated).getTime()-new Date(z.updated).getTime())[0]||null}function Xz($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function Kz($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function i6(){return oU().slice(0,8)}var zz="",q0,Jz=()=>lU(zz,"investigations.json"),Yz=50000;var Z8=H$(()=>{l();q0=[]});var fJ={};h9(fJ,{openUrl:()=>Q$,openFile:()=>J8,openApp:()=>Y$,getSystemInfo:()=>z$,getRunningApps:()=>X8,getOutlookEvents:()=>l0,getKnownApps:()=>CZ,getDateTimeInfo:()=>J$});function MZ($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(SH.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function Y$($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=NZ[Y];if(!Q){let z=Object.keys(NZ).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=MZ(Z,"argument");if(z)return z}if(!j)return"Error: this command is only available on Windows.";if(!Q.includes(":")){let z=await x8(Q);if(!z.exists)return`Error: ${Q} not found. ${z.error||""}`}try{let z=await v7(Q,Z);if(z.exitCode!==0&&z.stderr.trim())return`Error opening ${$}: ${z.stderr.trim()}`;if(z.timedOut)return`Error opening ${$}: timeout (application may have opened but response was delayed)`;return`Opened: ${$}`}catch(z){return`Error opening ${$}: ${z instanceof Error?z.message:String(z)}`}}async function Q$($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=MZ($,"URL");if(Z)return Z;if(!j)return"Error: this command is only available on Windows.";try{let Y=await v7($);if(Y.exitCode!==0&&Y.stderr.trim())return`Error: ${Y.stderr.trim()}`;if(Y.timedOut)return"Error: timeout opening URL (browser may have opened but response was delayed)";return`Opened in browser: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function J8($){let Z=MZ($,"file path");if(Z)return Z;if(!j)return"Error: this command is only available on Windows.";try{let Y=await r9($);if(Y.exitCode!==0&&Y.stderr.trim())return`Error: ${Y.stderr.trim()}`;if(Y.timedOut)return"Error: timeout opening file (application may have opened but response was delayed)";return`Opened: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function X8(){if(!j)return"Error: this command is only available on Windows.";try{let $=await n9(15);if($.stderr.trim())return`Error: ${$.stderr.trim()}`;if($.timedOut)return"Error: timeout getting process list";return $.stdout.trim()||"No windowed applications running."}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async function z$(){if(!j)return"Error: this command is only available on Windows.";let $=['$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average; "CPU: $cpu%"','$os = Get-CimInstance Win32_OperatingSystem; $total = [math]::Round($os.TotalVisibleMemorySize/1MB,1); $free = [math]::Round($os.FreePhysicalMemory/1MB,1); $used = $total - $free; "RAM: $used GB / $total GB (Free: $free GB)"','Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { $free = [math]::Round($_.FreeSpace/1GB,1); $total = [math]::Round($_.Size/1GB,1); "$($_.DeviceID) $free GB free / $total GB" }','$uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime; "Uptime: $($uptime.Days)d $($uptime.Hours)h $($uptime.Minutes)m"','$b = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue; if ($b) { "Battery: $($b.EstimatedChargeRemaining)%" } else { "Battery: N/A (desktop)" }'];try{let Z=await O0($.join("; "));if(!Z.stdout.trim()&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;if(Z.timedOut)return"Error: timeout getting system info";return Z.stdout.trim()||"System info unavailable."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function J$(){let $=new Date,Z=[],Y=$.toLocaleDateString("pt-BR",{weekday:"long"}),Q=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),z=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Y}, ${Q} \u2014 ${z}`);let J=new Date($.valueOf());J.setDate(J.getDate()+3-(J.getDay()+6)%7);let X=new Date(J.getFullYear(),0,4),K=1+Math.round(((J.getTime()-X.getTime())/86400000-3+(X.getDay()+6)%7)/7);Z.push(`Semana ${K} do ano`);let G=$.getHours();if(G>=8&&G<18)Z.push("Status: horario comercial");else if(G>=18&&G<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
22
+ `)}async function l0(){if(!j)return"Outlook integration only available on Windows.";let $=await wH();if($.success)return $.data;let Z=await kH();if(Z.success)return Z.data;return Z.data||$.data||"Calendario nao disponivel."}async function wH(){let $=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop",' $ns = $outlook.GetNamespace("MAPI")'," $cal = $ns.GetDefaultFolder(9)"," $today = (Get-Date).Date"," $tomorrow = $today.AddDays(1)"," $items = $cal.Items",' $items.Sort("[Start]")'," $items.IncludeRecurrences = $true",' $todayStr = $today.ToString("MM/dd/yyyy HH:mm")',' $tomorrowStr = $tomorrow.ToString("MM/dd/yyyy HH:mm")',` $filter = "[Start] >= '$todayStr' AND [Start] < '$tomorrowStr'"`," $events = $items.Restrict($filter)"," $results = @()"," foreach ($e in $events) {",' $start = ([DateTime]$e.Start).ToString("HH:mm")',' $end = ([DateTime]$e.End).ToString("HH:mm")',' $results += "$start-$end $($e.Subject)"'," }",' if ($results.Count -eq 0) { Write-Output "Nenhum evento hoje." }'," else { Write-Output ($results -join [char]10) }","} catch {"," Write-Error $_.Exception.Message"," exit 1","}"].join(`
23
+ `);try{let Z=await O0($,{timeout:30000,sta:!0});if(Z.timedOut)return{success:!1,data:"Outlook timeout."};if(Z.exitCode===0&&Z.stdout.trim())return{success:!0,data:Z.stdout.trim()};return{success:!1,data:Z.stderr.trim()||"Outlook COM indisponivel."}}catch{return{success:!1,data:"Outlook COM indisponivel."}}}async function kH(){try{let Z=await i9(`
24
24
  try {
25
25
  Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction Stop
26
26
 
@@ -88,10 +88,15 @@ try {
88
88
  Write-Error $_.Exception.Message
89
89
  exit 1
90
90
  }
91
- `,{timeout:30000,sta:!0});if(Z.timedOut)return{success:!1,data:"Calendario timeout."};if(Z.exitCode===0&&Z.stdout.trim())return{success:!0,data:Z.stdout.trim()};return{success:!1,data:Z.stderr.trim()||"Calendario Windows indisponivel."}}catch{return{success:!1,data:"Calendario Windows indisponivel."}}}function o9(){return Object.keys(c9)}var aq,c9;var J1=V1(()=>{o();p$();aq=/[";`$\n\r|&<>{}()]/;c9={excel:"excel",word:"winword",powerpoint:"powerpnt",outlook:"ms-outlook:",onenote:"onenote",teams:"msteams:",edge:"msedge",chrome:"chrome",firefox:"firefox",calculator:"calc",notepad:"notepad",terminal:"wt",explorer:"explorer",taskmanager:"taskmgr",settings:"ms-settings:",paint:"mspaint",snip:"snippingtool",vscode:"code",cursor:"cursor",postman:"Postman"}});import{readFileSync as PX}from"fs";import{join as AX,dirname as TX}from"path";function iZ($){let Z={help:!1,version:!1,noTools:!1,print:!1},Y=[],Q=0;while(Q<$.length){let J=$[Q];switch(J){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++Q],!Z.model)N4("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)N4("--session requires a value");break;case"--max-tokens":let z=Number($[++Q]);if(!z||z<=0)N4("--max-tokens requires a positive number");Z.maxTokens=z;break;case"--no-tools":Z.noTools=!0;break;case"-p":case"--print":Z.print=!0;break;default:if(J.startsWith("-"))N4(`Unknown option: ${J}. Try --help`);Y.push(J)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function u1(){return"1.5.0"}function aZ(){let $=u1();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
91
+ `,{timeout:30000,sta:!0});if(Z.timedOut)return{success:!1,data:"Calendario timeout."};if(Z.exitCode===0&&Z.stdout.trim())return{success:!0,data:Z.stdout.trim()};return{success:!1,data:Z.stderr.trim()||"Calendario Windows indisponivel."}}catch{return{success:!1,data:"Calendario Windows indisponivel."}}}function CZ(){return Object.keys(NZ)}var SH,NZ;var X$=H$(()=>{s();n0();SH=/[";`$\n\r|&<>{}()]/;NZ={excel:"excel",word:"winword",powerpoint:"powerpnt",outlook:"ms-outlook:",onenote:"onenote",teams:"msteams:",edge:"msedge",chrome:"chrome",firefox:"firefox",calculator:"calc",notepad:"notepad",terminal:"wt",explorer:"explorer",taskmanager:"taskmgr",settings:"ms-settings:",paint:"mspaint",snip:"snippingtool",vscode:"code",cursor:"cursor",postman:"Postman"}});import{readFileSync as zG}from"fs";import{join as JG,dirname as XG}from"path";function g9($){let Z={help:!1,version:!1,noTools:!1,print:!1,uiMode:"tui"},Y=[],Q=0;while(Q<$.length){let z=$[Q];switch(z){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++Q],!Z.model)n$("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)n$("--session requires a value");break;case"--max-tokens":let J=Number($[++Q]);if(!J||J<=0)n$("--max-tokens requires a positive number");Z.maxTokens=J;break;case"--no-tools":Z.noTools=!0;break;case"-p":case"--print":Z.print=!0;break;case"ui":Z.uiMode="web";break;case"desktop":Z.uiMode="desktop";break;case"--port":let X=Number($[++Q]);if(!X||X<=0||X>65535)n$("--port requires a valid port number (1-65535)");Z.port=X;break;default:if(z.startsWith("-"))n$(`Unknown option: ${z}. Try --help`);Y.push(z)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function a$(){return"1.6.0"}function m9(){let $=a$();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
92
92
 
93
93
  Usage:
94
- smolerclaw [options] [prompt]
94
+ smolerclaw [command] [options] [prompt]
95
+
96
+ Commands:
97
+ (none) Interactive TUI mode (default)
98
+ ui Launch web-based UI (browser)
99
+ desktop Launch desktop app (Electrobun)
95
100
 
96
101
  Options:
97
102
  -h, --help Show this help
@@ -101,9 +106,13 @@ Options:
101
106
  --max-tokens <n> Override max tokens per response
102
107
  --no-tools Disable tool use for this session
103
108
  -p, --print Print response and exit (no TUI)
109
+ --port <n> Port for web/desktop UI (default: 3847)
104
110
 
105
111
  Examples:
106
112
  smolerclaw Interactive TUI mode
113
+ smolerclaw ui Web UI at http://localhost:3847
114
+ smolerclaw desktop Desktop app (Electrobun)
115
+ smolerclaw ui --port 8080 Web UI on custom port
107
116
  smolerclaw "explain this error" Launch TUI with initial prompt
108
117
  smolerclaw -p "what is 2+2" Print answer and exit
109
118
  echo "review" | smolerclaw -p Pipe input, print response
@@ -116,16 +125,16 @@ Commands (inside TUI):
116
125
  /briefing Daily briefing /news News radar
117
126
  /task Create task /tasks List tasks
118
127
  /open Open Windows app /calendar Outlook calendar
119
- /export Export markdown /exit Quit`)}function N4($){console.error(`smolerclaw: ${$}`),process.exit(2)}o();g();import{existsSync as w4,mkdirSync as nX,readFileSync as F6}from"fs";import{homedir as rX}from"os";import{join as o$}from"path";var o1=rX(),k4=L?o$(process.env.APPDATA||o$(o1,"AppData","Roaming"),"smolerclaw"):o$(o1,".config","smolerclaw"),R2=L?o$(process.env.LOCALAPPDATA||o$(o1,"AppData","Local"),"smolerclaw"):o$(o1,".local","share","smolerclaw"),M0=o$(k4,"config.json"),H1={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:R2,toolApproval:"auto",language:"auto",maxSessionCost:0};function l1($){if(!w4($))nX($,{recursive:!0})}function R6(){if(l1(k4),l1(R2),l1(o$(R2,"sessions")),L)tX();if(!w4(M0))return P(M0,JSON.stringify(H1,null,2)),{...H1};let $;try{$=JSON.parse(F6(M0,"utf-8"))}catch{return P(M0,JSON.stringify(H1,null,2)),{...H1}}return sX({...H1,...$})}function sX($){let Z={...H1};if(typeof $.model==="string"&&$.model.trim())Z.model=$.model;if(typeof $.maxTokens==="number"&&$.maxTokens>0&&$.maxTokens<=1e5)Z.maxTokens=$.maxTokens;if(typeof $.maxHistory==="number"&&$.maxHistory>0&&$.maxHistory<=1000)Z.maxHistory=$.maxHistory;if(typeof $.systemPrompt==="string")Z.systemPrompt=$.systemPrompt;if(typeof $.skillsDir==="string"&&$.skillsDir.trim())Z.skillsDir=$.skillsDir;if(typeof $.dataDir==="string"&&$.dataDir.trim())Z.dataDir=$.dataDir;let Y=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&Y.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function b4($){l1(k4),P(M0,JSON.stringify($,null,2))}function y4(){return M0}function tX(){let $=o$(o1,".config","smolerclaw","config.json");if(w4($)&&!w4(M0))try{let Z=F6($,"utf-8");l1(k4),P(M0,Z)}catch{}}import{existsSync as eX,readFileSync as $K}from"fs";import{homedir as ZK}from"os";import{join as YK}from"path";var E6=YK(ZK(),".claude",".credentials.json");function E2(){let $=QK();if($)return $;throw Error("Claude Code subscription not found or expired.\nInstall Claude Code with a Pro/Max subscription and run `claude` to authenticate.")}function QK(){if(!eX(E6))return null;try{let Z=JSON.parse($K(E6,"utf-8")).claudeAiOauth;if(!Z?.accessToken)return null;if(Date.now()>Z.expiresAt-60000)return null;return{token:Z.accessToken,subscriptionType:Z.subscriptionType,expiresAt:Z.expiresAt}}catch{return null}}function g0(){try{return E2()}catch{return null}}function L6($){return`sub:${$.subscriptionType||"pro"}`}var _4=[{id:"claude-haiku-4-5-20251001",alias:"haiku",name:"Claude Haiku 4.5",contextWindow:200000,tier:"fast"},{id:"claude-sonnet-4-20250514",alias:"sonnet",name:"Claude Sonnet 4",contextWindow:200000,tier:"balanced"},{id:"claude-sonnet-4-6-20250627",alias:"sonnet-4.6",name:"Claude Sonnet 4.6",contextWindow:200000,tier:"balanced"},{id:"claude-opus-4-20250514",alias:"opus",name:"Claude Opus 4",contextWindow:200000,tier:"powerful"},{id:"claude-opus-4-6-20250318",alias:"opus-4.6",name:"Claude Opus 4.6",contextWindow:200000,tier:"powerful"}];function x4($){let Z=_4.find((z)=>z.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=_4.find((z)=>z.alias===Y);if(Q)return Q.id;let J=_4.find((z)=>z.id.includes(Y)||z.name.toLowerCase().includes(Y));if(J)return J.id;return $}function j6($){let Z=["Available models:"];for(let Y of _4){let Q=Y.id===$?" *":" ",J=Y.tier==="fast"?"\u26A1":Y.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${Q} ${Y.alias.padEnd(12)} ${J} ${Y.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
120
- `)}function R($,Z,Y,Q,J){if(Q==="m")throw TypeError("Private method is not writable");if(Q==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?J.call($,Y):J?J.value=Y:Z.set($,Y),Y}function C($,Z,Y,Q){if(Y==="a"&&!Q)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Q:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?Q:Y==="a"?Q.call($):Q?Q.value:Z.get($)}var L2=function(){let{crypto:$}=globalThis;if($?.randomUUID)return L2=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),Y=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Q)=>(+Q^Y()&15>>+Q/4).toString(16))};function i$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var i1=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class E extends Error{}class i extends E{constructor($,Z,Y,Q){super(`${i.makeMessage($,Z,Y)}`);this.status=$,this.headers=Q,this.requestID=Q?.get("request-id"),this.error=Z}static makeMessage($,Z,Y){let Q=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Y;if($&&Q)return`${$} ${Q}`;if($)return`${$} status code (no body)`;if(Q)return Q;return"(no status code or body)"}static generate($,Z,Y,Q){if(!$||!Q)return new m0({message:Y,cause:i1(Z)});let J=Z;if($===400)return new n1($,J,Y,Q);if($===401)return new r1($,J,Y,Q);if($===403)return new s1($,J,Y,Q);if($===404)return new t1($,J,Y,Q);if($===409)return new e1($,J,Y,Q);if($===422)return new $8($,J,Y,Q);if($===429)return new Z8($,J,Y,Q);if($>=500)return new Y8($,J,Y,Q);return new i($,J,Y,Q)}}class z$ extends i{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class m0 extends i{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class a1 extends m0{constructor({message:$}={}){super({message:$??"Request timed out."})}}class n1 extends i{}class r1 extends i{}class s1 extends i{}class t1 extends i{}class e1 extends i{}class $8 extends i{}class Z8 extends i{}class Y8 extends i{}var zK=/^[a-z][a-z0-9+.-]*:/i,D6=($)=>{return zK.test($)},j2=($)=>(j2=Array.isArray,j2($)),D2=j2;function v4($){if(typeof $!=="object")return{};return $??{}}function P2($){if(!$)return!0;for(let Z in $)return!1;return!0}function P6($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var A6=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new E(`${$} must be an integer`);if(Z<0)throw new E(`${$} must be a positive integer`);return Z};var f4=($)=>{try{return JSON.parse($)}catch(Z){return}};var T6=($)=>new Promise((Z)=>setTimeout(Z,$));var C0="0.80.0";var k6=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function XK(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var KK=()=>{let $=XK();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C0,"X-Stainless-OS":S6(Deno.build.os),"X-Stainless-Arch":I6(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C0,"X-Stainless-OS":S6(globalThis.process.platform??"unknown"),"X-Stainless-Arch":I6(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=VK();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Z.browser}`,"X-Stainless-Runtime-Version":Z.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function VK(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:Y}of $){let Q=Y.exec(navigator.userAgent);if(Q){let J=Q[1]||0,z=Q[2]||0,X=Q[3]||0;return{browser:Z,version:`${J}.${z}.${X}`}}}return null}var I6=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},S6=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},w6,b6=()=>{return w6??(w6=KK())};function y6(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function A2(...$){let Z=globalThis.ReadableStream;if(typeof Z>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Z(...$)}function h4($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return A2({start(){},async pull(Y){let{done:Q,value:J}=await Z.next();if(Q)Y.close();else Y.enqueue(J)},async cancel(){await Z.return?.()}})}function Q8($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let Y=await Z.read();if(Y?.done)Z.releaseLock();return Y}catch(Y){throw Z.releaseLock(),Y}},async return(){let Y=Z.cancel();return Z.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function _6($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var x6=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function v6($){return Object.entries($).filter(([Z,Y])=>typeof Y<"u").map(([Z,Y])=>{if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(Y)}`;if(Y===null)return`${encodeURIComponent(Z)}=`;throw new E(`Cannot stringify type ${typeof Y}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function g6($){let Z=0;for(let J of $)Z+=J.length;let Y=new Uint8Array(Z),Q=0;for(let J of $)Y.set(J,Q),Q+=J.length;return Y}var f6;function J8($){let Z;return(f6??(Z=new globalThis.TextEncoder,f6=Z.encode.bind(Z)))($)}var h6;function T2($){let Z;return(h6??(Z=new globalThis.TextDecoder,h6=Z.decode.bind(Z)))($)}var N$,O$;class N0{constructor(){N$.set(this,void 0),O$.set(this,void 0),R(this,N$,new Uint8Array,"f"),R(this,O$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?J8($):$;R(this,N$,g6([C(this,N$,"f"),Z]),"f");let Y=[],Q;while((Q=UK(C(this,N$,"f"),C(this,O$,"f")))!=null){if(Q.carriage&&C(this,O$,"f")==null){R(this,O$,Q.index,"f");continue}if(C(this,O$,"f")!=null&&(Q.index!==C(this,O$,"f")+1||Q.carriage)){Y.push(T2(C(this,N$,"f").subarray(0,C(this,O$,"f")-1))),R(this,N$,C(this,N$,"f").subarray(C(this,O$,"f")),"f"),R(this,O$,null,"f");continue}let J=C(this,O$,"f")!==null?Q.preceding-1:Q.preceding,z=T2(C(this,N$,"f").subarray(0,J));Y.push(z),R(this,N$,C(this,N$,"f").subarray(Q.index),"f"),R(this,O$,null,"f")}return Y}flush(){if(!C(this,N$,"f").length)return[];return this.decode(`
121
- `)}}N$=new WeakMap,O$=new WeakMap;N0.NEWLINE_CHARS=new Set([`
122
- `,"\r"]);N0.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function UK($,Z){for(let J=Z??0;J<$.length;J++){if($[J]===10)return{preceding:J,index:J+1,carriage:!1};if($[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function m6($){for(let Q=0;Q<$.length-1;Q++){if($[Q]===10&&$[Q+1]===10)return Q+2;if($[Q]===13&&$[Q+1]===13)return Q+2;if($[Q]===13&&$[Q+1]===10&&Q+3<$.length&&$[Q+2]===13&&$[Q+3]===10)return Q+4}return-1}var m4={off:0,error:200,warn:300,info:400,debug:500},I2=($,Z,Y)=>{if(!$)return;if(P6(m4,$))return $;t(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(m4))}`);return};function z8(){}function g4($,Z,Y){if(!Z||m4[$]>m4[Y])return z8;else return Z[$].bind(Z)}var HK={error:z8,warn:z8,info:z8,debug:z8},u6=new WeakMap;function t($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return HK;let Q=u6.get(Z);if(Q&&Q[0]===Y)return Q[1];let J={error:g4("error",Z,Y),warn:g4("warn",Z,Y),info:g4("info",Z,Y),debug:g4("debug",Z,Y)};return u6.set(Z,[Y,J]),J}var a$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,Y])=>[Z,Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":Y]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var X8;class F${constructor($,Z,Y){this.iterator=$,X8.set(this,void 0),this.controller=Z,R(this,X8,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,J=Y?t(Y):console;async function*z(){if(Q)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of WK($,Z)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(V){throw J.error("Could not parse message into JSON:",K.data),J.error("From chunk:",K.raw),V}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(V){throw J.error("Could not parse message into JSON:",K.data),J.error("From chunk:",K.raw),V}if(K.event==="ping")continue;if(K.event==="error")throw new i(void 0,f4(K.data)??K.data,void 0,$.headers)}X=!0}catch(K){if(i$(K))return;throw K}finally{if(!X)Z.abort()}}return new F$(z,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*J(){let X=new N0,K=Q8($);for await(let V of K)for(let G of X.decode(V))yield G;for(let V of X.flush())yield V}async function*z(){if(Q)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of J()){if(X)continue;if(K)yield JSON.parse(K)}X=!0}catch(K){if(i$(K))return;throw K}finally{if(!X)Z.abort()}}return new F$(z,Z,Y)}[(X8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),Q=(J)=>{return{next:()=>{if(J.length===0){let z=Y.next();$.push(z),Z.push(z)}return J.shift()}}};return[new F$(()=>Q($),this.controller,C(this,X8,"f")),new F$(()=>Q(Z),this.controller,C(this,X8,"f"))]}toReadableStream(){let $=this,Z;return A2({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:J}=await Z.next();if(J)return Y.close();let z=J8(JSON.stringify(Q)+`
123
- `);Y.enqueue(z)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*WK($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new E("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new E("Attempted to iterate over a response with no body")}let Y=new p6,Q=new N0,J=Q8($.body);for await(let z of BK(J))for(let X of Q.decode(z)){let K=Y.decode(X);if(K)yield K}for(let z of Q.flush()){let X=Y.decode(z);if(X)yield X}}async function*BK($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?J8(Y):Y,J=new Uint8Array(Z.length+Q.length);J.set(Z),J.set(Q,Z.length),Z=J;let z;while((z=m6(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class p6{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
124
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=MK($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function MK($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function u4($,Z){let{response:Y,requestLogID:Q,retryOfRequestLogID:J,startTime:z}=Z,X=await(async()=>{if(Z.options.stream){if(t($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return F$.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let V=Y.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let W=await Y.json();return S2(W,Y)}return await Y.text()})();return t($).debug(`[${Q}] response parsed`,a$({retryOfRequestLogID:J,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-z})),X}function S2($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var K8;class u0 extends Promise{constructor($,Z,Y=u4){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,K8.set(this,void 0),R(this,K8,$,"f")}_thenUnwrap($){return new u0(C(this,K8,"f"),this.responsePromise,async(Z,Y)=>S2($(await this.parseResponse(Z,Y),Y),Y.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(C(this,K8,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}K8=new WeakMap;var p4;class w2{constructor($,Z,Y,Q){p4.set(this,void 0),R(this,p4,$,"f"),this.options=Q,this.response=Z,this.body=Y}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new E("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,p4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(p4=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class d4 extends u0{constructor($,Z,Y){super($,Z,async(Q,J)=>new Y(Q,J.response,await u4(Q,J),J.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class k$ extends w2{constructor($,Z,Y,Q){super($,Z,Y,Q);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.first_id=Y.first_id||null,this.last_id=Y.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let Z=this.first_id;if(!Z)return null;return{...this.options,query:{...v4(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...v4(this.options.query),after_id:$}}}}class V8 extends w2{constructor($,Z,Y,Q){super($,Z,Y,Q);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.next_page=Y.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next_page;if(!$)return null;return{...this.options,query:{...v4(this.options.query),page:$}}}}var b2=()=>{if(typeof File>"u"){let{process:$}=globalThis,Z=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Z?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function p0($,Z,Y){return b2(),new File($,Z??"unknown_file",Y)}function G8($,Z){let Y=typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"";return Z?Y.split(/[\\/]/).pop()||void 0:Y}var y2=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var W1=async($,Z,Y=!0)=>{return{...$,body:await OK($.body,Z,Y)}},d6=new WeakMap;function NK($){let Z=typeof $==="function"?$:$.fetch,Y=d6.get(Z);if(Y)return Y;let Q=(async()=>{try{let J="Response"in Z?Z.Response:(await Z("data:,")).constructor,z=new FormData;if(z.toString()===await new J(z).text())return!1;return!0}catch{return!0}})();return d6.set(Z,Q),Q}var OK=async($,Z,Y=!0)=>{if(!await NK(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Q=new FormData;return await Promise.all(Object.entries($||{}).map(([J,z])=>k2(Q,J,z,Y))),Q},FK=($)=>$ instanceof Blob&&("name"in $);var k2=async($,Z,Y,Q)=>{if(Y===void 0)return;if(Y==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")$.append(Z,String(Y));else if(Y instanceof Response){let J={},z=Y.headers.get("Content-Type");if(z)J={type:z};$.append(Z,p0([await Y.blob()],G8(Y,Q),J))}else if(y2(Y))$.append(Z,p0([await new Response(h4(Y)).blob()],G8(Y,Q)));else if(FK(Y))$.append(Z,p0([Y],G8(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((J)=>k2($,Z+"[]",J,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([J,z])=>k2($,`${Z}[${J}]`,z,Q)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var c6=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",RK=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&c6($),EK=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function c4($,Z,Y){if(b2(),$=await $,Z||(Z=G8($,!0)),RK($)){if($ instanceof File&&Z==null&&Y==null)return $;return p0([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(EK($)){let J=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),p0(await _2(J),Z,Y)}let Q=await _2($);if(!Y?.type){let J=Q.find((z)=>typeof z==="object"&&("type"in z)&&z.type);if(typeof J==="string")Y={...Y,type:J}}return p0(Q,Z,Y)}async function _2($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(c6($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(y2($))for await(let Y of $)Z.push(...await _2(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${LK($)}`)}return Z}function LK($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class u{constructor($){this._client=$}}var l6=Symbol.for("brand.privateNullableHeaders");function*DK($){if(!$)return;if(l6 in $){let{values:Q,nulls:J}=$;yield*Q.entries();for(let z of J)yield[z,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(D2($))Y=$;else Z=!0,Y=Object.entries($??{});for(let Q of Y){let J=Q[0];if(typeof J!=="string")throw TypeError("expected header name to be a string");let z=D2(Q[1])?Q[1]:[Q[1]],X=!1;for(let K of z){if(K===void 0)continue;if(Z&&!X)X=!0,yield[J,null];yield[J,K]}}}var A=($)=>{let Z=new Headers,Y=new Set;for(let Q of $){let J=new Set;for(let[z,X]of DK(Q)){let K=z.toLowerCase();if(!J.has(K))Z.delete(z),J.add(K);if(X===null)Z.delete(z),Y.add(K);else Z.append(z,X),Y.delete(K)}}return{[l6]:!0,values:Z,nulls:Y}};var q8=Symbol("anthropic.sdk.stainlessHelper");function l4($){return typeof $==="object"&&$!==null&&q8 in $}function x2($,Z){let Y=new Set;if($){for(let Q of $)if(l4(Q))Y.add(Q[q8])}if(Z)for(let Q of Z){if(l4(Q))Y.add(Q[q8]);if(Array.isArray(Q.content)){for(let J of Q.content)if(l4(J))Y.add(J[q8])}}return Array.from(Y)}function o4($,Z){let Y=x2($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function o6($){if(l4($))return{"x-stainless-helper":$[q8]};return{}}function a6($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var i6=Object.freeze(Object.create(null)),PK=($=a6)=>function(Y,...Q){if(Y.length===1)return Y[0];let J=!1,z=[],X=Y.reduce((q,U,W)=>{if(/[?#]/.test(U))J=!0;let B=Q[W],M=(J?encodeURIComponent:$)(""+B);if(W!==Q.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??i6)??i6)?.toString))M=B+"",z.push({start:q.length+U.length,length:M.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return q+U+(W===Q.length?"":M)},""),K=X.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,G;while((G=V.exec(K))!==null)z.push({start:G.index,length:G[0].length,error:`Value "${G[0]}" can't be safely passed as a path parameter`});if(z.sort((q,U)=>q.start-U.start),z.length>0){let q=0,U=z.reduce((W,B)=>{let M=" ".repeat(B.start-q),N="^".repeat(B.length);return q=B.start+B.length,W+M+N},"");throw new E(`Path parameters result in path with invalid segments:
125
- ${z.map((W)=>W.error).join(`
128
+ /export Export markdown /exit Quit`)}function n$($){console.error(`smolerclaw: ${$}`),process.exit(2)}s();l();import{existsSync as M$,mkdirSync as IG,readFileSync as qY,readdirSync as HY,copyFileSync as SG}from"fs";import{homedir as wG}from"os";import{join as C0}from"path";var $2=wG(),E$=j?C0(process.env.APPDATA||C0($2,"AppData","Roaming"),"smolerclaw"):C0($2,".config","smolerclaw"),c7=j?C0(process.env.LOCALAPPDATA||C0($2,"AppData","Local"),"smolerclaw"):C0($2,".local","share","smolerclaw"),C1=C0(E$,"config.json"),N$={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:c7,toolApproval:"auto",language:"auto",maxSessionCost:0};function C$($){if(!M$($))IG($,{recursive:!0})}function WY(){if(C$(E$),C$(c7),C$(C0(c7,"sessions")),j)fG();if(!M$(C1))return P(C1,JSON.stringify(N$,null,2)),{...N$};let $;try{$=JSON.parse(qY(C1,"utf-8"))}catch{return P(C1,JSON.stringify(N$,null,2)),{...N$}}return kG({...N$,...$})}function kG($){let Z={...N$};if(typeof $.model==="string"&&$.model.trim())Z.model=$.model;if(typeof $.maxTokens==="number"&&$.maxTokens>0&&$.maxTokens<=1e5)Z.maxTokens=$.maxTokens;if(typeof $.maxHistory==="number"&&$.maxHistory>0&&$.maxHistory<=1000)Z.maxHistory=$.maxHistory;if(typeof $.systemPrompt==="string")Z.systemPrompt=$.systemPrompt;if(typeof $.skillsDir==="string"&&$.skillsDir.trim())Z.skillsDir=$.skillsDir;if(typeof $.dataDir==="string"&&$.dataDir.trim())Z.dataDir=$.dataDir;let Y=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&Y.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function o8($){C$(E$),P(C1,JSON.stringify($,null,2))}function i8(){return C1}function l7(){return E$}function fG(){let $=C0($2,".config","smolerclaw"),Z=C0($,"config.json");if(M$(Z)&&!M$(C1))try{let Y=qY(Z,"utf-8");C$(E$),P(C1,Y)}catch{}for(let Y of["plugins","materials"]){let Q=C0($,Y),z=C0(E$,Y);if(M$(Q)&&(!M$(z)||bG(z)))try{BY(Q,z)}catch{}}}function bG($){try{return HY($).length===0}catch{return!0}}function BY($,Z){C$(Z);let Y=HY($,{withFileTypes:!0});for(let Q of Y){let z=C0($,Q.name),J=C0(Z,Q.name);if(Q.isDirectory())BY(z,J);else if(Q.isFile())SG(z,J)}}import{existsSync as yG,readFileSync as _G}from"fs";import{homedir as xG}from"os";import{join as vG}from"path";var OY=vG(xG(),".claude",".credentials.json");function o7(){let $=hG();if($)return $;throw Error("Claude Code subscription not found or expired.\nInstall Claude Code with a Pro/Max subscription and run `claude` to authenticate.")}function hG(){if(!yG(OY))return null;try{let Z=JSON.parse(_G(OY,"utf-8")).claudeAiOauth;if(!Z?.accessToken)return null;if(Date.now()>Z.expiresAt-60000)return null;return{token:Z.accessToken,subscriptionType:Z.subscriptionType,expiresAt:Z.expiresAt}}catch{return null}}function u1(){try{return o7()}catch{return null}}function NY($){return`sub:${$.subscriptionType||"pro"}`}var r8=[{id:"claude-haiku-4-5-20251001",alias:"haiku",name:"Claude Haiku 4.5",contextWindow:200000,tier:"fast"},{id:"claude-sonnet-4-20250514",alias:"sonnet",name:"Claude Sonnet 4",contextWindow:200000,tier:"balanced"},{id:"claude-sonnet-4-6-20250627",alias:"sonnet-4.6",name:"Claude Sonnet 4.6",contextWindow:200000,tier:"balanced"},{id:"claude-opus-4-20250514",alias:"opus",name:"Claude Opus 4",contextWindow:200000,tier:"powerful"},{id:"claude-opus-4-6-20250318",alias:"opus-4.6",name:"Claude Opus 4.6",contextWindow:200000,tier:"powerful"}];function n8($){let Z=r8.find((J)=>J.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=r8.find((J)=>J.alias===Y);if(Q)return Q.id;let z=r8.find((J)=>J.id.includes(Y)||J.name.toLowerCase().includes(Y));if(z)return z.id;return $}function MY($){let Z=["Available models:"];for(let Y of r8){let Q=Y.id===$?" *":" ",z=Y.tier==="fast"?"\u26A1":Y.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${Q} ${Y.alias.padEnd(12)} ${z} ${Y.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
129
+ `)}function R($,Z,Y,Q,z){if(Q==="m")throw TypeError("Private method is not writable");if(Q==="a"&&!z)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!z:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?z.call($,Y):z?z.value=Y:Z.set($,Y),Y}function N($,Z,Y,Q){if(Y==="a"&&!Q)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Q:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?Q:Y==="a"?Q.call($):Q?Q.value:Z.get($)}var i7=function(){let{crypto:$}=globalThis;if($?.randomUUID)return i7=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),Y=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Q)=>(+Q^Y()&15>>+Q/4).toString(16))};function t0($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var Z2=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class L extends Error{}class $0 extends L{constructor($,Z,Y,Q){super(`${$0.makeMessage($,Z,Y)}`);this.status=$,this.headers=Q,this.requestID=Q?.get("request-id"),this.error=Z}static makeMessage($,Z,Y){let Q=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Y;if($&&Q)return`${$} ${Q}`;if($)return`${$} status code (no body)`;if(Q)return Q;return"(no status code or body)"}static generate($,Z,Y,Q){if(!$||!Q)return new p1({message:Y,cause:Z2(Z)});let z=Z;if($===400)return new Q2($,z,Y,Q);if($===401)return new z2($,z,Y,Q);if($===403)return new J2($,z,Y,Q);if($===404)return new X2($,z,Y,Q);if($===409)return new K2($,z,Y,Q);if($===422)return new G2($,z,Y,Q);if($===429)return new V2($,z,Y,Q);if($>=500)return new U2($,z,Y,Q);return new $0($,z,Y,Q)}}class U0 extends $0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class p1 extends $0{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class Y2 extends p1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class Q2 extends $0{}class z2 extends $0{}class J2 extends $0{}class X2 extends $0{}class K2 extends $0{}class G2 extends $0{}class V2 extends $0{}class U2 extends $0{}var mG=/^[a-z][a-z0-9+.-]*:/i,CY=($)=>{return mG.test($)},r7=($)=>(r7=Array.isArray,r7($)),n7=r7;function a8($){if(typeof $!=="object")return{};return $??{}}function a7($){if(!$)return!0;for(let Z in $)return!1;return!0}function EY($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var RY=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new L(`${$} must be an integer`);if(Z<0)throw new L(`${$} must be a positive integer`);return Z};var s8=($)=>{try{return JSON.parse($)}catch(Z){return}};var FY=($)=>new Promise((Z)=>setTimeout(Z,$));var E1="0.80.0";var PY=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function uG(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var pG=()=>{let $=uG();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E1,"X-Stainless-OS":jY(Deno.build.os),"X-Stainless-Arch":LY(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E1,"X-Stainless-OS":jY(globalThis.process.platform??"unknown"),"X-Stainless-Arch":LY(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=dG();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Z.browser}`,"X-Stainless-Runtime-Version":Z.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function dG(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:Y}of $){let Q=Y.exec(navigator.userAgent);if(Q){let z=Q[1]||0,J=Q[2]||0,X=Q[3]||0;return{browser:Z,version:`${z}.${J}.${X}`}}}return null}var LY=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},jY=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},AY,DY=()=>{return AY??(AY=pG())};function TY(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function s7(...$){let Z=globalThis.ReadableStream;if(typeof Z>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Z(...$)}function t8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return s7({start(){},async pull(Y){let{done:Q,value:z}=await Z.next();if(Q)Y.close();else Y.enqueue(z)},async cancel(){await Z.return?.()}})}function q2($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let Y=await Z.read();if(Y?.done)Z.releaseLock();return Y}catch(Y){throw Z.releaseLock(),Y}},async return(){let Y=Z.cancel();return Z.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function IY($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var SY=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function wY($){return Object.entries($).filter(([Z,Y])=>typeof Y<"u").map(([Z,Y])=>{if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(Y)}`;if(Y===null)return`${encodeURIComponent(Z)}=`;throw new L(`Cannot stringify type ${typeof Y}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function bY($){let Z=0;for(let z of $)Z+=z.length;let Y=new Uint8Array(Z),Q=0;for(let z of $)Y.set(z,Q),Q+=z.length;return Y}var kY;function H2($){let Z;return(kY??(Z=new globalThis.TextEncoder,kY=Z.encode.bind(Z)))($)}var fY;function t7($){let Z;return(fY??(Z=new globalThis.TextDecoder,fY=Z.decode.bind(Z)))($)}var P0,D0;class R1{constructor(){P0.set(this,void 0),D0.set(this,void 0),R(this,P0,new Uint8Array,"f"),R(this,D0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?H2($):$;R(this,P0,bY([N(this,P0,"f"),Z]),"f");let Y=[],Q;while((Q=oG(N(this,P0,"f"),N(this,D0,"f")))!=null){if(Q.carriage&&N(this,D0,"f")==null){R(this,D0,Q.index,"f");continue}if(N(this,D0,"f")!=null&&(Q.index!==N(this,D0,"f")+1||Q.carriage)){Y.push(t7(N(this,P0,"f").subarray(0,N(this,D0,"f")-1))),R(this,P0,N(this,P0,"f").subarray(N(this,D0,"f")),"f"),R(this,D0,null,"f");continue}let z=N(this,D0,"f")!==null?Q.preceding-1:Q.preceding,J=t7(N(this,P0,"f").subarray(0,z));Y.push(J),R(this,P0,N(this,P0,"f").subarray(Q.index),"f"),R(this,D0,null,"f")}return Y}flush(){if(!N(this,P0,"f").length)return[];return this.decode(`
130
+ `)}}P0=new WeakMap,D0=new WeakMap;R1.NEWLINE_CHARS=new Set([`
131
+ `,"\r"]);R1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function oG($,Z){for(let z=Z??0;z<$.length;z++){if($[z]===10)return{preceding:z,index:z+1,carriage:!1};if($[z]===13)return{preceding:z,index:z+1,carriage:!0}}return null}function yY($){for(let Q=0;Q<$.length-1;Q++){if($[Q]===10&&$[Q+1]===10)return Q+2;if($[Q]===13&&$[Q+1]===13)return Q+2;if($[Q]===13&&$[Q+1]===10&&Q+3<$.length&&$[Q+2]===13&&$[Q+3]===10)return Q+4}return-1}var $4={off:0,error:200,warn:300,info:400,debug:500},e7=($,Z,Y)=>{if(!$)return;if(EY($4,$))return $;z0(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys($4))}`);return};function W2(){}function e8($,Z,Y){if(!Z||$4[$]>$4[Y])return W2;else return Z[$].bind(Z)}var iG={error:W2,warn:W2,info:W2,debug:W2},_Y=new WeakMap;function z0($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return iG;let Q=_Y.get(Z);if(Q&&Q[0]===Y)return Q[1];let z={error:e8("error",Z,Y),warn:e8("warn",Z,Y),info:e8("info",Z,Y),debug:e8("debug",Z,Y)};return _Y.set(Z,[Y,z]),z}var e0=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,Y])=>[Z,Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":Y]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var B2;class T0{constructor($,Z,Y){this.iterator=$,B2.set(this,void 0),this.controller=Z,R(this,B2,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,z=Y?z0(Y):console;async function*J(){if(Q)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of rG($,Z)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(G){throw z.error("Could not parse message into JSON:",K.data),z.error("From chunk:",K.raw),G}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(G){throw z.error("Could not parse message into JSON:",K.data),z.error("From chunk:",K.raw),G}if(K.event==="ping")continue;if(K.event==="error")throw new $0(void 0,s8(K.data)??K.data,void 0,$.headers)}X=!0}catch(K){if(t0(K))return;throw K}finally{if(!X)Z.abort()}}return new T0(J,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*z(){let X=new R1,K=q2($);for await(let G of K)for(let V of X.decode(G))yield V;for(let G of X.flush())yield G}async function*J(){if(Q)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of z()){if(X)continue;if(K)yield JSON.parse(K)}X=!0}catch(K){if(t0(K))return;throw K}finally{if(!X)Z.abort()}}return new T0(J,Z,Y)}[(B2=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),Q=(z)=>{return{next:()=>{if(z.length===0){let J=Y.next();$.push(J),Z.push(J)}return z.shift()}}};return[new T0(()=>Q($),this.controller,N(this,B2,"f")),new T0(()=>Q(Z),this.controller,N(this,B2,"f"))]}toReadableStream(){let $=this,Z;return s7({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:z}=await Z.next();if(z)return Y.close();let J=H2(JSON.stringify(Q)+`
132
+ `);Y.enqueue(J)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*rG($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new L("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new L("Attempted to iterate over a response with no body")}let Y=new xY,Q=new R1,z=q2($.body);for await(let J of nG(z))for(let X of Q.decode(J)){let K=Y.decode(X);if(K)yield K}for(let J of Q.flush()){let X=Y.decode(J);if(X)yield X}}async function*nG($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?H2(Y):Y,z=new Uint8Array(Z.length+Q.length);z.set(Z),z.set(Q,Z.length),Z=z;let J;while((J=yY(Z))!==-1)yield Z.slice(0,J),Z=Z.slice(J)}if(Z.length>0)yield Z}class xY{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let z={event:this.event,data:this.data.join(`
133
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],z}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=aG($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function aG($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function Z4($,Z){let{response:Y,requestLogID:Q,retryOfRequestLogID:z,startTime:J}=Z,X=await(async()=>{if(Z.options.stream){if(z0($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return T0.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let G=Y.headers.get("content-type")?.split(";")[0]?.trim();if(G?.includes("application/json")||G?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let H=await Y.json();return $6(H,Y)}return await Y.text()})();return z0($).debug(`[${Q}] response parsed`,e0({retryOfRequestLogID:z,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-J})),X}function $6($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var O2;class d1 extends Promise{constructor($,Z,Y=Z4){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,O2.set(this,void 0),R(this,O2,$,"f")}_thenUnwrap($){return new d1(N(this,O2,"f"),this.responsePromise,async(Z,Y)=>$6($(await this.parseResponse(Z,Y),Y),Y.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(N(this,O2,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}O2=new WeakMap;var Y4;class Z6{constructor($,Z,Y,Q){Y4.set(this,void 0),R(this,Y4,$,"f"),this.options=Q,this.response=Z,this.body=Y}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new L("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,Y4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(Y4=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class Q4 extends d1{constructor($,Z,Y){super($,Z,async(Q,z)=>new Y(Q,z.response,await Z4(Q,z),z.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class g0 extends Z6{constructor($,Z,Y,Q){super($,Z,Y,Q);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.first_id=Y.first_id||null,this.last_id=Y.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let Z=this.first_id;if(!Z)return null;return{...this.options,query:{...a8(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...a8(this.options.query),after_id:$}}}}class N2 extends Z6{constructor($,Z,Y,Q){super($,Z,Y,Q);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.next_page=Y.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next_page;if(!$)return null;return{...this.options,query:{...a8(this.options.query),page:$}}}}var Q6=()=>{if(typeof File>"u"){let{process:$}=globalThis,Z=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Z?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function c1($,Z,Y){return Q6(),new File($,Z??"unknown_file",Y)}function M2($,Z){let Y=typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"";return Z?Y.split(/[\\/]/).pop()||void 0:Y}var z6=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var R$=async($,Z,Y=!0)=>{return{...$,body:await eG($.body,Z,Y)}},vY=new WeakMap;function tG($){let Z=typeof $==="function"?$:$.fetch,Y=vY.get(Z);if(Y)return Y;let Q=(async()=>{try{let z="Response"in Z?Z.Response:(await Z("data:,")).constructor,J=new FormData;if(J.toString()===await new z(J).text())return!1;return!0}catch{return!0}})();return vY.set(Z,Q),Q}var eG=async($,Z,Y=!0)=>{if(!await tG(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Q=new FormData;return await Promise.all(Object.entries($||{}).map(([z,J])=>Y6(Q,z,J,Y))),Q},$V=($)=>$ instanceof Blob&&("name"in $);var Y6=async($,Z,Y,Q)=>{if(Y===void 0)return;if(Y==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")$.append(Z,String(Y));else if(Y instanceof Response){let z={},J=Y.headers.get("Content-Type");if(J)z={type:J};$.append(Z,c1([await Y.blob()],M2(Y,Q),z))}else if(z6(Y))$.append(Z,c1([await new Response(t8(Y)).blob()],M2(Y,Q)));else if($V(Y))$.append(Z,c1([Y],M2(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((z)=>Y6($,Z+"[]",z,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([z,J])=>Y6($,`${Z}[${z}]`,J,Q)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var hY=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",ZV=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&hY($),YV=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function z4($,Z,Y){if(Q6(),$=await $,Z||(Z=M2($,!0)),ZV($)){if($ instanceof File&&Z==null&&Y==null)return $;return c1([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(YV($)){let z=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),c1(await J6(z),Z,Y)}let Q=await J6($);if(!Y?.type){let z=Q.find((J)=>typeof J==="object"&&("type"in J)&&J.type);if(typeof z==="string")Y={...Y,type:z}}return c1(Q,Z,Y)}async function J6($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(hY($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(z6($))for await(let Y of $)Z.push(...await J6(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${QV($)}`)}return Z}function QV($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class i{constructor($){this._client=$}}var gY=Symbol.for("brand.privateNullableHeaders");function*JV($){if(!$)return;if(gY in $){let{values:Q,nulls:z}=$;yield*Q.entries();for(let J of z)yield[J,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(n7($))Y=$;else Z=!0,Y=Object.entries($??{});for(let Q of Y){let z=Q[0];if(typeof z!=="string")throw TypeError("expected header name to be a string");let J=n7(Q[1])?Q[1]:[Q[1]],X=!1;for(let K of J){if(K===void 0)continue;if(Z&&!X)X=!0,yield[z,null];yield[z,K]}}}var T=($)=>{let Z=new Headers,Y=new Set;for(let Q of $){let z=new Set;for(let[J,X]of JV(Q)){let K=J.toLowerCase();if(!z.has(K))Z.delete(J),z.add(K);if(X===null)Z.delete(J),Y.add(K);else Z.append(J,X),Y.delete(K)}}return{[gY]:!0,values:Z,nulls:Y}};var C2=Symbol("anthropic.sdk.stainlessHelper");function J4($){return typeof $==="object"&&$!==null&&C2 in $}function X6($,Z){let Y=new Set;if($){for(let Q of $)if(J4(Q))Y.add(Q[C2])}if(Z)for(let Q of Z){if(J4(Q))Y.add(Q[C2]);if(Array.isArray(Q.content)){for(let z of Q.content)if(J4(z))Y.add(z[C2])}}return Array.from(Y)}function X4($,Z){let Y=X6($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function mY($){if(J4($))return{"x-stainless-helper":$[C2]};return{}}function pY($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var uY=Object.freeze(Object.create(null)),XV=($=pY)=>function(Y,...Q){if(Y.length===1)return Y[0];let z=!1,J=[],X=Y.reduce((U,q,H)=>{if(/[?#]/.test(q))z=!0;let B=Q[H],O=(z?encodeURIComponent:$)(""+B);if(H!==Q.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??uY)??uY)?.toString))O=B+"",J.push({start:U.length+q.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return U+q+(H===Q.length?"":O)},""),K=X.split(/[?#]/,1)[0],G=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,V;while((V=G.exec(K))!==null)J.push({start:V.index,length:V[0].length,error:`Value "${V[0]}" can't be safely passed as a path parameter`});if(J.sort((U,q)=>U.start-q.start),J.length>0){let U=0,q=J.reduce((H,B)=>{let O=" ".repeat(B.start-U),M="^".repeat(B.length);return U=B.start+B.length,H+O+M},"");throw new L(`Path parameters result in path with invalid segments:
134
+ ${J.map((H)=>H.error).join(`
126
135
  `)}
127
136
  ${X}
128
- ${U}`)}return X},m=PK(a6);class U8 extends u{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",k$,{query:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(m`/v1/files/${$}`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(m`/v1/files/${$}/content`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(m`/v1/files/${$}`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/files",W1({body:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},o6(Q.file),Z?.headers])},this._client))}}class H8 extends u{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(m`/v1/models/${$}?beta=true`,{...Y,headers:A([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models?beta=true",k$,{query:Q,...Z,headers:A([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var i4={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function n6($){return $?.output_format??$?.output_config?.format}function v2($,Z,Y){let Q=n6(Z);if(!Z||!("parse"in(Q??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text"){let z=Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return J}),parsed_output:null};return f2($,Z,Y)}function f2($,Z,Y){let Q=null,J=$.content.map((z)=>{if(z.type==="text"){let X=IK(Z,z.text);if(Q===null)Q=X;let K=Object.defineProperty({...z},"parsed_output",{value:X,enumerable:!1});return Object.defineProperty(K,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),X},enumerable:!1})}return z});return{...$,content:J,parsed_output:Q}}function IK($,Z){let Y=n6($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new E(`Failed to parse structured output: ${Q}`)}}var SK=($)=>{let Z=0,Y=[];while(Z<$.length){let Q=$[Z];if(Q==="\\"){Z++;continue}if(Q==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(Q==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(Q==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(Q==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(Q===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(Q===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(Q==='"'){let K="",V=!1;Q=$[++Z];while(Q!=='"'){if(Z===$.length){V=!0;break}if(Q==="\\"){if(Z++,Z===$.length){V=!0;break}K+=Q+$[Z],Q=$[++Z]}else K+=Q,Q=$[++Z]}if(Q=$[++Z],!V)Y.push({type:"string",value:K});continue}if(Q&&/\s/.test(Q)){Z++;continue}let z=/[0-9]/;if(Q&&z.test(Q)||Q==="-"||Q==="."){let K="";if(Q==="-")K+=Q,Q=$[++Z];while(Q&&z.test(Q)||Q===".")K+=Q,Q=$[++Z];Y.push({type:"number",value:K});continue}let X=/[a-z]/i;if(Q&&X.test(Q)){let K="";while(Q&&X.test(Q)){if(Z===$.length)break;K+=Q,Q=$[++Z]}if(K=="true"||K=="false"||K==="null")Y.push({type:"name",value:K});else{Z++;continue}continue}Z++}return Y},B1=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),B1($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),B1($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),B1($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),B1($);break;case"delimiter":return $=$.slice(0,$.length-1),B1($);break}return $},wK=($)=>{let Z=[];if($.map((Y)=>{if(Y.type==="brace")if(Y.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(Y.type==="paren")if(Y.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((Y)=>{if(Y==="}")$.push({type:"brace",value:"}"});else if(Y==="]")$.push({type:"paren",value:"]"})});return $},kK=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},a4=($)=>JSON.parse(kK(wK(B1(SK($)))));var P$,O0,M1,W8,n4,B8,M8,r4,C8,n$,N8,s4,t4,d0,e4,$7,O8,h2,r6,Z7,g2,m2,u2,s6,t6="__json_buf";function e6($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class F8{constructor($,Z){P$.add(this),this.messages=[],this.receivedMessages=[],O0.set(this,void 0),M1.set(this,null),this.controller=new AbortController,W8.set(this,void 0),n4.set(this,()=>{}),B8.set(this,()=>{}),M8.set(this,void 0),r4.set(this,()=>{}),C8.set(this,()=>{}),n$.set(this,{}),N8.set(this,!1),s4.set(this,!1),t4.set(this,!1),d0.set(this,!1),e4.set(this,void 0),$7.set(this,void 0),O8.set(this,void 0),Z7.set(this,(Y)=>{if(R(this,s4,!0,"f"),i$(Y))Y=new z$;if(Y instanceof z$)return R(this,t4,!0,"f"),this._emit("abort",Y);if(Y instanceof E)return this._emit("error",Y);if(Y instanceof Error){let Q=new E(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new E(String(Y)))}),R(this,W8,new Promise((Y,Q)=>{R(this,n4,Y,"f"),R(this,B8,Q,"f")}),"f"),R(this,M8,new Promise((Y,Q)=>{R(this,r4,Y,"f"),R(this,C8,Q,"f")}),"f"),C(this,W8,"f").catch(()=>{}),C(this,M8,"f").catch(()=>{}),R(this,M1,$,"f"),R(this,O8,Z?.logger??console,"f")}get response(){return C(this,e4,"f")}get request_id(){return C(this,$7,"f")}async withResponse(){R(this,d0,!0,"f");let $=await C(this,W8,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new F8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let J=new F8(Z,{logger:Q});for(let z of Z.messages)J._addMessageParam(z);return R(J,M1,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},C(this,Z7,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let Q=Y?.signal,J;if(Q){if(Q.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Q.addEventListener("abort",J)}try{C(this,P$,"m",g2).call(this);let{response:z,data:X}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let K of X)C(this,P$,"m",m2).call(this,K);if(X.controller.signal?.aborted)throw new z$;C(this,P$,"m",u2).call(this)}finally{if(Q&&J)Q.removeEventListener("abort",J)}}_connected($){if(this.ended)return;R(this,e4,$,"f"),R(this,$7,$?.headers.get("request-id"),"f"),C(this,n4,"f").call(this,$),this._emit("connect")}get ended(){return C(this,N8,"f")}get errored(){return C(this,s4,"f")}get aborted(){return C(this,t4,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,n$,"f")[$]||(C(this,n$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=C(this,n$,"f")[$];if(!Y)return this;let Q=Y.findIndex((J)=>J.listener===Z);if(Q>=0)Y.splice(Q,1);return this}once($,Z){return(C(this,n$,"f")[$]||(C(this,n$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,d0,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,d0,!0,"f"),await C(this,M8,"f")}get currentMessage(){return C(this,O0,"f")}async finalMessage(){return await this.done(),C(this,P$,"m",h2).call(this)}async finalText(){return await this.done(),C(this,P$,"m",r6).call(this)}_emit($,...Z){if(C(this,N8,"f"))return;if($==="end")R(this,N8,!0,"f"),C(this,r4,"f").call(this);let Y=C(this,n$,"f")[$];if(Y)C(this,n$,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!C(this,d0,"f")&&!Y?.length)Promise.reject(Q);C(this,B8,"f").call(this,Q),C(this,C8,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!C(this,d0,"f")&&!Y?.length)Promise.reject(Q);C(this,B8,"f").call(this,Q),C(this,C8,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,P$,"m",h2).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{C(this,P$,"m",g2).call(this),this._connected(null);let J=F$.fromReadableStream($,this.controller);for await(let z of J)C(this,P$,"m",m2).call(this,z);if(J.controller.signal?.aborted)throw new z$;C(this,P$,"m",u2).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(O0=new WeakMap,M1=new WeakMap,W8=new WeakMap,n4=new WeakMap,B8=new WeakMap,M8=new WeakMap,r4=new WeakMap,C8=new WeakMap,n$=new WeakMap,N8=new WeakMap,s4=new WeakMap,t4=new WeakMap,d0=new WeakMap,e4=new WeakMap,$7=new WeakMap,O8=new WeakMap,Z7=new WeakMap,P$=new WeakSet,h2=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},r6=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Y)=>Y.type==="text").map((Y)=>Y.text);if(Z.length===0)throw new E("stream ended without producing a content block with type=text");return Z.join(" ")},g2=function(){if(this.ended)return;R(this,O0,void 0,"f")},m2=function(Z){if(this.ended)return;let Y=C(this,P$,"m",s6).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let Q=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Z.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Z.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(e6(Q)&&Q.input)this._emit("inputJson",Z.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Z.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}case"compaction_delta":{if(Q.type==="compaction"&&Q.content)this._emit("compaction",Q.content);break}default:$3(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(v2(Y,C(this,M1,"f"),{logger:C(this,O8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,O0,Y,"f");break}case"content_block_start":case"message_delta":break}},u2=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let Z=C(this,O0,"f");if(!Z)throw new E("request ended without sending any chunks");return R(this,O0,void 0,"f"),v2(Z,C(this,M1,"f"),{logger:C(this,O8,"f")})},s6=function(Z){let Y=C(this,O0,"f");if(Z.type==="message_start"){if(Y)throw new E(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new E(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Y;case"message_delta":if(Y.container=Z.delta.container,Y.stop_reason=Z.delta.stop_reason,Y.stop_sequence=Z.delta.stop_sequence,Y.usage.output_tokens=Z.usage.output_tokens,Y.context_management=Z.context_management,Z.usage.input_tokens!=null)Y.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Y.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Y.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Y.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)Y.usage.iterations=Z.usage.iterations;return Y;case"content_block_start":return Y.content.push(Z.content_block),Y;case"content_block_delta":{let Q=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,text:(Q.text||"")+Z.delta.text};break}case"citations_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,citations:[...Q.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Q&&e6(Q)){let J=Q[t6]||"";J+=Z.delta.partial_json;let z={...Q};if(Object.defineProperty(z,t6,{value:J,enumerable:!1,writable:!0}),J)try{z.input=a4(J)}catch(X){let K=new E(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${X}. JSON: ${J}`);C(this,Z7,"f").call(this,K)}Y.content[Z.index]=z}break}case"thinking_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,thinking:Q.thinking+Z.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,signature:Z.delta.signature};break}case"compaction_delta":{if(Q?.type==="compaction")Y.content[Z.index]={...Q,content:(Q.content||"")+Z.delta.content};break}default:$3(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(Q)=>{let J=Z.shift();if(J)J.resolve(Q);else $.push(Q)}),this.on("end",()=>{Y=!0;for(let Q of Z)Q.resolve(void 0);Z.length=0}),this.on("abort",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),this.on("error",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,z)=>Z.push({resolve:J,reject:z})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new F$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function $3($){}class C1 extends Error{constructor($){let Z=typeof $==="string"?$:$.map((Y)=>{if(Y.type==="text")return Y.text;return`[${Y.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var Z3=1e5,Y3=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
137
+ ${q}`)}return X},o=XV(pY);class E2 extends i{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",g0,{query:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(o`/v1/files/${$}`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/files/${$}/content`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/files/${$}`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/files",R$({body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},mY(Q.file),Z?.headers])},this._client))}}class R2 extends i{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/models/${$}?beta=true`,{...Y,headers:T([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models?beta=true",g0,{query:Q,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var K4={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function dY($){return $?.output_format??$?.output_config?.format}function K6($,Z,Y){let Q=dY(Z);if(!Z||!("parse"in(Q??{})))return{...$,content:$.content.map((z)=>{if(z.type==="text"){let J=Object.defineProperty({...z},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(J,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return z}),parsed_output:null};return G6($,Z,Y)}function G6($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=VV(Z,J.text);if(Q===null)Q=X;let K=Object.defineProperty({...J},"parsed_output",{value:X,enumerable:!1});return Object.defineProperty(K,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),X},enumerable:!1})}return J});return{...$,content:z,parsed_output:Q}}function VV($,Z){let Y=dY($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new L(`Failed to parse structured output: ${Q}`)}}var UV=($)=>{let Z=0,Y=[];while(Z<$.length){let Q=$[Z];if(Q==="\\"){Z++;continue}if(Q==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(Q==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(Q==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(Q==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(Q===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(Q===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(Q==='"'){let K="",G=!1;Q=$[++Z];while(Q!=='"'){if(Z===$.length){G=!0;break}if(Q==="\\"){if(Z++,Z===$.length){G=!0;break}K+=Q+$[Z],Q=$[++Z]}else K+=Q,Q=$[++Z]}if(Q=$[++Z],!G)Y.push({type:"string",value:K});continue}if(Q&&/\s/.test(Q)){Z++;continue}let J=/[0-9]/;if(Q&&J.test(Q)||Q==="-"||Q==="."){let K="";if(Q==="-")K+=Q,Q=$[++Z];while(Q&&J.test(Q)||Q===".")K+=Q,Q=$[++Z];Y.push({type:"number",value:K});continue}let X=/[a-z]/i;if(Q&&X.test(Q)){let K="";while(Q&&X.test(Q)){if(Z===$.length)break;K+=Q,Q=$[++Z]}if(K=="true"||K=="false"||K==="null")Y.push({type:"name",value:K});else{Z++;continue}continue}Z++}return Y},F$=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),F$($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),F$($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),F$($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),F$($);break;case"delimiter":return $=$.slice(0,$.length-1),F$($);break}return $},qV=($)=>{let Z=[];if($.map((Y)=>{if(Y.type==="brace")if(Y.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(Y.type==="paren")if(Y.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((Y)=>{if(Y==="}")$.push({type:"brace",value:"}"});else if(Y==="]")$.push({type:"paren",value:"]"})});return $},HV=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},G4=($)=>JSON.parse(HV(qV(F$(UV($)))));var f0,F1,L$,F2,V4,L2,j2,U4,A2,$1,P2,q4,H4,l1,W4,B4,D2,V6,cY,O4,U6,q6,H6,lY,oY="__json_buf";function iY($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class T2{constructor($,Z){f0.add(this),this.messages=[],this.receivedMessages=[],F1.set(this,void 0),L$.set(this,null),this.controller=new AbortController,F2.set(this,void 0),V4.set(this,()=>{}),L2.set(this,()=>{}),j2.set(this,void 0),U4.set(this,()=>{}),A2.set(this,()=>{}),$1.set(this,{}),P2.set(this,!1),q4.set(this,!1),H4.set(this,!1),l1.set(this,!1),W4.set(this,void 0),B4.set(this,void 0),D2.set(this,void 0),O4.set(this,(Y)=>{if(R(this,q4,!0,"f"),t0(Y))Y=new U0;if(Y instanceof U0)return R(this,H4,!0,"f"),this._emit("abort",Y);if(Y instanceof L)return this._emit("error",Y);if(Y instanceof Error){let Q=new L(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new L(String(Y)))}),R(this,F2,new Promise((Y,Q)=>{R(this,V4,Y,"f"),R(this,L2,Q,"f")}),"f"),R(this,j2,new Promise((Y,Q)=>{R(this,U4,Y,"f"),R(this,A2,Q,"f")}),"f"),N(this,F2,"f").catch(()=>{}),N(this,j2,"f").catch(()=>{}),R(this,L$,$,"f"),R(this,D2,Z?.logger??console,"f")}get response(){return N(this,W4,"f")}get request_id(){return N(this,B4,"f")}async withResponse(){R(this,l1,!0,"f");let $=await N(this,F2,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new T2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new T2(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return R(z,L$,{...Z,stream:!0},"f"),z._run(()=>z._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},N(this,O4,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let Q=Y?.signal,z;if(Q){if(Q.aborted)this.controller.abort();z=this.controller.abort.bind(this.controller),Q.addEventListener("abort",z)}try{N(this,f0,"m",U6).call(this);let{response:J,data:X}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(J);for await(let K of X)N(this,f0,"m",q6).call(this,K);if(X.controller.signal?.aborted)throw new U0;N(this,f0,"m",H6).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;R(this,W4,$,"f"),R(this,B4,$?.headers.get("request-id"),"f"),N(this,V4,"f").call(this,$),this._emit("connect")}get ended(){return N(this,P2,"f")}get errored(){return N(this,q4,"f")}get aborted(){return N(this,H4,"f")}abort(){this.controller.abort()}on($,Z){return(N(this,$1,"f")[$]||(N(this,$1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=N(this,$1,"f")[$];if(!Y)return this;let Q=Y.findIndex((z)=>z.listener===Z);if(Q>=0)Y.splice(Q,1);return this}once($,Z){return(N(this,$1,"f")[$]||(N(this,$1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,l1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,l1,!0,"f"),await N(this,j2,"f")}get currentMessage(){return N(this,F1,"f")}async finalMessage(){return await this.done(),N(this,f0,"m",V6).call(this)}async finalText(){return await this.done(),N(this,f0,"m",cY).call(this)}_emit($,...Z){if(N(this,P2,"f"))return;if($==="end")R(this,P2,!0,"f"),N(this,U4,"f").call(this);let Y=N(this,$1,"f")[$];if(Y)N(this,$1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!N(this,l1,"f")&&!Y?.length)Promise.reject(Q);N(this,L2,"f").call(this,Q),N(this,A2,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!N(this,l1,"f")&&!Y?.length)Promise.reject(Q);N(this,L2,"f").call(this,Q),N(this,A2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",N(this,f0,"m",V6).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{N(this,f0,"m",U6).call(this),this._connected(null);let z=T0.fromReadableStream($,this.controller);for await(let J of z)N(this,f0,"m",q6).call(this,J);if(z.controller.signal?.aborted)throw new U0;N(this,f0,"m",H6).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(F1=new WeakMap,L$=new WeakMap,F2=new WeakMap,V4=new WeakMap,L2=new WeakMap,j2=new WeakMap,U4=new WeakMap,A2=new WeakMap,$1=new WeakMap,P2=new WeakMap,q4=new WeakMap,H4=new WeakMap,l1=new WeakMap,W4=new WeakMap,B4=new WeakMap,D2=new WeakMap,O4=new WeakMap,f0=new WeakSet,V6=function(){if(this.receivedMessages.length===0)throw new L("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},cY=function(){if(this.receivedMessages.length===0)throw new L("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Y)=>Y.type==="text").map((Y)=>Y.text);if(Z.length===0)throw new L("stream ended without producing a content block with type=text");return Z.join(" ")},U6=function(){if(this.ended)return;R(this,F1,void 0,"f")},q6=function(Z){if(this.ended)return;let Y=N(this,f0,"m",lY).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let Q=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Z.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Z.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(iY(Q)&&Q.input)this._emit("inputJson",Z.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Z.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}case"compaction_delta":{if(Q.type==="compaction"&&Q.content)this._emit("compaction",Q.content);break}default:rY(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(K6(Y,N(this,L$,"f"),{logger:N(this,D2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,F1,Y,"f");break}case"content_block_start":case"message_delta":break}},H6=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");let Z=N(this,F1,"f");if(!Z)throw new L("request ended without sending any chunks");return R(this,F1,void 0,"f"),K6(Z,N(this,L$,"f"),{logger:N(this,D2,"f")})},lY=function(Z){let Y=N(this,F1,"f");if(Z.type==="message_start"){if(Y)throw new L(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new L(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Y;case"message_delta":if(Y.container=Z.delta.container,Y.stop_reason=Z.delta.stop_reason,Y.stop_sequence=Z.delta.stop_sequence,Y.usage.output_tokens=Z.usage.output_tokens,Y.context_management=Z.context_management,Z.usage.input_tokens!=null)Y.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Y.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Y.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Y.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)Y.usage.iterations=Z.usage.iterations;return Y;case"content_block_start":return Y.content.push(Z.content_block),Y;case"content_block_delta":{let Q=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,text:(Q.text||"")+Z.delta.text};break}case"citations_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,citations:[...Q.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Q&&iY(Q)){let z=Q[oY]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,oY,{value:z,enumerable:!1,writable:!0}),z)try{J.input=G4(z)}catch(X){let K=new L(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${X}. JSON: ${z}`);N(this,O4,"f").call(this,K)}Y.content[Z.index]=J}break}case"thinking_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,thinking:Q.thinking+Z.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,signature:Z.delta.signature};break}case"compaction_delta":{if(Q?.type==="compaction")Y.content[Z.index]={...Q,content:(Q.content||"")+Z.delta.content};break}default:rY(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(Q)=>{let z=Z.shift();if(z)z.resolve(Q);else $.push(Q)}),this.on("end",()=>{Y=!0;for(let Q of Z)Q.resolve(void 0);Z.length=0}),this.on("abort",(Q)=>{Y=!0;for(let z of Z)z.reject(Q);Z.length=0}),this.on("error",(Q)=>{Y=!0;for(let z of Z)z.reject(Q);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((z,J)=>Z.push({resolve:z,reject:J})).then((z)=>z?{value:z,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new T0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function rY($){}class j$ extends Error{constructor($){let Z=typeof $==="string"?$:$.map((Y)=>{if(Y.type==="text")return Y.text;return`[${Y.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var nY=1e5,aY=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
129
138
  1. Task Overview
130
139
  The user's core request and success criteria
131
140
  Any clarifications or constraints they specified
@@ -147,44 +156,44 @@ User preferences or style requirements
147
156
  Domain-specific details that aren't obvious
148
157
  Any promises made to the user
149
158
  Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
150
- Wrap your summary in <summary></summary> tags.`;var R8,N1,c0,a,E8,R$,r$,F0,L8,Q3,p2;function J3(){let $,Z;return{promise:new Promise((Q,J)=>{$=Q,Z=J}),resolve:$,reject:Z}}class j8{constructor($,Z,Y){R8.add(this),this.client=$,N1.set(this,!1),c0.set(this,!1),a.set(this,void 0),E8.set(this,void 0),R$.set(this,void 0),r$.set(this,void 0),F0.set(this,void 0),L8.set(this,0),R(this,a,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let J=["BetaToolRunner",...x2(Z.tools,Z.messages)].join(", ");R(this,E8,{...Y,headers:A([{"x-stainless-helper":J},Y?.headers])},"f"),R(this,F0,J3(),"f")}async*[(N1=new WeakMap,c0=new WeakMap,a=new WeakMap,E8=new WeakMap,R$=new WeakMap,r$=new WeakMap,F0=new WeakMap,L8=new WeakMap,R8=new WeakSet,Q3=async function(){let Z=C(this,a,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(C(this,R$,"f")!==void 0)try{let V=await C(this,R$,"f");Y=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Q=Z.contextTokenThreshold??Z3;if(Y<Q)return!1;let J=Z.model??C(this,a,"f").params.model,z=Z.summaryPrompt??Y3,X=C(this,a,"f").params.messages;if(X[X.length-1].role==="assistant"){let V=X[X.length-1];if(Array.isArray(V.content)){let G=V.content.filter((q)=>q.type!=="tool_use");if(G.length===0)X.pop();else V.content=G}}let K=await this.client.beta.messages.create({model:J,messages:[...X,{role:"user",content:[{type:"text",text:z}]}],max_tokens:C(this,a,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(K.content[0]?.type!=="text")throw new E("Expected text response for compaction");return C(this,a,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(C(this,N1,"f"))throw new E("Cannot iterate over a consumed stream");R(this,N1,!0,"f"),R(this,c0,!0,"f"),R(this,r$,void 0,"f");try{while(!0){let Z;try{if(C(this,a,"f").params.max_iterations&&C(this,L8,"f")>=C(this,a,"f").params.max_iterations)break;R(this,c0,!1,"f"),R(this,r$,void 0,"f"),R(this,L8,($=C(this,L8,"f"),$++,$),"f"),R(this,R$,void 0,"f");let{max_iterations:Y,compactionControl:Q,...J}=C(this,a,"f").params;if(J.stream)Z=this.client.beta.messages.stream({...J},C(this,E8,"f")),R(this,R$,Z.finalMessage(),"f"),C(this,R$,"f").catch(()=>{}),yield Z;else R(this,R$,this.client.beta.messages.create({...J,stream:!1},C(this,E8,"f")),"f"),yield C(this,R$,"f");if(!await C(this,R8,"m",Q3).call(this)){if(!C(this,c0,"f")){let{role:K,content:V}=await C(this,R$,"f");C(this,a,"f").params.messages.push({role:K,content:V})}let X=await C(this,R8,"m",p2).call(this,C(this,a,"f").params.messages.at(-1));if(X)C(this,a,"f").params.messages.push(X);else if(!C(this,c0,"f"))break}}finally{if(Z)Z.abort()}}if(!C(this,R$,"f"))throw new E("ToolRunner concluded without a message from the server");C(this,F0,"f").resolve(await C(this,R$,"f"))}catch(Z){throw R(this,N1,!1,"f"),C(this,F0,"f").promise.catch(()=>{}),C(this,F0,"f").reject(Z),R(this,F0,J3(),"f"),Z}}setMessagesParams($){if(typeof $==="function")C(this,a,"f").params=$(C(this,a,"f").params);else C(this,a,"f").params=$;R(this,c0,!0,"f"),R(this,r$,void 0,"f")}async generateToolResponse(){let $=await C(this,R$,"f")??this.params.messages.at(-1);if(!$)return null;return C(this,R8,"m",p2).call(this,$)}done(){return C(this,F0,"f").promise}async runUntilDone(){if(!C(this,N1,"f"))for await(let $ of this);return this.done()}get params(){return C(this,a,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}p2=async function(Z){if(C(this,r$,"f")!==void 0)return C(this,r$,"f");return R(this,r$,bK(C(this,a,"f").params,Z),"f"),C(this,r$,"f")};async function bK($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Y=Z.content.filter((J)=>J.type==="tool_use");if(Y.length===0)return null;return{role:"user",content:await Promise.all(Y.map(async(J)=>{let z=$.tools.find((X)=>("name"in X?X.name:X.mcp_server_name)===J.name);if(!z||!("run"in z))return{type:"tool_result",tool_use_id:J.id,content:`Error: Tool '${J.name}' not found`,is_error:!0};try{let X=J.input;if("parse"in z&&z.parse)X=z.parse(X);let K=await z.run(X);return{type:"tool_result",tool_use_id:J.id,content:K}}catch(X){return{type:"tool_result",tool_use_id:J.id,content:X instanceof C1?X.content:`Error: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}))}}class O1{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new N0;for await(let Z of this.iterator)for(let Y of $.decode(Z))yield JSON.parse(Y);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new E("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new E("Attempted to iterate over a response with no body")}return new O1(Q8($.body),Z)}}class D8 extends u{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(m`/v1/messages/batches/${$}?beta=true`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",k$,{query:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(m`/v1/messages/batches/${$}?beta=true`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:Q}=Z??{};return this._client.post(m`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}async results($,Z={},Y){let Q=await this.retrieve($);if(!Q.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);let{betas:J}=Z??{};return this._client.get(Q.results_url,{...Y,headers:A([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((z,X)=>O1.fromResponse(X.response,X.controller))}}var z3={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},_K=["claude-opus-4-6"];class R0 extends u{constructor(){super(...arguments);this.batches=new D8(this._client)}create($,Z){let Y=X3($),{betas:Q,...J}=Y;if(J.model in z3)console.warn(`The model '${J.model}' is deprecated and will reach end-of-life on ${z3[J.model]}
151
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(J.model in _K&&J.thinking&&J.thinking.type==="enabled")console.warn(`Using Claude with ${J.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let z=this._client._options.timeout;if(!J.stream&&z==null){let K=i4[J.model]??void 0;z=this._client.calculateNonstreamingTimeout(J.max_tokens,K)}let X=o4(J.tools,J.messages);return this._client.post("/v1/messages?beta=true",{body:J,timeout:z??600000,...Z,headers:A([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:A([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>f2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return F8.createMessage(this,$,Z)}countTokens($,Z){let Y=X3($),{betas:Q,...J}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:J,...Z,headers:A([{"anthropic-beta":[...Q??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new j8(this._client,$,Z)}}function X3($){if(!$.output_format)return $;if($.output_config?.format)throw new E("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...Y}=$;return{...Y,output_config:{...$.output_config,format:Z}}}R0.Batches=D8;R0.BetaToolRunner=j8;R0.ToolError=C1;class P8 extends u{create($,Z={},Y){let{betas:Q,...J}=Z??{};return this._client.post(m`/v1/skills/${$}/versions?beta=true`,W1({body:J,...Y,headers:A([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve($,Z,Y){let{skill_id:Q,betas:J}=Z;return this._client.get(m`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:A([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:Q,...J}=Z??{};return this._client.getAPIList(m`/v1/skills/${$}/versions?beta=true`,V8,{query:J,...Y,headers:A([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:Q,betas:J}=Z;return this._client.delete(m`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:A([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class F1 extends u{constructor(){super(...arguments);this.versions=new P8(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",W1({body:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(m`/v1/skills/${$}?beta=true`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/skills?beta=true",V8,{query:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(m`/v1/skills/${$}?beta=true`,{...Y,headers:A([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}F1.Versions=P8;class _$ extends u{constructor(){super(...arguments);this.models=new H8(this._client),this.messages=new R0(this._client),this.files=new U8(this._client),this.skills=new F1(this._client)}}_$.Models=H8;_$.Messages=R0;_$.Files=U8;_$.Skills=F1;class R1 extends u{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Z,headers:A([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function K3($){return $?.output_config?.format}function d2($,Z,Y){let Q=K3(Z);if(!Z||!("parse"in(Q??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text")return Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return J}),parsed_output:null};return c2($,Z,Y)}function c2($,Z,Y){let Q=null,J=$.content.map((z)=>{if(z.type==="text"){let X=hK(Z,z.text);if(Q===null)Q=X;return Object.defineProperty({...z},"parsed_output",{value:X,enumerable:!1})}return z});return{...$,content:J,parsed_output:Q}}function hK($,Z){let Y=K3($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new E(`Failed to parse structured output: ${Q}`)}}var A$,E0,E1,A8,Y7,T8,I8,Q7,S8,s$,w8,J7,z7,l0,X7,K7,k8,l2,V3,o2,i2,a2,n2,G3,q3="__json_buf";function U3($){return $.type==="tool_use"||$.type==="server_tool_use"}class b8{constructor($,Z){A$.add(this),this.messages=[],this.receivedMessages=[],E0.set(this,void 0),E1.set(this,null),this.controller=new AbortController,A8.set(this,void 0),Y7.set(this,()=>{}),T8.set(this,()=>{}),I8.set(this,void 0),Q7.set(this,()=>{}),S8.set(this,()=>{}),s$.set(this,{}),w8.set(this,!1),J7.set(this,!1),z7.set(this,!1),l0.set(this,!1),X7.set(this,void 0),K7.set(this,void 0),k8.set(this,void 0),o2.set(this,(Y)=>{if(R(this,J7,!0,"f"),i$(Y))Y=new z$;if(Y instanceof z$)return R(this,z7,!0,"f"),this._emit("abort",Y);if(Y instanceof E)return this._emit("error",Y);if(Y instanceof Error){let Q=new E(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new E(String(Y)))}),R(this,A8,new Promise((Y,Q)=>{R(this,Y7,Y,"f"),R(this,T8,Q,"f")}),"f"),R(this,I8,new Promise((Y,Q)=>{R(this,Q7,Y,"f"),R(this,S8,Q,"f")}),"f"),C(this,A8,"f").catch(()=>{}),C(this,I8,"f").catch(()=>{}),R(this,E1,$,"f"),R(this,k8,Z?.logger??console,"f")}get response(){return C(this,X7,"f")}get request_id(){return C(this,K7,"f")}async withResponse(){R(this,l0,!0,"f");let $=await C(this,A8,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new b8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let J=new b8(Z,{logger:Q});for(let z of Z.messages)J._addMessageParam(z);return R(J,E1,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},C(this,o2,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let Q=Y?.signal,J;if(Q){if(Q.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Q.addEventListener("abort",J)}try{C(this,A$,"m",i2).call(this);let{response:z,data:X}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let K of X)C(this,A$,"m",a2).call(this,K);if(X.controller.signal?.aborted)throw new z$;C(this,A$,"m",n2).call(this)}finally{if(Q&&J)Q.removeEventListener("abort",J)}}_connected($){if(this.ended)return;R(this,X7,$,"f"),R(this,K7,$?.headers.get("request-id"),"f"),C(this,Y7,"f").call(this,$),this._emit("connect")}get ended(){return C(this,w8,"f")}get errored(){return C(this,J7,"f")}get aborted(){return C(this,z7,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,s$,"f")[$]||(C(this,s$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=C(this,s$,"f")[$];if(!Y)return this;let Q=Y.findIndex((J)=>J.listener===Z);if(Q>=0)Y.splice(Q,1);return this}once($,Z){return(C(this,s$,"f")[$]||(C(this,s$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,l0,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,l0,!0,"f"),await C(this,I8,"f")}get currentMessage(){return C(this,E0,"f")}async finalMessage(){return await this.done(),C(this,A$,"m",l2).call(this)}async finalText(){return await this.done(),C(this,A$,"m",V3).call(this)}_emit($,...Z){if(C(this,w8,"f"))return;if($==="end")R(this,w8,!0,"f"),C(this,Q7,"f").call(this);let Y=C(this,s$,"f")[$];if(Y)C(this,s$,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!C(this,l0,"f")&&!Y?.length)Promise.reject(Q);C(this,T8,"f").call(this,Q),C(this,S8,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!C(this,l0,"f")&&!Y?.length)Promise.reject(Q);C(this,T8,"f").call(this,Q),C(this,S8,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,A$,"m",l2).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{C(this,A$,"m",i2).call(this),this._connected(null);let J=F$.fromReadableStream($,this.controller);for await(let z of J)C(this,A$,"m",a2).call(this,z);if(J.controller.signal?.aborted)throw new z$;C(this,A$,"m",n2).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(E0=new WeakMap,E1=new WeakMap,A8=new WeakMap,Y7=new WeakMap,T8=new WeakMap,I8=new WeakMap,Q7=new WeakMap,S8=new WeakMap,s$=new WeakMap,w8=new WeakMap,J7=new WeakMap,z7=new WeakMap,l0=new WeakMap,X7=new WeakMap,K7=new WeakMap,k8=new WeakMap,o2=new WeakMap,A$=new WeakSet,l2=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},V3=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Y)=>Y.type==="text").map((Y)=>Y.text);if(Z.length===0)throw new E("stream ended without producing a content block with type=text");return Z.join(" ")},i2=function(){if(this.ended)return;R(this,E0,void 0,"f")},a2=function(Z){if(this.ended)return;let Y=C(this,A$,"m",G3).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let Q=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Z.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Z.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(U3(Q)&&Q.input)this._emit("inputJson",Z.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Z.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:H3(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(d2(Y,C(this,E1,"f"),{logger:C(this,k8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,E0,Y,"f");break}case"content_block_start":case"message_delta":break}},n2=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let Z=C(this,E0,"f");if(!Z)throw new E("request ended without sending any chunks");return R(this,E0,void 0,"f"),d2(Z,C(this,E1,"f"),{logger:C(this,k8,"f")})},G3=function(Z){let Y=C(this,E0,"f");if(Z.type==="message_start"){if(Y)throw new E(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new E(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Y;case"message_delta":if(Y.stop_reason=Z.delta.stop_reason,Y.stop_sequence=Z.delta.stop_sequence,Y.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)Y.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Y.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Y.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Y.usage.server_tool_use=Z.usage.server_tool_use;return Y;case"content_block_start":return Y.content.push({...Z.content_block}),Y;case"content_block_delta":{let Q=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,text:(Q.text||"")+Z.delta.text};break}case"citations_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,citations:[...Q.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Q&&U3(Q)){let J=Q[q3]||"";J+=Z.delta.partial_json;let z={...Q};if(Object.defineProperty(z,q3,{value:J,enumerable:!1,writable:!0}),J)z.input=a4(J);Y.content[Z.index]=z}break}case"thinking_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,thinking:Q.thinking+Z.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,signature:Z.delta.signature};break}default:H3(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(Q)=>{let J=Z.shift();if(J)J.resolve(Q);else $.push(Q)}),this.on("end",()=>{Y=!0;for(let Q of Z)Q.resolve(void 0);Z.length=0}),this.on("abort",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),this.on("error",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,z)=>Z.push({resolve:J,reject:z})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new F$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function H3($){}class y8 extends u{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(m`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",k$,{query:$,...Z})}delete($,Z){return this._client.delete(m`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(m`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:A([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,J)=>O1.fromResponse(J.response,J.controller))}}class o0 extends u{constructor(){super(...arguments);this.batches=new y8(this._client)}create($,Z){if($.model in W3)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${W3[$.model]}
152
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in mK&&$.thinking&&$.thinking.type==="enabled")console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let Y=this._client._options.timeout;if(!$.stream&&Y==null){let J=i4[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,J)}let Q=o4($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:A([Q,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>c2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return b8.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var W3={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026"},mK=["claude-opus-4-6"];o0.Batches=y8;class L1 extends u{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(m`/v1/models/${$}`,{...Y,headers:A([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models",k$,{query:Q,...Z,headers:A([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var _8=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var r2,s2,V7,B3,M3="\\n\\nHuman:",C3="\\n\\nAssistant:";class d{constructor({baseURL:$=_8("ANTHROPIC_BASE_URL"),apiKey:Z=_8("ANTHROPIC_API_KEY")??null,authToken:Y=_8("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){r2.add(this),V7.set(this,void 0);let J={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!J.dangerouslyAllowBrowser&&k6())throw new E(`It looks like you're running in a browser-like environment.
159
+ Wrap your summary in <summary></summary> tags.`;var I2,A$,o1,Z0,S2,I0,Z1,L1,w2,sY,W6;function tY(){let $,Z;return{promise:new Promise((Q,z)=>{$=Q,Z=z}),resolve:$,reject:Z}}class k2{constructor($,Z,Y){I2.add(this),this.client=$,A$.set(this,!1),o1.set(this,!1),Z0.set(this,void 0),S2.set(this,void 0),I0.set(this,void 0),Z1.set(this,void 0),L1.set(this,void 0),w2.set(this,0),R(this,Z0,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let z=["BetaToolRunner",...X6(Z.tools,Z.messages)].join(", ");R(this,S2,{...Y,headers:T([{"x-stainless-helper":z},Y?.headers])},"f"),R(this,L1,tY(),"f")}async*[(A$=new WeakMap,o1=new WeakMap,Z0=new WeakMap,S2=new WeakMap,I0=new WeakMap,Z1=new WeakMap,L1=new WeakMap,w2=new WeakMap,I2=new WeakSet,sY=async function(){let Z=N(this,Z0,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(N(this,I0,"f")!==void 0)try{let G=await N(this,I0,"f");Y=G.usage.input_tokens+(G.usage.cache_creation_input_tokens??0)+(G.usage.cache_read_input_tokens??0)+G.usage.output_tokens}catch{return!1}let Q=Z.contextTokenThreshold??nY;if(Y<Q)return!1;let z=Z.model??N(this,Z0,"f").params.model,J=Z.summaryPrompt??aY,X=N(this,Z0,"f").params.messages;if(X[X.length-1].role==="assistant"){let G=X[X.length-1];if(Array.isArray(G.content)){let V=G.content.filter((U)=>U.type!=="tool_use");if(V.length===0)X.pop();else G.content=V}}let K=await this.client.beta.messages.create({model:z,messages:[...X,{role:"user",content:[{type:"text",text:J}]}],max_tokens:N(this,Z0,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(K.content[0]?.type!=="text")throw new L("Expected text response for compaction");return N(this,Z0,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(N(this,A$,"f"))throw new L("Cannot iterate over a consumed stream");R(this,A$,!0,"f"),R(this,o1,!0,"f"),R(this,Z1,void 0,"f");try{while(!0){let Z;try{if(N(this,Z0,"f").params.max_iterations&&N(this,w2,"f")>=N(this,Z0,"f").params.max_iterations)break;R(this,o1,!1,"f"),R(this,Z1,void 0,"f"),R(this,w2,($=N(this,w2,"f"),$++,$),"f"),R(this,I0,void 0,"f");let{max_iterations:Y,compactionControl:Q,...z}=N(this,Z0,"f").params;if(z.stream)Z=this.client.beta.messages.stream({...z},N(this,S2,"f")),R(this,I0,Z.finalMessage(),"f"),N(this,I0,"f").catch(()=>{}),yield Z;else R(this,I0,this.client.beta.messages.create({...z,stream:!1},N(this,S2,"f")),"f"),yield N(this,I0,"f");if(!await N(this,I2,"m",sY).call(this)){if(!N(this,o1,"f")){let{role:K,content:G}=await N(this,I0,"f");N(this,Z0,"f").params.messages.push({role:K,content:G})}let X=await N(this,I2,"m",W6).call(this,N(this,Z0,"f").params.messages.at(-1));if(X)N(this,Z0,"f").params.messages.push(X);else if(!N(this,o1,"f"))break}}finally{if(Z)Z.abort()}}if(!N(this,I0,"f"))throw new L("ToolRunner concluded without a message from the server");N(this,L1,"f").resolve(await N(this,I0,"f"))}catch(Z){throw R(this,A$,!1,"f"),N(this,L1,"f").promise.catch(()=>{}),N(this,L1,"f").reject(Z),R(this,L1,tY(),"f"),Z}}setMessagesParams($){if(typeof $==="function")N(this,Z0,"f").params=$(N(this,Z0,"f").params);else N(this,Z0,"f").params=$;R(this,o1,!0,"f"),R(this,Z1,void 0,"f")}async generateToolResponse(){let $=await N(this,I0,"f")??this.params.messages.at(-1);if(!$)return null;return N(this,I2,"m",W6).call(this,$)}done(){return N(this,L1,"f").promise}async runUntilDone(){if(!N(this,A$,"f"))for await(let $ of this);return this.done()}get params(){return N(this,Z0,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}W6=async function(Z){if(N(this,Z1,"f")!==void 0)return N(this,Z1,"f");return R(this,Z1,WV(N(this,Z0,"f").params,Z),"f"),N(this,Z1,"f")};async function WV($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Y=Z.content.filter((z)=>z.type==="tool_use");if(Y.length===0)return null;return{role:"user",content:await Promise.all(Y.map(async(z)=>{let J=$.tools.find((X)=>("name"in X?X.name:X.mcp_server_name)===z.name);if(!J||!("run"in J))return{type:"tool_result",tool_use_id:z.id,content:`Error: Tool '${z.name}' not found`,is_error:!0};try{let X=z.input;if("parse"in J&&J.parse)X=J.parse(X);let K=await J.run(X);return{type:"tool_result",tool_use_id:z.id,content:K}}catch(X){return{type:"tool_result",tool_use_id:z.id,content:X instanceof j$?X.content:`Error: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}))}}class P${constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new R1;for await(let Z of this.iterator)for(let Y of $.decode(Z))yield JSON.parse(Y);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new L("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new L("Attempted to iterate over a response with no body")}return new P$(q2($.body),Z)}}class f2 extends i{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/messages/batches/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",g0,{query:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(o`/v1/messages/batches/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:Q}=Z??{};return this._client.post(o`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}async results($,Z={},Y){let Q=await this.retrieve($);if(!Q.results_url)throw new L(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);let{betas:z}=Z??{};return this._client.get(Q.results_url,{...Y,headers:T([{"anthropic-beta":[...z??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,X)=>P$.fromResponse(X.response,X.controller))}}var eY={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},OV=["claude-opus-4-6"];class j1 extends i{constructor(){super(...arguments);this.batches=new f2(this._client)}create($,Z){let Y=$Q($),{betas:Q,...z}=Y;if(z.model in eY)console.warn(`The model '${z.model}' is deprecated and will reach end-of-life on ${eY[z.model]}
160
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(z.model in OV&&z.thinking&&z.thinking.type==="enabled")console.warn(`Using Claude with ${z.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let J=this._client._options.timeout;if(!z.stream&&J==null){let K=K4[z.model]??void 0;J=this._client.calculateNonstreamingTimeout(z.max_tokens,K)}let X=X4(z.tools,z.messages);return this._client.post("/v1/messages?beta=true",{body:z,timeout:J??600000,...Z,headers:T([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:T([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>G6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return T2.createMessage(this,$,Z)}countTokens($,Z){let Y=$Q($),{betas:Q,...z}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:z,...Z,headers:T([{"anthropic-beta":[...Q??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new k2(this._client,$,Z)}}function $Q($){if(!$.output_format)return $;if($.output_config?.format)throw new L("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...Y}=$;return{...Y,output_config:{...$.output_config,format:Z}}}j1.Batches=f2;j1.BetaToolRunner=k2;j1.ToolError=j$;class b2 extends i{create($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.post(o`/v1/skills/${$}/versions?beta=true`,R$({body:z,...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve($,Z,Y){let{skill_id:Q,betas:z}=Z;return this._client.get(o`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.getAPIList(o`/v1/skills/${$}/versions?beta=true`,N2,{query:z,...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:Q,betas:z}=Z;return this._client.delete(o`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class D$ extends i{constructor(){super(...arguments);this.versions=new b2(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",R$({body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/skills/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/skills?beta=true",N2,{query:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(o`/v1/skills/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}D$.Versions=b2;class p0 extends i{constructor(){super(...arguments);this.models=new R2(this._client),this.messages=new j1(this._client),this.files=new E2(this._client),this.skills=new D$(this._client)}}p0.Models=R2;p0.Messages=j1;p0.Files=E2;p0.Skills=D$;class T$ extends i{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function ZQ($){return $?.output_config?.format}function B6($,Z,Y){let Q=ZQ(Z);if(!Z||!("parse"in(Q??{})))return{...$,content:$.content.map((z)=>{if(z.type==="text")return Object.defineProperty({...z},"parsed_output",{value:null,enumerable:!1});return z}),parsed_output:null};return O6($,Z,Y)}function O6($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=EV(Z,J.text);if(Q===null)Q=X;return Object.defineProperty({...J},"parsed_output",{value:X,enumerable:!1})}return J});return{...$,content:z,parsed_output:Q}}function EV($,Z){let Y=ZQ($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new L(`Failed to parse structured output: ${Q}`)}}var b0,A1,I$,y2,N4,_2,x2,M4,v2,Y1,h2,C4,E4,i1,R4,F4,g2,N6,YQ,M6,C6,E6,R6,QQ,zQ="__json_buf";function JQ($){return $.type==="tool_use"||$.type==="server_tool_use"}class m2{constructor($,Z){b0.add(this),this.messages=[],this.receivedMessages=[],A1.set(this,void 0),I$.set(this,null),this.controller=new AbortController,y2.set(this,void 0),N4.set(this,()=>{}),_2.set(this,()=>{}),x2.set(this,void 0),M4.set(this,()=>{}),v2.set(this,()=>{}),Y1.set(this,{}),h2.set(this,!1),C4.set(this,!1),E4.set(this,!1),i1.set(this,!1),R4.set(this,void 0),F4.set(this,void 0),g2.set(this,void 0),M6.set(this,(Y)=>{if(R(this,C4,!0,"f"),t0(Y))Y=new U0;if(Y instanceof U0)return R(this,E4,!0,"f"),this._emit("abort",Y);if(Y instanceof L)return this._emit("error",Y);if(Y instanceof Error){let Q=new L(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new L(String(Y)))}),R(this,y2,new Promise((Y,Q)=>{R(this,N4,Y,"f"),R(this,_2,Q,"f")}),"f"),R(this,x2,new Promise((Y,Q)=>{R(this,M4,Y,"f"),R(this,v2,Q,"f")}),"f"),N(this,y2,"f").catch(()=>{}),N(this,x2,"f").catch(()=>{}),R(this,I$,$,"f"),R(this,g2,Z?.logger??console,"f")}get response(){return N(this,R4,"f")}get request_id(){return N(this,F4,"f")}async withResponse(){R(this,i1,!0,"f");let $=await N(this,y2,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new m2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new m2(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return R(z,I$,{...Z,stream:!0},"f"),z._run(()=>z._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),z}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},N(this,M6,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let Q=Y?.signal,z;if(Q){if(Q.aborted)this.controller.abort();z=this.controller.abort.bind(this.controller),Q.addEventListener("abort",z)}try{N(this,b0,"m",C6).call(this);let{response:J,data:X}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(J);for await(let K of X)N(this,b0,"m",E6).call(this,K);if(X.controller.signal?.aborted)throw new U0;N(this,b0,"m",R6).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;R(this,R4,$,"f"),R(this,F4,$?.headers.get("request-id"),"f"),N(this,N4,"f").call(this,$),this._emit("connect")}get ended(){return N(this,h2,"f")}get errored(){return N(this,C4,"f")}get aborted(){return N(this,E4,"f")}abort(){this.controller.abort()}on($,Z){return(N(this,Y1,"f")[$]||(N(this,Y1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=N(this,Y1,"f")[$];if(!Y)return this;let Q=Y.findIndex((z)=>z.listener===Z);if(Q>=0)Y.splice(Q,1);return this}once($,Z){return(N(this,Y1,"f")[$]||(N(this,Y1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,i1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,i1,!0,"f"),await N(this,x2,"f")}get currentMessage(){return N(this,A1,"f")}async finalMessage(){return await this.done(),N(this,b0,"m",N6).call(this)}async finalText(){return await this.done(),N(this,b0,"m",YQ).call(this)}_emit($,...Z){if(N(this,h2,"f"))return;if($==="end")R(this,h2,!0,"f"),N(this,M4,"f").call(this);let Y=N(this,Y1,"f")[$];if(Y)N(this,Y1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!N(this,i1,"f")&&!Y?.length)Promise.reject(Q);N(this,_2,"f").call(this,Q),N(this,v2,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!N(this,i1,"f")&&!Y?.length)Promise.reject(Q);N(this,_2,"f").call(this,Q),N(this,v2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",N(this,b0,"m",N6).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{N(this,b0,"m",C6).call(this),this._connected(null);let z=T0.fromReadableStream($,this.controller);for await(let J of z)N(this,b0,"m",E6).call(this,J);if(z.controller.signal?.aborted)throw new U0;N(this,b0,"m",R6).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(A1=new WeakMap,I$=new WeakMap,y2=new WeakMap,N4=new WeakMap,_2=new WeakMap,x2=new WeakMap,M4=new WeakMap,v2=new WeakMap,Y1=new WeakMap,h2=new WeakMap,C4=new WeakMap,E4=new WeakMap,i1=new WeakMap,R4=new WeakMap,F4=new WeakMap,g2=new WeakMap,M6=new WeakMap,b0=new WeakSet,N6=function(){if(this.receivedMessages.length===0)throw new L("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},YQ=function(){if(this.receivedMessages.length===0)throw new L("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Y)=>Y.type==="text").map((Y)=>Y.text);if(Z.length===0)throw new L("stream ended without producing a content block with type=text");return Z.join(" ")},C6=function(){if(this.ended)return;R(this,A1,void 0,"f")},E6=function(Z){if(this.ended)return;let Y=N(this,b0,"m",QQ).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let Q=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Z.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Z.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(JQ(Q)&&Q.input)this._emit("inputJson",Z.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Z.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:XQ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(B6(Y,N(this,I$,"f"),{logger:N(this,g2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,A1,Y,"f");break}case"content_block_start":case"message_delta":break}},R6=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");let Z=N(this,A1,"f");if(!Z)throw new L("request ended without sending any chunks");return R(this,A1,void 0,"f"),B6(Z,N(this,I$,"f"),{logger:N(this,g2,"f")})},QQ=function(Z){let Y=N(this,A1,"f");if(Z.type==="message_start"){if(Y)throw new L(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new L(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Y;case"message_delta":if(Y.stop_reason=Z.delta.stop_reason,Y.stop_sequence=Z.delta.stop_sequence,Y.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)Y.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Y.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Y.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Y.usage.server_tool_use=Z.usage.server_tool_use;return Y;case"content_block_start":return Y.content.push({...Z.content_block}),Y;case"content_block_delta":{let Q=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,text:(Q.text||"")+Z.delta.text};break}case"citations_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,citations:[...Q.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Q&&JQ(Q)){let z=Q[zQ]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,zQ,{value:z,enumerable:!1,writable:!0}),z)J.input=G4(z);Y.content[Z.index]=J}break}case"thinking_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,thinking:Q.thinking+Z.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,signature:Z.delta.signature};break}default:XQ(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(Q)=>{let z=Z.shift();if(z)z.resolve(Q);else $.push(Q)}),this.on("end",()=>{Y=!0;for(let Q of Z)Q.resolve(void 0);Z.length=0}),this.on("abort",(Q)=>{Y=!0;for(let z of Z)z.reject(Q);Z.length=0}),this.on("error",(Q)=>{Y=!0;for(let z of Z)z.reject(Q);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((z,J)=>Z.push({resolve:z,reject:J})).then((z)=>z?{value:z,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new T0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function XQ($){}class u2 extends i{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(o`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",g0,{query:$,...Z})}delete($,Z){return this._client.delete(o`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(o`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new L(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:T([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,z)=>P$.fromResponse(z.response,z.controller))}}class r1 extends i{constructor(){super(...arguments);this.batches=new u2(this._client)}create($,Z){if($.model in KQ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${KQ[$.model]}
161
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in FV&&$.thinking&&$.thinking.type==="enabled")console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let Y=this._client._options.timeout;if(!$.stream&&Y==null){let z=K4[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,z)}let Q=X4($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:T([Q,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>O6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return m2.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var KQ={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026"},FV=["claude-opus-4-6"];r1.Batches=u2;class S$ extends i{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/models/${$}`,{...Y,headers:T([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models",g0,{query:Q,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var p2=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var F6,L6,L4,GQ,VQ="\\n\\nHuman:",UQ="\\n\\nAssistant:";class r{constructor({baseURL:$=p2("ANTHROPIC_BASE_URL"),apiKey:Z=p2("ANTHROPIC_API_KEY")??null,authToken:Y=p2("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){F6.add(this),L4.set(this,void 0);let z={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!z.dangerouslyAllowBrowser&&PY())throw new L(`It looks like you're running in a browser-like environment.
153
162
 
154
163
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
155
164
  If you understand the risks and have appropriate mitigations in place,
156
165
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
157
166
 
158
167
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
159
- `);this.baseURL=J.baseURL,this.timeout=J.timeout??s2.DEFAULT_TIMEOUT,this.logger=J.logger??console;let z="warn";this.logLevel=z,this.logLevel=I2(J.logLevel,"ClientOptions.logLevel",this)??I2(_8("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??z,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??y6(),R(this,V7,x6,"f"),this._options=J,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Y}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return A([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return A([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return A([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return v6($)}getUserAgent(){return`${this.constructor.name}/JS ${C0}`}defaultIdempotencyKey(){return`stainless-node-retry-${L2()}`}makeStatusError($,Z,Y,Q){return i.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!C(this,r2,"m",B3).call(this)&&Y||this.baseURL,J=D6($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),X=Object.fromEntries(J.searchParams);if(!P2(z)||!P2(X))Z={...X,...z,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))J.search=this.stringifyQuery(Z);return J.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new E("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:Y}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Y){return this.request(Promise.resolve(Y).then((Q)=>{return{method:$,path:Z,...Q}}))}request($,Z=null){return new u0(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let Q=await $,J=Q.maxRetries??this.maxRetries;if(Z==null)Z=J;await this.prepareOptions(Q);let{req:z,url:X,timeout:K}=await this.buildRequest(Q,{retryCount:J-Z});await this.prepareRequest(z,{url:X,options:Q});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),G=Y===void 0?"":`, retryOf: ${Y}`,q=Date.now();if(t(this).debug(`[${V}] sending request`,a$({retryOfRequestLogID:Y,method:Q.method,url:X,options:Q,headers:z.headers})),Q.signal?.aborted)throw new z$;let U=new AbortController,W=await this.fetchWithTimeout(X,z,K,U).catch(i1),B=Date.now();if(W instanceof globalThis.Error){let F=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new z$;let j=i$(W)||/timed? ?out/i.test(String(W)+("cause"in W?String(W.cause):""));if(Z)return t(this).info(`[${V}] connection ${j?"timed out":"failed"} - ${F}`),t(this).debug(`[${V}] connection ${j?"timed out":"failed"} (${F})`,a$({retryOfRequestLogID:Y,url:X,durationMs:B-q,message:W.message})),this.retryRequest(Q,Z,Y??V);if(t(this).info(`[${V}] connection ${j?"timed out":"failed"} - error; no more retries left`),t(this).debug(`[${V}] connection ${j?"timed out":"failed"} (error; no more retries left)`,a$({retryOfRequestLogID:Y,url:X,durationMs:B-q,message:W.message})),j)throw new a1;throw new m0({cause:W})}let M=[...W.headers.entries()].filter(([F])=>F==="request-id").map(([F,j])=>", "+F+": "+JSON.stringify(j)).join(""),N=`[${V}${G}${M}] ${z.method} ${X} ${W.ok?"succeeded":"failed"} with status ${W.status} in ${B-q}ms`;if(!W.ok){let F=await this.shouldRetry(W);if(Z&&F){let $$=`retrying, ${Z} attempts remaining`;return await _6(W.body),t(this).info(`${N} - ${$$}`),t(this).debug(`[${V}] response error (${$$})`,a$({retryOfRequestLogID:Y,url:W.url,status:W.status,headers:W.headers,durationMs:B-q})),this.retryRequest(Q,Z,Y??V,W.headers)}let j=F?"error; no more retries left":"error; not retryable";t(this).info(`${N} - ${j}`);let p=await W.text().catch(($$)=>i1($$).message),n=f4(p),T=n?void 0:p;throw t(this).debug(`[${V}] response error (${j})`,a$({retryOfRequestLogID:Y,url:W.url,status:W.status,headers:W.headers,message:T,durationMs:Date.now()-q})),this.makeStatusError(W.status,n,T,W.headers)}return t(this).info(N),t(this).debug(`[${V}] response start`,a$({retryOfRequestLogID:Y,url:W.url,status:W.status,headers:W.headers,durationMs:B-q})),{response:W,options:Q,controller:U,requestLogID:V,retryOfRequestLogID:Y,startTime:q}}getAPIList($,Z,Y){return this.requestAPIList(Z,Y&&"then"in Y?Y.then((Q)=>({method:"get",path:$,...Q})):{method:"get",path:$,...Y})}requestAPIList($,Z){let Y=this.makeRequest(Z,null,void 0);return new d4(this,Y,$)}async fetchWithTimeout($,Z,Y,Q){let{signal:J,method:z,...X}=Z||{},K=this._makeAbort(Q);if(J)J.addEventListener("abort",K,{once:!0});let V=setTimeout(K,Y),G=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,q={signal:Q.signal,...G?{duplex:"half"}:{},method:"GET",...X};if(z)q.method=z.toUpperCase();try{return await this.fetch.call(void 0,$,q)}finally{clearTimeout(V)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,Q){let J,z=Q?.get("retry-after-ms");if(z){let K=parseFloat(z);if(!Number.isNaN(K))J=K}let X=Q?.get("retry-after");if(X&&!J){let K=parseFloat(X);if(!Number.isNaN(K))J=K*1000;else J=Date.parse(X)-Date.now()}if(J===void 0){let K=$.maxRetries??this.maxRetries;J=this.calculateDefaultRetryTimeoutMillis(Z,K)}return await T6(J),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let J=Z-$,z=Math.min(0.5*Math.pow(2,J),8),X=1-Math.random()*0.25;return z*X*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new E("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Y={...$},{method:Q,path:J,query:z,defaultBaseURL:X}=Y,K=this.buildURL(J,z,X);if("timeout"in Y)A6("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:V,body:G}=this.buildBody({options:Y}),q=await this.buildHeaders({options:$,method:Q,bodyHeaders:V,retryCount:Z});return{req:{method:Q,headers:q,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"},...G&&{body:G},...this.fetchOptions??{},...Y.fetchOptions??{}},url:K,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:Q}){let J={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let z=A([J,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...b6(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Y,$.headers]);return this.validateHeaders(z),z.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Y=A([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Y.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:h4($)};else if(typeof $==="object"&&Y.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return C(this,V7,"f").call(this,{body:$,headers:Y})}}s2=d,V7=new WeakMap,r2=new WeakSet,B3=function(){return this.baseURL!=="https://api.anthropic.com"};d.Anthropic=s2;d.HUMAN_PROMPT=M3;d.AI_PROMPT=C3;d.DEFAULT_TIMEOUT=600000;d.AnthropicError=E;d.APIError=i;d.APIConnectionError=m0;d.APIConnectionTimeoutError=a1;d.APIUserAbortError=z$;d.NotFoundError=t1;d.ConflictError=e1;d.RateLimitError=Z8;d.BadRequestError=n1;d.AuthenticationError=r1;d.InternalServerError=Y8;d.PermissionDeniedError=s1;d.UnprocessableEntityError=$8;d.toFile=c4;class x$ extends d{constructor(){super(...arguments);this.completions=new R1(this),this.messages=new o0(this),this.models=new L1(this),this.beta=new _$(this)}}x$.Completions=R1;x$.Messages=o0;x$.Models=L1;x$.Beta=_$;import{existsSync as pK,readFileSync as dK,writeFileSync as cK}from"fs";import{basename as t2}from"path";var N3=50;class e2{entries=[];saveState($){let Z=pK($),Y=Z?dK($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>N3)this.entries=this.entries.slice(-N3)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${t2($.path)} was a new file. Remove it manually if needed.`;cK($.path,$.content);let Z=$.content.split(`
160
- `).length;return`Undo: restored ${t2($.path)} (${Z} lines, from ${O3($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${t2($.path)} (${O3($.timestamp)})`}}function O3($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let Y=Math.floor(Z/60);if(Y<60)return`${Y}m ago`;return`${Math.floor(Y/60)}h ago`}o();var k=[{name:"read_file",description:"Read file contents. For large files, use offset/limit to read specific line ranges.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},offset:{type:"number",description:"Start reading from this line number (1-based). Optional."},limit:{type:"number",description:"Max lines to read. Optional, defaults to 500."}},required:["path"]}},{name:"write_file",description:"Create a new file or completely overwrite an existing file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write"},content:{type:"string",description:"Full file content"}},required:["path","content"]}},{name:"edit_file",description:"Make a precise edit to a file. Finds old_text and replaces it with new_text. The old_text must match exactly (including whitespace). "+"Use this instead of write_file when modifying existing files \u2014 it preserves the rest of the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to edit"},old_text:{type:"string",description:"Exact text to find (must be unique in the file)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}},{name:"search_files",description:"Search file contents using a regex pattern (like grep). Returns matching lines with file paths and line numbers.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in. Defaults to cwd."},include:{type:"string",description:'Glob pattern to filter files, e.g. "*.ts" or "*.py"'}},required:["pattern"]}},{name:"find_files",description:"Find files by name pattern (glob). Returns matching file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.ts", "src/**/test*"'},path:{type:"string",description:"Base directory. Defaults to cwd."}},required:["pattern"]}},{name:"list_directory",description:"List files and directories with type indicators and sizes.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to list. Defaults to cwd."}},required:[]}},{name:"run_command",description:"Run a shell command. Use for: git operations, running tests, installing packages, building projects, or any CLI task. Commands run in the current working directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"number",description:"Timeout in seconds. Default 30, max 120."}},required:["command"]}},{name:"fetch_url",description:"Fetch the content of a URL. Use for: reading documentation, checking APIs, downloading config files, or verifying endpoints. Returns the response body as text. For HTML pages, returns a text-only extraction (no tags).",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method. Default GET.",enum:["GET","POST","PUT","DELETE","PATCH","HEAD"]},headers:{type:"object",description:"Optional request headers as key-value pairs."},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH)."}},required:["url"]}}];var x8=[{name:"open_application",description:"Open a Windows application by name. Available apps: excel, word, powerpoint, outlook, onenote, teams, edge, chrome, firefox, calculator, notepad, terminal, explorer, vscode, cursor, paint, snip, settings, taskmanager.",input_schema:{type:"object",properties:{name:{type:"string",description:'App name (e.g. "excel", "outlook", "teams")'},argument:{type:"string",description:"Optional argument (e.g. file path to open in the app)"}},required:["name"]}},{name:"open_file_default",description:"Open a file with its default Windows application. E.g. .xlsx opens in Excel, .pdf in the PDF reader.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to open"}},required:["path"]}},{name:"open_url_browser",description:"Open a URL in the default web browser.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"get_running_apps",description:"List currently running Windows applications with memory usage. Read-only, non-destructive.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_system_info",description:"Get Windows system resource summary: CPU, RAM, disk, uptime, battery. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_calendar_events",description:"Get today's Outlook calendar events. Read-only. Returns event times and subjects.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_news",description:"Fetch current news headlines. Categories: business, tech, finance, brazil, world, security. Returns headlines grouped by category with source attribution.",input_schema:{type:"object",properties:{category:{type:"string",description:"News category to filter. Omit for all categories.",enum:["business","tech","finance","brazil","world","security"]}},required:[]}}],G7=[{name:"execute_powershell_script",description:"Execute a PowerShell script on the local machine. The script runs in a temp .ps1 file with -ExecutionPolicy Bypass (scoped). Safety guards block dangerous operations (Defender, System32, formatting). Returns stdout, stderr, exit code, and duration. Use for: automation, system queries, batch operations, registry reads, scheduled tasks.",input_schema:{type:"object",properties:{script:{type:"string",description:"The PowerShell script to execute. Multi-line supported."}},required:["script"]}},{name:"analyze_screen_context",description:"Get detailed information about the user's current screen: foreground window (what they are looking at), all visible windows with PIDs, memory usage, and titles. Use to understand the user's current context. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"read_clipboard_content",description:'Read the current clipboard content. Auto-detects text or image. For images, performs OCR using Windows.Media.Ocr to extract text. Use when the user says "le o que copiei", "o que tem no clipboard", "cola isso", etc. Read-only.',input_schema:{type:"object",properties:{},required:[]}}],q7=[{name:"send_notification",description:'Send a Windows toast notification to the user. Displays a system notification with title and message. Use when you need to alert the user about: task completions, reminders, important events, or when the user asks "me avisa quando terminar", "notifica quando...", etc.',input_schema:{type:"object",properties:{title:{type:"string",description:"Notification title (short, max ~50 chars)."},message:{type:"string",description:"Notification message/body."}},required:["title","message"]}}],U7=x8.find(($)=>$.name==="get_news");import{resolve as F5,sep as pQ}from"path";import{writeFileSync as VU}from"fs";g();import{existsSync as lK,readFileSync as oK}from"fs";import{join as iK}from"path";var j1=[{name:"InfoMoney",url:"https://www.infomoney.com.br/feed/",category:"finance",builtin:!0},{name:"Valor Economico",url:"https://pox.globo.com/rss/valor/",category:"business",builtin:!0},{name:"Bloomberg Linea BR",url:"https://www.bloomberglinea.com.br/feed/",category:"finance",builtin:!0},{name:"TechCrunch",url:"https://techcrunch.com/feed/",category:"tech",builtin:!0},{name:"Hacker News (best)",url:"https://hnrss.org/best",category:"tech",builtin:!0},{name:"The Verge",url:"https://www.theverge.com/rss/index.xml",category:"tech",builtin:!0},{name:"G1",url:"https://g1.globo.com/rss/g1/",category:"brazil",builtin:!0},{name:"Folha",url:"https://feeds.folha.uol.com.br/folha/cotidiano/rss091.xml",category:"brazil",builtin:!0},{name:"BBC World",url:"https://feeds.bbci.co.uk/news/world/rss.xml",category:"world",builtin:!0},{name:"Reuters",url:"https://www.reutersagency.com/feed/",category:"world",builtin:!0},{name:"The Hacker News",url:"https://feeds.feedburner.com/TheHackersNews",category:"security",builtin:!0},{name:"BleepingComputer",url:"https://www.bleepingcomputer.com/feed/",category:"security",builtin:!0},{name:"Krebs on Security",url:"https://krebsonsecurity.com/feed/",category:"security",builtin:!0}],H7="",U$=[],E$=new Set,L3=()=>iK(H7,"news-feeds.json");function W7(){if(!H7)return;let $={custom:U$,disabled:[...E$]};P(L3(),JSON.stringify($,null,2))}function aK(){if(!H7)return;let $=L3();if(!lK($)){U$=[],E$=new Set;return}try{let Z=JSON.parse(oK($,"utf-8"));U$=Z.custom||[],E$=new Set(Z.disabled||[])}catch{U$=[],E$=new Set}}function j3($){H7=$,aK()}function Z9(){return[...j1.filter((Z)=>!E$.has(Z.url)),...U$]}function B7($,Z,Y){let Q=$.trim();if(!Q||Q.length>100)return"Error: nome invalido (1-100 caracteres).";let J=Y.trim().toLowerCase();if(!J||J.length>30)return"Error: categoria invalida (1-30 caracteres).";let z=Z.trim();if(!z.startsWith("http://")&&!z.startsWith("https://"))return"Error: URL deve comecar com http:// ou https://";if(z.length>500)return"Error: URL muito longa (max 500 caracteres).";if([...j1,...U$].some((V)=>V.url===z))return"Error: essa URL ja esta cadastrada.";let K={name:Q,url:z,category:J};return U$=[...U$,K],W7(),K}function M7($){let Z=$.toLowerCase().trim(),Y=U$.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return U$=[...U$.slice(0,Y),...U$.slice(Y+1)],W7(),!0}function C7($){let Z=$.toLowerCase().trim(),Y=j1.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(E$.has(Y.url))return!1;return E$=new Set([...E$,Y.url]),W7(),!0}function N7($){let Z=$.toLowerCase().trim(),Y=j1.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!E$.has(Y.url))return!1;return E$=new Set([...E$].filter((Q)=>Q!==Y.url)),W7(),!0}function O7(){let $=["Fontes de noticias:"];$.push(`
161
- --- Built-in ---`);for(let Z of j1){let Y=E$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(U$.length>0){$.push(`
162
- --- Custom ---`);for(let Z of U$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
163
- Total: ${Z9().length} ativas (${j1.length} built-in, ${U$.length} custom, ${E$.size} desativadas)`),$.join(`
164
- `)}var F3=2097152,$9=10,nK=1e4;function rK($,Z,Y){let Q=[],J=/<item[\s>]([\s\S]*?)<\/item>/gi,z;while((z=J.exec($))!==null){let X=z[1],K=R3(X,Z,Y);if(K)Q.push(K);if(Q.length>=$9)break}if(Q.length===0){let X=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((z=X.exec($))!==null){let K=z[1],V=R3(K,Z,Y);if(V)Q.push(V);if(Q.length>=$9)break}}return Q}function R3($,Z,Y){let Q=v8($,"title");if(!Q)return null;let J=v8($,"link")||ZV($),z=sK(J),X=v8($,"pubDate")||v8($,"published")||v8($,"updated"),K;if(X){let V=new Date(X);K=isNaN(V.getTime())?void 0:V}return{title:h8(Q),link:z,source:Z,category:Y,pubDate:K}}function sK($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function tK($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v8($,Z){let Y=tK(Z),J=new RegExp(`<${Y}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Y}>`,"i").exec($);if(J)return J[1].trim();let X=new RegExp(`<${Y}[^>]*>([\\s\\S]*?)</${Y}>`,"i").exec($);return X?X[1].trim():null}function eK($,Z){let Y=$V($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function $V($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return f8(J[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return f8(Q[1]);return"utf-8"}function f8($){let Z=$.toLowerCase().replace(/[^a-z0-9]/g,"");if(Z==="iso88591"||Z==="latin1")return"iso-8859-1";if(Z==="windows1252"||Z==="cp1252")return"windows-1252";if(Z==="utf8")return"utf-8";if(Z==="usascii"||Z==="ascii")return"utf-8";return $.trim().toLowerCase()}function ZV($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var YV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",aacute:"\xE1",Aacute:"\xC1",agrave:"\xE0",Agrave:"\xC0",atilde:"\xE3",Atilde:"\xC3",acirc:"\xE2",Acirc:"\xC2",eacute:"\xE9",Eacute:"\xC9",egrave:"\xE8",Egrave:"\xC8",ecirc:"\xEA",Ecirc:"\xCA",iacute:"\xED",Iacute:"\xCD",oacute:"\xF3",Oacute:"\xD3",otilde:"\xF5",Otilde:"\xD5",ocirc:"\xF4",Ocirc:"\xD4",uacute:"\xFA",Uacute:"\xDA",uuml:"\xFC",Uuml:"\xDC",ccedil:"\xE7",Ccedil:"\xC7",ntilde:"\xF1",Ntilde:"\xD1",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",bull:"\u2022",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",copy:"\xA9",reg:"\xAE",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2",deg:"\xB0",middot:"\xB7",times:"\xD7",divide:"\xF7"};function h8($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>YV[Y]??Z).replace(/&#(\d+);/g,(Z,Y)=>String.fromCharCode(Number(Y))).replace(/&#x([0-9a-fA-F]+);/g,(Z,Y)=>String.fromCharCode(parseInt(Y,16))).trim()}async function Y9($,Z=5){let Y=Math.max(1,Math.min(Z,$9));if($&&$.length===0)return{items:[],errors:[]};let Q=Z9(),J=$?Q.filter((V)=>$.includes(V.category)):Q,z=await Promise.allSettled(J.map((V)=>JV(V,Y))),X=[],K=[];for(let V=0;V<z.length;V++){let G=z[V];if(G.status==="fulfilled")X.push(...G.value);else K.push(`${J[V].name}: ${QV(G.reason)}`)}return X.sort((V,G)=>{let q=V.pubDate?.getTime()||0;return(G.pubDate?.getTime()||0)-q}),{items:X,errors:K}}async function L0($,Z=5){if($&&$.length===0)return XV();let{items:Y,errors:Q}=await Y9($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
165
- Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return zV(Y,Q)}function QV($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function JV($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),nK);try{let J=await fetch($.url,{signal:Y.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Q),!J.ok)return[];let z=J.headers.get("content-length");if(z&&Number(z)>F3)return[];let X=J.body?.getReader();if(!X)return[];let K=[],V=0;while(!0){let{done:W,value:B}=await X.read();if(W)break;if(V+=B.byteLength,V>F3)return X.cancel(),[];K.push(B)}let G=Buffer.concat(K),q=eK(G,J.headers.get("content-type"));return rK(q,$.name,$.category).slice(0,Z)}catch(J){throw clearTimeout(Q),J}}function zV($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Q=new Map;for(let K of $){let V=Q.get(K.category)||[];Q.set(K.category,[...V,K])}let J=[],z=["finance","business","tech","security","brazil","world"];for(let K of z){let V=Q.get(K);if(!V||V.length===0)continue;let G=Y[K],q=V.slice(0,8).map((U)=>{let W=U.pubDate?U.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${W?`[${W}]`:""} ${U.title} (${U.source})`});J.push(`--- ${G} ---
166
- ${q.join(`
167
- `)}`)}let X=J.join(`
168
+ `);this.baseURL=z.baseURL,this.timeout=z.timeout??L6.DEFAULT_TIMEOUT,this.logger=z.logger??console;let J="warn";this.logLevel=J,this.logLevel=e7(z.logLevel,"ClientOptions.logLevel",this)??e7(p2("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=z.fetchOptions,this.maxRetries=z.maxRetries??2,this.fetch=z.fetch??TY(),R(this,L4,SY,"f"),this._options=z,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Y}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return T([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return T([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return T([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return wY($)}getUserAgent(){return`${this.constructor.name}/JS ${E1}`}defaultIdempotencyKey(){return`stainless-node-retry-${i7()}`}makeStatusError($,Z,Y,Q){return $0.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!N(this,F6,"m",GQ).call(this)&&Y||this.baseURL,z=CY($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),X=Object.fromEntries(z.searchParams);if(!a7(J)||!a7(X))Z={...X,...J,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))z.search=this.stringifyQuery(Z);return z.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new L("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:Y}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Y){return this.request(Promise.resolve(Y).then((Q)=>{return{method:$,path:Z,...Q}}))}request($,Z=null){return new d1(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let Q=await $,z=Q.maxRetries??this.maxRetries;if(Z==null)Z=z;await this.prepareOptions(Q);let{req:J,url:X,timeout:K}=await this.buildRequest(Q,{retryCount:z-Z});await this.prepareRequest(J,{url:X,options:Q});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),V=Y===void 0?"":`, retryOf: ${Y}`,U=Date.now();if(z0(this).debug(`[${G}] sending request`,e0({retryOfRequestLogID:Y,method:Q.method,url:X,options:Q,headers:J.headers})),Q.signal?.aborted)throw new U0;let q=new AbortController,H=await this.fetchWithTimeout(X,J,K,q).catch(Z2),B=Date.now();if(H instanceof globalThis.Error){let C=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new U0;let F=t0(H)||/timed? ?out/i.test(String(H)+("cause"in H?String(H.cause):""));if(Z)return z0(this).info(`[${G}] connection ${F?"timed out":"failed"} - ${C}`),z0(this).debug(`[${G}] connection ${F?"timed out":"failed"} (${C})`,e0({retryOfRequestLogID:Y,url:X,durationMs:B-U,message:H.message})),this.retryRequest(Q,Z,Y??G);if(z0(this).info(`[${G}] connection ${F?"timed out":"failed"} - error; no more retries left`),z0(this).debug(`[${G}] connection ${F?"timed out":"failed"} (error; no more retries left)`,e0({retryOfRequestLogID:Y,url:X,durationMs:B-U,message:H.message})),F)throw new Y2;throw new p1({cause:H})}let O=[...H.headers.entries()].filter(([C])=>C==="request-id").map(([C,F])=>", "+C+": "+JSON.stringify(F)).join(""),M=`[${G}${V}${O}] ${J.method} ${X} ${H.ok?"succeeded":"failed"} with status ${H.status} in ${B-U}ms`;if(!H.ok){let C=await this.shouldRetry(H);if(Z&&C){let g=`retrying, ${Z} attempts remaining`;return await IY(H.body),z0(this).info(`${M} - ${g}`),z0(this).debug(`[${G}] response error (${g})`,e0({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,durationMs:B-U})),this.retryRequest(Q,Z,Y??G,H.headers)}let F=C?"error; no more retries left":"error; not retryable";z0(this).info(`${M} - ${F}`);let k=await H.text().catch((g)=>Z2(g).message),d=s8(k),D=d?void 0:k;throw z0(this).debug(`[${G}] response error (${F})`,e0({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,message:D,durationMs:Date.now()-U})),this.makeStatusError(H.status,d,D,H.headers)}return z0(this).info(M),z0(this).debug(`[${G}] response start`,e0({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,durationMs:B-U})),{response:H,options:Q,controller:q,requestLogID:G,retryOfRequestLogID:Y,startTime:U}}getAPIList($,Z,Y){return this.requestAPIList(Z,Y&&"then"in Y?Y.then((Q)=>({method:"get",path:$,...Q})):{method:"get",path:$,...Y})}requestAPIList($,Z){let Y=this.makeRequest(Z,null,void 0);return new Q4(this,Y,$)}async fetchWithTimeout($,Z,Y,Q){let{signal:z,method:J,...X}=Z||{},K=this._makeAbort(Q);if(z)z.addEventListener("abort",K,{once:!0});let G=setTimeout(K,Y),V=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,U={signal:Q.signal,...V?{duplex:"half"}:{},method:"GET",...X};if(J)U.method=J.toUpperCase();try{return await this.fetch.call(void 0,$,U)}finally{clearTimeout(G)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,Q){let z,J=Q?.get("retry-after-ms");if(J){let K=parseFloat(J);if(!Number.isNaN(K))z=K}let X=Q?.get("retry-after");if(X&&!z){let K=parseFloat(X);if(!Number.isNaN(K))z=K*1000;else z=Date.parse(X)-Date.now()}if(z===void 0){let K=$.maxRetries??this.maxRetries;z=this.calculateDefaultRetryTimeoutMillis(Z,K)}return await FY(z),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let z=Z-$,J=Math.min(0.5*Math.pow(2,z),8),X=1-Math.random()*0.25;return J*X*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new L("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Y={...$},{method:Q,path:z,query:J,defaultBaseURL:X}=Y,K=this.buildURL(z,J,X);if("timeout"in Y)RY("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:G,body:V}=this.buildBody({options:Y}),U=await this.buildHeaders({options:$,method:Q,bodyHeaders:G,retryCount:Z});return{req:{method:Q,headers:U,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&V instanceof globalThis.ReadableStream&&{duplex:"half"},...V&&{body:V},...this.fetchOptions??{},...Y.fetchOptions??{}},url:K,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:Q}){let z={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();z[this.idempotencyHeader]=$.idempotencyKey}let J=T([z,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...DY(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Y,$.headers]);return this.validateHeaders(J),J.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Y=T([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Y.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:t8($)};else if(typeof $==="object"&&Y.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return N(this,L4,"f").call(this,{body:$,headers:Y})}}L6=r,L4=new WeakMap,F6=new WeakSet,GQ=function(){return this.baseURL!=="https://api.anthropic.com"};r.Anthropic=L6;r.HUMAN_PROMPT=VQ;r.AI_PROMPT=UQ;r.DEFAULT_TIMEOUT=600000;r.AnthropicError=L;r.APIError=$0;r.APIConnectionError=p1;r.APIConnectionTimeoutError=Y2;r.APIUserAbortError=U0;r.NotFoundError=X2;r.ConflictError=K2;r.RateLimitError=V2;r.BadRequestError=Q2;r.AuthenticationError=z2;r.InternalServerError=U2;r.PermissionDeniedError=J2;r.UnprocessableEntityError=G2;r.toFile=z4;class d0 extends r{constructor(){super(...arguments);this.completions=new T$(this),this.messages=new r1(this),this.models=new S$(this),this.beta=new p0(this)}}d0.Completions=T$;d0.Messages=r1;d0.Models=S$;d0.Beta=p0;import{existsSync as jV,readFileSync as AV,writeFileSync as PV}from"fs";import{basename as j6}from"path";var qQ=50;class A6{entries=[];saveState($){let Z=jV($),Y=Z?AV($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>qQ)this.entries=this.entries.slice(-qQ)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${j6($.path)} was a new file. Remove it manually if needed.`;PV($.path,$.content);let Z=$.content.split(`
169
+ `).length;return`Undo: restored ${j6($.path)} (${Z} lines, from ${HQ($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${j6($.path)} (${HQ($.timestamp)})`}}function HQ($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let Y=Math.floor(Z/60);if(Y<60)return`${Y}m ago`;return`${Math.floor(Y/60)}h ago`}s();var y=[{name:"read_file",description:"Read file contents. For large files, use offset/limit to read specific line ranges.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},offset:{type:"number",description:"Start reading from this line number (1-based). Optional."},limit:{type:"number",description:"Max lines to read. Optional, defaults to 500."}},required:["path"]}},{name:"write_file",description:"Create a new file or completely overwrite an existing file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write"},content:{type:"string",description:"Full file content"}},required:["path","content"]}},{name:"edit_file",description:"Make a precise edit to a file. Finds old_text and replaces it with new_text. The old_text must match exactly (including whitespace). "+"Use this instead of write_file when modifying existing files \u2014 it preserves the rest of the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to edit"},old_text:{type:"string",description:"Exact text to find (must be unique in the file)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}},{name:"search_files",description:"Search file contents using a regex pattern (like grep). Returns matching lines with file paths and line numbers.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in. Defaults to cwd."},include:{type:"string",description:'Glob pattern to filter files, e.g. "*.ts" or "*.py"'}},required:["pattern"]}},{name:"find_files",description:"Find files by name pattern (glob). Returns matching file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.ts", "src/**/test*"'},path:{type:"string",description:"Base directory. Defaults to cwd."}},required:["pattern"]}},{name:"list_directory",description:"List files and directories with type indicators and sizes.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to list. Defaults to cwd."}},required:[]}},{name:"run_command",description:"Run a shell command. Use for: git operations, running tests, installing packages, building projects, or any CLI task. Commands run in the current working directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"number",description:"Timeout in seconds. Default 30, max 120."}},required:["command"]}},{name:"fetch_url",description:"Fetch the content of a URL. Use for: reading documentation, checking APIs, downloading config files, or verifying endpoints. Returns the response body as text. For HTML pages, returns a text-only extraction (no tags).",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method. Default GET.",enum:["GET","POST","PUT","DELETE","PATCH","HEAD"]},headers:{type:"object",description:"Optional request headers as key-value pairs."},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH)."}},required:["url"]}}];var d2=[{name:"open_application",description:"Open a Windows application by name. Available apps: excel, word, powerpoint, outlook, onenote, teams, edge, chrome, firefox, calculator, notepad, terminal, explorer, vscode, cursor, paint, snip, settings, taskmanager.",input_schema:{type:"object",properties:{name:{type:"string",description:'App name (e.g. "excel", "outlook", "teams")'},argument:{type:"string",description:"Optional argument (e.g. file path to open in the app)"}},required:["name"]}},{name:"open_file_default",description:"Open a file with its default Windows application. E.g. .xlsx opens in Excel, .pdf in the PDF reader.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to open"}},required:["path"]}},{name:"open_url_browser",description:"Open a URL in the default web browser.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"get_running_apps",description:"List currently running Windows applications with memory usage. Read-only, non-destructive.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_system_info",description:"Get Windows system resource summary: CPU, RAM, disk, uptime, battery. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_calendar_events",description:"Get today's Outlook calendar events. Read-only. Returns event times and subjects.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_news",description:"Fetch current news headlines. Categories: business, tech, finance, brazil, world, security. Returns headlines grouped by category with source attribution.",input_schema:{type:"object",properties:{category:{type:"string",description:"News category to filter. Omit for all categories.",enum:["business","tech","finance","brazil","world","security"]}},required:[]}}],j4=[{name:"execute_powershell_script",description:"Execute a PowerShell script on the local machine. The script runs in a temp .ps1 file with -ExecutionPolicy Bypass (scoped). Safety guards block dangerous operations (Defender, System32, formatting). Returns stdout, stderr, exit code, and duration. Use for: automation, system queries, batch operations, registry reads, scheduled tasks.",input_schema:{type:"object",properties:{script:{type:"string",description:"The PowerShell script to execute. Multi-line supported."}},required:["script"]}},{name:"analyze_screen_context",description:"Get detailed information about the user's current screen: foreground window (what they are looking at), all visible windows with PIDs, memory usage, and titles. Use to understand the user's current context. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"read_clipboard_content",description:'Read the current clipboard content. Auto-detects text or image. For images, performs OCR using Windows.Media.Ocr to extract text. Use when the user says "le o que copiei", "o que tem no clipboard", "cola isso", etc. Read-only.',input_schema:{type:"object",properties:{},required:[]}}],A4=[{name:"send_notification",description:'Send a Windows toast notification to the user. Displays a system notification with title and message. Use when you need to alert the user about: task completions, reminders, important events, or when the user asks "me avisa quando terminar", "notifica quando...", etc.',input_schema:{type:"object",properties:{title:{type:"string",description:"Notification title (short, max ~50 chars)."},message:{type:"string",description:"Notification message/body."}},required:["title","message"]}}],P4=d2.find(($)=>$.name==="get_news");import{resolve as b5,sep as _J}from"path";import{writeFileSync as dH}from"fs";l();import{existsSync as DV,readFileSync as TV}from"fs";import{join as IV}from"path";var w$=[{name:"InfoMoney",url:"https://www.infomoney.com.br/feed/",category:"finance",builtin:!0},{name:"Valor Economico",url:"https://pox.globo.com/rss/valor/",category:"business",builtin:!0},{name:"Bloomberg Linea BR",url:"https://www.bloomberglinea.com.br/feed/",category:"finance",builtin:!0},{name:"TechCrunch",url:"https://techcrunch.com/feed/",category:"tech",builtin:!0},{name:"Hacker News (best)",url:"https://hnrss.org/best",category:"tech",builtin:!0},{name:"The Verge",url:"https://www.theverge.com/rss/index.xml",category:"tech",builtin:!0},{name:"G1",url:"https://g1.globo.com/rss/g1/",category:"brazil",builtin:!0},{name:"Folha",url:"https://feeds.folha.uol.com.br/folha/cotidiano/rss091.xml",category:"brazil",builtin:!0},{name:"BBC World",url:"https://feeds.bbci.co.uk/news/world/rss.xml",category:"world",builtin:!0},{name:"Reuters",url:"https://www.reutersagency.com/feed/",category:"world",builtin:!0},{name:"The Hacker News",url:"https://feeds.feedburner.com/TheHackersNews",category:"security",builtin:!0},{name:"BleepingComputer",url:"https://www.bleepingcomputer.com/feed/",category:"security",builtin:!0},{name:"Krebs on Security",url:"https://krebsonsecurity.com/feed/",category:"security",builtin:!0}],D4="",N0=[],S0=new Set,NQ=()=>IV(D4,"news-feeds.json");function T4(){if(!D4)return;let $={custom:N0,disabled:[...S0]};P(NQ(),JSON.stringify($,null,2))}function SV(){if(!D4)return;let $=NQ();if(!DV($)){N0=[],S0=new Set;return}try{let Z=JSON.parse(TV($,"utf-8"));N0=Z.custom||[],S0=new Set(Z.disabled||[])}catch{N0=[],S0=new Set}}function MQ($){D4=$,SV()}function D6(){return[...w$.filter((Z)=>!S0.has(Z.url)),...N0]}function I4($,Z,Y){let Q=$.trim();if(!Q||Q.length>100)return"Error: nome invalido (1-100 caracteres).";let z=Y.trim().toLowerCase();if(!z||z.length>30)return"Error: categoria invalida (1-30 caracteres).";let J=Z.trim();if(!J.startsWith("http://")&&!J.startsWith("https://"))return"Error: URL deve comecar com http:// ou https://";if(J.length>500)return"Error: URL muito longa (max 500 caracteres).";if([...w$,...N0].some((G)=>G.url===J))return"Error: essa URL ja esta cadastrada.";let K={name:Q,url:J,category:z};return N0=[...N0,K],T4(),K}function S4($){let Z=$.toLowerCase().trim(),Y=N0.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return N0=[...N0.slice(0,Y),...N0.slice(Y+1)],T4(),!0}function w4($){let Z=$.toLowerCase().trim(),Y=w$.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(S0.has(Y.url))return!1;return S0=new Set([...S0,Y.url]),T4(),!0}function k4($){let Z=$.toLowerCase().trim(),Y=w$.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!S0.has(Y.url))return!1;return S0=new Set([...S0].filter((Q)=>Q!==Y.url)),T4(),!0}function f4(){let $=["Fontes de noticias:"];$.push(`
170
+ --- Built-in ---`);for(let Z of w$){let Y=S0.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(N0.length>0){$.push(`
171
+ --- Custom ---`);for(let Z of N0)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
172
+ Total: ${D6().length} ativas (${w$.length} built-in, ${N0.length} custom, ${S0.size} desativadas)`),$.join(`
173
+ `)}var WQ=2097152,P6=10,wV=1e4;function kV($,Z,Y){let Q=[],z=/<item[\s>]([\s\S]*?)<\/item>/gi,J;while((J=z.exec($))!==null){let X=J[1],K=BQ(X,Z,Y);if(K)Q.push(K);if(Q.length>=P6)break}if(Q.length===0){let X=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((J=X.exec($))!==null){let K=J[1],G=BQ(K,Z,Y);if(G)Q.push(G);if(Q.length>=P6)break}}return Q}function BQ($,Z,Y){let Q=c2($,"title");if(!Q)return null;let z=c2($,"link")||xV($),J=fV(z),X=c2($,"pubDate")||c2($,"published")||c2($,"updated"),K;if(X){let G=new Date(X);K=isNaN(G.getTime())?void 0:G}return{title:o2(Q),link:J,source:Z,category:Y,pubDate:K}}function fV($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function bV($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function c2($,Z){let Y=bV(Z),z=new RegExp(`<${Y}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Y}>`,"i").exec($);if(z)return z[1].trim();let X=new RegExp(`<${Y}[^>]*>([\\s\\S]*?)</${Y}>`,"i").exec($);return X?X[1].trim():null}function yV($,Z){let Y=_V($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function _V($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return l2(z[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return l2(Q[1]);return"utf-8"}function l2($){let Z=$.toLowerCase().replace(/[^a-z0-9]/g,"");if(Z==="iso88591"||Z==="latin1")return"iso-8859-1";if(Z==="windows1252"||Z==="cp1252")return"windows-1252";if(Z==="utf8")return"utf-8";if(Z==="usascii"||Z==="ascii")return"utf-8";return $.trim().toLowerCase()}function xV($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var vV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",aacute:"\xE1",Aacute:"\xC1",agrave:"\xE0",Agrave:"\xC0",atilde:"\xE3",Atilde:"\xC3",acirc:"\xE2",Acirc:"\xC2",eacute:"\xE9",Eacute:"\xC9",egrave:"\xE8",Egrave:"\xC8",ecirc:"\xEA",Ecirc:"\xCA",iacute:"\xED",Iacute:"\xCD",oacute:"\xF3",Oacute:"\xD3",otilde:"\xF5",Otilde:"\xD5",ocirc:"\xF4",Ocirc:"\xD4",uacute:"\xFA",Uacute:"\xDA",uuml:"\xFC",Uuml:"\xDC",ccedil:"\xE7",Ccedil:"\xC7",ntilde:"\xF1",Ntilde:"\xD1",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",bull:"\u2022",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",copy:"\xA9",reg:"\xAE",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2",deg:"\xB0",middot:"\xB7",times:"\xD7",divide:"\xF7"};function o2($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>vV[Y]??Z).replace(/&#(\d+);/g,(Z,Y)=>String.fromCharCode(Number(Y))).replace(/&#x([0-9a-fA-F]+);/g,(Z,Y)=>String.fromCharCode(parseInt(Y,16))).trim()}async function T6($,Z=5){let Y=Math.max(1,Math.min(Z,P6));if($&&$.length===0)return{items:[],errors:[]};let Q=D6(),z=$?Q.filter((G)=>$.includes(G.category)):Q,J=await Promise.allSettled(z.map((G)=>gV(G,Y))),X=[],K=[];for(let G=0;G<J.length;G++){let V=J[G];if(V.status==="fulfilled")X.push(...V.value);else K.push(`${z[G].name}: ${hV(V.reason)}`)}return X.sort((G,V)=>{let U=G.pubDate?.getTime()||0;return(V.pubDate?.getTime()||0)-U}),{items:X,errors:K}}async function P1($,Z=5){if($&&$.length===0)return uV();let{items:Y,errors:Q}=await T6($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
174
+ Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return mV(Y,Q)}function hV($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function gV($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),wV);try{let z=await fetch($.url,{signal:Y.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Q),!z.ok)return[];let J=z.headers.get("content-length");if(J&&Number(J)>WQ)return[];let X=z.body?.getReader();if(!X)return[];let K=[],G=0;while(!0){let{done:H,value:B}=await X.read();if(H)break;if(G+=B.byteLength,G>WQ)return X.cancel(),[];K.push(B)}let V=Buffer.concat(K),U=yV(V,z.headers.get("content-type"));return kV(U,$.name,$.category).slice(0,Z)}catch(z){throw clearTimeout(Q),z}}function mV($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Q=new Map;for(let K of $){let G=Q.get(K.category)||[];Q.set(K.category,[...G,K])}let z=[],J=["finance","business","tech","security","brazil","world"];for(let K of J){let G=Q.get(K);if(!G||G.length===0)continue;let V=Y[K],U=G.slice(0,8).map((q)=>{let H=q.pubDate?q.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${H?`[${H}]`:""} ${q.title} (${q.source})`});z.push(`--- ${V} ---
175
+ ${U.join(`
176
+ `)}`)}let X=z.join(`
168
177
 
169
178
  `);if(Z.length>0)X+=`
170
179
 
171
- (Fontes indisponiveis: ${Z.join(", ")})`;return X}function XV(){let $=Z9();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
172
- Uso: /news [categoria]`}var KV=15000,E3=5242880;async function D3($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),KV);try{let Q=await fetch($,{signal:Z.signal,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"pt-BR,pt;q=0.9,en;q=0.8"}});if(clearTimeout(Y),!Q.ok)return`Error: HTTP ${Q.status}`;let J=Q.headers.get("content-length");if(J&&Number(J)>E3)return"Error: pagina muito grande";let z=Q.body?.getReader();if(!z)return"Error: sem corpo de resposta";let X=[],K=0;while(!0){let{done:W,value:B}=await z.read();if(W)break;if(K+=B.byteLength,K>E3)return z.cancel(),"Error: pagina muito grande";X.push(B)}let V=Buffer.concat(X),G=Q.headers.get("content-type"),q=VV(V,G);return qV(q)}catch(Q){if(clearTimeout(Y),Q instanceof Error){if(Q.name==="AbortError")return"Error: timeout ao buscar pagina";return`Error: ${Q.message.slice(0,100)}`}return"Error: falha ao buscar pagina"}}function VV($,Z){let Y=GV($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function GV($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return f8(z[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return f8(Q[1]);let J=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(J)return f8(J[1]);return"utf-8"}function qV($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?h8(Z[1]):"Sem titulo",Q="",J=$.match(/<article[^>]*>([\s\S]*?)<\/article>/i);if(J)Q=J[1];if(!Q){let X=[/<div[^>]+class="[^"]*(?:article-body|post-content|entry-content|story-body|content-body|article-content|news-content|materia-corpo)[^"]*"[^>]*>([\s\S]*?)<\/div>/i,/<div[^>]+itemprop="articleBody"[^>]*>([\s\S]*?)<\/div>/i,/<main[^>]*>([\s\S]*?)<\/main>/i];for(let K of X){let V=$.match(K);if(V){Q=V[1];break}}}if(!Q){let X=[],K=/<p[^>]*>([\s\S]*?)<\/p>/gi,V;while((V=K.exec($))!==null){let G=h8(V[1]).trim();if(G.length>50)X.push(G)}Q=X.join(`
180
+ (Fontes indisponiveis: ${Z.join(", ")})`;return X}function uV(){let $=D6();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
181
+ Uso: /news [categoria]`}var pV=15000,OQ=5242880;async function CQ($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),pV);try{let Q=await fetch($,{signal:Z.signal,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"pt-BR,pt;q=0.9,en;q=0.8"}});if(clearTimeout(Y),!Q.ok)return`Error: HTTP ${Q.status}`;let z=Q.headers.get("content-length");if(z&&Number(z)>OQ)return"Error: pagina muito grande";let J=Q.body?.getReader();if(!J)return"Error: sem corpo de resposta";let X=[],K=0;while(!0){let{done:H,value:B}=await J.read();if(H)break;if(K+=B.byteLength,K>OQ)return J.cancel(),"Error: pagina muito grande";X.push(B)}let G=Buffer.concat(X),V=Q.headers.get("content-type"),U=dV(G,V);return lV(U)}catch(Q){if(clearTimeout(Y),Q instanceof Error){if(Q.name==="AbortError")return"Error: timeout ao buscar pagina";return`Error: ${Q.message.slice(0,100)}`}return"Error: falha ao buscar pagina"}}function dV($,Z){let Y=cV($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function cV($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return l2(J[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return l2(Q[1]);let z=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(z)return l2(z[1]);return"utf-8"}function lV($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?o2(Z[1]):"Sem titulo",Q="",z=$.match(/<article[^>]*>([\s\S]*?)<\/article>/i);if(z)Q=z[1];if(!Q){let X=[/<div[^>]+class="[^"]*(?:article-body|post-content|entry-content|story-body|content-body|article-content|news-content|materia-corpo)[^"]*"[^>]*>([\s\S]*?)<\/div>/i,/<div[^>]+itemprop="articleBody"[^>]*>([\s\S]*?)<\/div>/i,/<main[^>]*>([\s\S]*?)<\/main>/i];for(let K of X){let G=$.match(K);if(G){Q=G[1];break}}}if(!Q){let X=[],K=/<p[^>]*>([\s\S]*?)<\/p>/gi,G;while((G=K.exec($))!==null){let V=o2(G[1]).trim();if(V.length>50)X.push(V)}Q=X.join(`
173
182
 
174
- `)}else Q=UV(Q);let z=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:z}}function UV($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let J=h8(Q[1]).trim();if(J.length>20)Z.push(J)}if(Z.length===0){let J=h8($).trim();if(J.length>50)return J}return Z.join(`
183
+ `)}else Q=oV(Q);let J=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:J}}function oV($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let z=o2(Q[1]).trim();if(z.length>20)Z.push(z)}if(Z.length===0){let z=o2($).trim();if(z.length>50)return z}return Z.join(`
175
184
 
176
- `)}o();g();p$();import{existsSync as P3,mkdirSync as HV,readFileSync as WV}from"fs";import{join as BV}from"path";import{randomUUID as MV}from"crypto";var A3="",c=[],D1=null,T3=null,I3=()=>BV(A3,"tasks.json");function F7(){P(I3(),JSON.stringify(c,null,2))}function CV(){let $=I3();if(!P3($)){c=[];return}try{c=JSON.parse(WV($,"utf-8"))}catch{c=[]}}function S3($,Z){if(A3=$,T3=Z,!P3($))HV($,{recursive:!0});if(CV(),D1)clearInterval(D1);D1=setInterval(NV,30000),RV().catch(()=>{})}function w3(){if(D1)clearInterval(D1),D1=null}function R7($,Z){let Y={id:EV(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(c=[...c,Y],F7(),Z&&L)Q9(Y).catch(()=>{});return Y}function E7($){let Z=$.toLowerCase(),Y=c.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(c=c.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),F7(),Y.dueAt&&L)b3(Y.id).catch(()=>{});return c.find((Q)=>Q.id===Y.id)||null}function k3($){let Z=$.toLowerCase(),Y=c.findIndex((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=c[Y];if(c=[...c.slice(0,Y),...c.slice(Y+1)],F7(),Q.dueAt&&L)b3(Q.id).catch(()=>{});return!0}function t$($=!1){return $?[...c]:c.filter((Z)=>!Z.done)}function i0($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",J=Y.dueAt?` (${LV(Y.dueAt)})`:"";return` ${Q} ${Y.title}${J} [${Y.id}]`});return`Tarefas (${$.length}):
185
+ `)}s();l();n0();import{existsSync as EQ,mkdirSync as iV,readFileSync as rV}from"fs";import{join as nV}from"path";import{randomUUID as aV}from"crypto";var RQ="",n=[],k$=null,FQ=null,LQ=()=>nV(RQ,"tasks.json");function b4(){P(LQ(),JSON.stringify(n,null,2))}function sV(){let $=LQ();if(!EQ($)){n=[];return}try{n=JSON.parse(rV($,"utf-8"))}catch{n=[]}}function S6($,Z){if(RQ=$,FQ=Z,!EQ($))iV($,{recursive:!0});if(sV(),k$)clearInterval(k$);k$=setInterval(tV,30000),ZU().catch(()=>{})}function jQ(){if(k$)clearInterval(k$),k$=null}function y4($,Z){let Y={id:YU(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(n=[...n,Y],b4(),Z&&j)I6(Y).catch(()=>{});return Y}function _4($){let Z=$.toLowerCase(),Y=n.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(n=n.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),b4(),Y.dueAt&&j)PQ(Y.id).catch(()=>{});return n.find((Q)=>Q.id===Y.id)||null}function AQ($){let Z=$.toLowerCase(),Y=n.findIndex((z)=>z.id===$||z.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=n[Y];if(n=[...n.slice(0,Y),...n.slice(Y+1)],b4(),Q.dueAt&&j)PQ(Q.id).catch(()=>{});return!0}function Q1($=!1){return $?[...n]:n.filter((Z)=>!Z.done)}function n1($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",z=Y.dueAt?` (${QU(Y.dueAt)})`:"";return` ${Q} ${Y.title}${z} [${Y.id}]`});return`Tarefas (${$.length}):
177
186
  ${Z.join(`
178
- `)}`}function P1($){let Z=new Date,Y=$.toLowerCase().trim(),Q=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Q){let X=parseInt(Q[1]),K=Q[2].startsWith("h")?"hours":"minutes",V=new Date(Z);if(K==="hours")V.setHours(V.getHours()+X);else V.setMinutes(V.getMinutes()+X);return V}let J=new Date(Z);if(Y.includes("amanha")||Y.includes("amanh\xE3"))J.setDate(J.getDate()+1);let z=Y.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(z){let X=parseInt(z[1]),K=parseInt(z[2]||"0");if(X>=0&&X<=23&&K>=0&&K<=59){if(J.setHours(X,K,0,0),J<=Z&&!Y.includes("amanha")&&!Y.includes("amanh\xE3"))J.setDate(J.getDate()+1);return J}}return null}function NV(){let $=new Date,Z=!1;for(let Y of c){if(Y.done||Y.notified||!Y.dueAt)continue;let Q=new Date(Y.dueAt);if(isNaN(Q.getTime()))continue;let J=$.getTime()-Q.getTime();if(J>=0&&J<300000)c=c.map((z)=>z.id===Y.id?{...z,notified:!0}:z),Z=!0,FV(Y),T3?.(Y)}if(Z)F7()}function OV($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function FV($){if(!L)return;try{await U0("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var J9="smolerclaw-reminder-";async function Q9($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${J9}${$.id}`,Q=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),J=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),X=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;","$x = New-Object Windows.Data.Xml.Dom.XmlDocument;",`$x.LoadXml('<toast><visual><binding template=""ToastText02""><text id=""1"">smolerclaw</text><text id=""2"">${J6(OV($.title))}</text></binding></visual><audio src=""ms-winsoundevent:Notification.Reminder""/></toast>');`,"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show([Windows.UI.Notifications.ToastNotification]::new($x))"].join(" ");try{await u$("Create",Y,["/SC","ONCE","/SD",Q,"/ST",J,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${X}"`,"/F"])}catch{}}async function b3($){let Z=`${J9}${$}`;try{await u$("Delete",Z,["/F"])}catch{}}async function RV(){if(!L)return;let $=Date.now();for(let Z of c){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await u$("Query",`${J9}${Z.id}`)).exitCode!==0)await Q9(Z)}catch{await Q9(Z)}}}function EV(){return MV().slice(0,8)}function LV($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),J=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),z=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(J.getTime()===Q.getTime())return`hoje ${z}`;let X=new Date(Q);if(X.setDate(X.getDate()+1),J.getTime()===X.getTime())return`amanha ${z}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${z}`}g();import{existsSync as y3,mkdirSync as jV,readFileSync as DV}from"fs";import{join as PV}from"path";import{randomUUID as AV}from"crypto";var _3="",W$=[],x3=()=>PV(_3,"memos.json");function v3(){P(x3(),JSON.stringify(W$,null,2))}function TV(){let $=x3();if(!y3($)){W$=[];return}try{W$=JSON.parse(DV($,"utf-8"))}catch{W$=[]}}function f3($){if(_3=$,!y3($))jV($,{recursive:!0});TV()}function L7($,Z=[]){let Y=new Date().toISOString(),Q=$.match(/#(\w+)/g)?.map((X)=>X.slice(1).toLowerCase())||[],J=[...new Set([...Z.map((X)=>X.toLowerCase()),...Q])],z={id:SV(),content:$.trim(),tags:J,createdAt:Y,updatedAt:Y};return W$=[...W$,z],v3(),z}function h3($){let Z=W$.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return W$=[...W$.slice(0,Z),...W$.slice(Z+1)],v3(),!0}function j7($){let Z=$.toLowerCase().trim();if(!Z)return[...W$];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return W$.filter((J)=>{if(Y)return J.tags.some((z)=>z.includes(Q));return J.content.toLowerCase().includes(Q)||J.tags.some((z)=>z.includes(Q))}).sort((J,z)=>new Date(z.updatedAt).getTime()-new Date(J.updatedAt).getTime())}function g8($=20){return[...W$].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function IV(){let $=new Map;for(let Z of W$)for(let Y of Z.tags)$.set(Y,($.get(Y)||0)+1);return[...$.entries()].map(([Z,Y])=>({tag:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function a0($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Y)=>{let Q=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.tags.length>0?` [${Y.tags.map((X)=>`#${X}`).join(" ")}]`:"",z=Y.content.length>80?Y.content.slice(0,80).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${Q}] ${z}${J} {${Y.id}}`});return`Memos (${$.length}):
187
+ `)}`}function f$($){let Z=new Date,Y=$.toLowerCase().trim(),Q=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Q){let X=parseInt(Q[1]),K=Q[2].startsWith("h")?"hours":"minutes",G=new Date(Z);if(K==="hours")G.setHours(G.getHours()+X);else G.setMinutes(G.getMinutes()+X);return G}let z=new Date(Z);if(Y.includes("amanha")||Y.includes("amanh\xE3"))z.setDate(z.getDate()+1);let J=Y.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(J){let X=parseInt(J[1]),K=parseInt(J[2]||"0");if(X>=0&&X<=23&&K>=0&&K<=59){if(z.setHours(X,K,0,0),z<=Z&&!Y.includes("amanha")&&!Y.includes("amanh\xE3"))z.setDate(z.getDate()+1);return z}}return null}function tV(){let $=new Date,Z=!1;for(let Y of n){if(Y.done||Y.notified||!Y.dueAt)continue;let Q=new Date(Y.dueAt);if(isNaN(Q.getTime()))continue;let z=$.getTime()-Q.getTime();if(z>=0&&z<300000)n=n.map((J)=>J.id===Y.id?{...J,notified:!0}:J),Z=!0,$U(Y),FQ?.(Y)}if(Z)b4()}function eV($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function $U($){if(!j)return;try{await B1("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var w6="smolerclaw-reminder-";async function I6($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${w6}${$.id}`,Q=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),z=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),X=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;","$x = New-Object Windows.Data.Xml.Dom.XmlDocument;",`$x.LoadXml('<toast><visual><binding template=""ToastText02""><text id=""1"">smolerclaw</text><text id=""2"">${a9(eV($.title))}</text></binding></visual><audio src=""ms-winsoundevent:Notification.Reminder""/></toast>');`,"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show([Windows.UI.Notifications.ToastNotification]::new($x))"].join(" ");try{await r0("Create",Y,["/SC","ONCE","/SD",Q,"/ST",z,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${X}"`,"/F"])}catch{}}async function PQ($){let Z=`${w6}${$}`;try{await r0("Delete",Z,["/F"])}catch{}}async function ZU(){if(!j)return;let $=Date.now();for(let Z of n){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await r0("Query",`${w6}${Z.id}`)).exitCode!==0)await I6(Z)}catch{await I6(Z)}}}function YU(){return aV().slice(0,8)}function QU($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),z=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),J=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(z.getTime()===Q.getTime())return`hoje ${J}`;let X=new Date(Q);if(X.setDate(X.getDate()+1),z.getTime()===X.getTime())return`amanha ${J}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${J}`}l();import{existsSync as DQ,mkdirSync as zU,readFileSync as JU}from"fs";import{join as XU}from"path";import{randomUUID as KU}from"crypto";var TQ="",E0=[],IQ=()=>XU(TQ,"memos.json");function SQ(){P(IQ(),JSON.stringify(E0,null,2))}function GU(){let $=IQ();if(!DQ($)){E0=[];return}try{E0=JSON.parse(JU($,"utf-8"))}catch{E0=[]}}function wQ($){if(TQ=$,!DQ($))zU($,{recursive:!0});GU()}function x4($,Z=[]){let Y=new Date().toISOString(),Q=$.match(/#(\w+)/g)?.map((X)=>X.slice(1).toLowerCase())||[],z=[...new Set([...Z.map((X)=>X.toLowerCase()),...Q])],J={id:UU(),content:$.trim(),tags:z,createdAt:Y,updatedAt:Y};return E0=[...E0,J],SQ(),J}function kQ($){let Z=E0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return E0=[...E0.slice(0,Z),...E0.slice(Z+1)],SQ(),!0}function v4($){let Z=$.toLowerCase().trim();if(!Z)return[...E0];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return E0.filter((z)=>{if(Y)return z.tags.some((J)=>J.includes(Q));return z.content.toLowerCase().includes(Q)||z.tags.some((J)=>J.includes(Q))}).sort((z,J)=>new Date(J.updatedAt).getTime()-new Date(z.updatedAt).getTime())}function i2($=20){return[...E0].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function VU(){let $=new Map;for(let Z of E0)for(let Y of Z.tags)$.set(Y,($.get(Y)||0)+1);return[...$.entries()].map(([Z,Y])=>({tag:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function a1($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Y)=>{let Q=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Y.tags.length>0?` [${Y.tags.map((X)=>`#${X}`).join(" ")}]`:"",J=Y.content.length>80?Y.content.slice(0,80).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${Q}] ${J}${z} {${Y.id}}`});return`Memos (${$.length}):
179
188
  ${Z.join(`
180
- `)}`}function g3(){let $=IV();if($.length===0)return"Nenhuma tag.";return`Tags:
189
+ `)}`}function fQ(){let $=VU();if($.length===0)return"Nenhuma tag.";return`Tags:
181
190
  ${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
182
- `)}`}function SV(){return AV().slice(0,8)}o();async function D7($){if(L)return wV($);return z9($)}async function wV($){let Z=$.to.replace(/'/g,"''"),Y=$.subject.replace(/'/g,"''"),Q=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),J=$.cc?.replace(/'/g,"''")||"",z=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${Y}'`,` $mail.Body = '${Q}'`,J?` $mail.CC = '${J}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
183
- `);try{let X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",z],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),15000),[V]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]);await X.exited,clearTimeout(K);let G=V.trim();if(G.includes("mailto"))return z9($);return G||"Email aberto no Outlook."}catch{return z9($)}}async function z9($){let Z=[];if($.subject)Z.push(`subject=${encodeURIComponent($.subject)}`);if($.body)Z.push(`body=${encodeURIComponent($.body)}`);if($.cc)Z.push(`cc=${encodeURIComponent($.cc)}`);let Y=`mailto:${encodeURIComponent($.to)}${Z.length?"?"+Z.join("&"):""}`;try{let Q=L?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Y}'`]:["xdg-open",Y],J=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe"}),z=setTimeout(()=>J.kill(),1e4);return await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),await J.exited,clearTimeout(z),"Email aberto no cliente de email padrao."}catch(Q){return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}function P7($){let Z=["--- Rascunho de Email ---",`Para: ${$.to}`];if($.cc)Z.push(`CC: ${$.cc}`);return Z.push(`Assunto: ${$.subject}`),Z.push(""),Z.push($.body),Z.push("------------------------"),Z.join(`
184
- `)}o();g();p$();import{existsSync as T7,mkdirSync as d3,readFileSync as kV,writeFileSync as bV,unlinkSync as yV}from"fs";import{join as I7}from"path";import{randomUUID as _V}from"crypto";var X9="",f=[],xV=null,c3=()=>I7(X9,"scheduler.json"),vV="Smolerclaw_";function l3($,Z){if(X9=$,xV=Z??null,!T7($))d3($,{recursive:!0});if(mV(),L)gV().catch(()=>{})}async function S7($,Z,Y,Q,J,z){let X=uV(),K=`${vV}${X}`,V={id:X,name:$.trim(),scheduleType:Z,time:Y,dateOrDay:z,action:Q,target:J.trim(),enabled:!0,taskName:K,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};if(L)await A7(V);return f=[...f,V],A1(),V}async function w7($){let Z=$.toLowerCase(),Y=f.findIndex((J)=>J.id===$||J.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=f[Y];if(L)await V9(Q.taskName,Q.id);return f=[...f.slice(0,Y),...f.slice(Y+1)],A1(),!0}async function k7($){let Z=f7($);if(!Z||Z.enabled)return null;if(L)await A7(Z);return f=f.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),A1(),f.find((Y)=>Y.id===Z.id)??null}async function b7($){let Z=f7($);if(!Z||!Z.enabled)return null;if(L)await V9(Z.taskName,void 0);return f=f.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),A1(),f.find((Y)=>Y.id===Z.id)??null}function m8($=!1){return $?[...f]:f.filter((Z)=>Z.enabled)}function o3($){return f7($)}async function y7($){let Z=f7($);if(!Z)return"Agendamento nao encontrado.";if(L){let Y=await u$("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return f=f.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),A1(),`Agendamento "${Z.name}" executado.`}function u8($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",J=pV(Y),z=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${J} [${z}] (${Q})`});return`Agendamentos (${$.length}):
191
+ `)}`}function UU(){return KU().slice(0,8)}s();async function h4($){if(j)return qU($);return k6($)}async function qU($){let Z=$.to.replace(/'/g,"''"),Y=$.subject.replace(/'/g,"''"),Q=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),z=$.cc?.replace(/'/g,"''")||"",J=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${Y}'`,` $mail.Body = '${Q}'`,z?` $mail.CC = '${z}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
192
+ `);try{let X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",J],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),15000),[G]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]);await X.exited,clearTimeout(K);let V=G.trim();if(V.includes("mailto"))return k6($);return V||"Email aberto no Outlook."}catch{return k6($)}}async function k6($){let Z=[];if($.subject)Z.push(`subject=${encodeURIComponent($.subject)}`);if($.body)Z.push(`body=${encodeURIComponent($.body)}`);if($.cc)Z.push(`cc=${encodeURIComponent($.cc)}`);let Y=`mailto:${encodeURIComponent($.to)}${Z.length?"?"+Z.join("&"):""}`;try{let Q=j?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Y}'`]:["xdg-open",Y],z=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>z.kill(),1e4);return await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),await z.exited,clearTimeout(J),"Email aberto no cliente de email padrao."}catch(Q){return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}function g4($){let Z=["--- Rascunho de Email ---",`Para: ${$.to}`];if($.cc)Z.push(`CC: ${$.cc}`);return Z.push(`Assunto: ${$.subject}`),Z.push(""),Z.push($.body),Z.push("------------------------"),Z.join(`
193
+ `)}s();l();n0();import{existsSync as u4,mkdirSync as xQ,readFileSync as HU,writeFileSync as WU,unlinkSync as BU}from"fs";import{join as p4}from"path";import{randomUUID as OU}from"crypto";var f6="",u=[],NU=null,vQ=()=>p4(f6,"scheduler.json"),MU="Smolerclaw_";function hQ($,Z){if(f6=$,NU=Z??null,!u4($))xQ($,{recursive:!0});if(FU(),j)RU().catch(()=>{})}async function d4($,Z,Y,Q,z,J){let X=LU(),K=`${MU}${X}`,G={id:X,name:$.trim(),scheduleType:Z,time:Y,dateOrDay:J,action:Q,target:z.trim(),enabled:!0,taskName:K,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};if(j)await m4(G);return u=[...u,G],b$(),G}async function c4($){let Z=$.toLowerCase(),Y=u.findIndex((z)=>z.id===$||z.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=u[Y];if(j)await y6(Q.taskName,Q.id);return u=[...u.slice(0,Y),...u.slice(Y+1)],b$(),!0}async function l4($){let Z=s4($);if(!Z||Z.enabled)return null;if(j)await m4(Z);return u=u.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),b$(),u.find((Y)=>Y.id===Z.id)??null}async function o4($){let Z=s4($);if(!Z||!Z.enabled)return null;if(j)await y6(Z.taskName,void 0);return u=u.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),b$(),u.find((Y)=>Y.id===Z.id)??null}function r2($=!1){return $?[...u]:u.filter((Z)=>Z.enabled)}function gQ($){return s4($)}async function i4($){let Z=s4($);if(!Z)return"Agendamento nao encontrado.";if(j){let Y=await r0("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return u=u.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),b$(),`Agendamento "${Z.name}" executado.`}function n2($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",z=jU(Y),J=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${z} [${J}] (${Q})`});return`Agendamentos (${$.length}):
185
194
  ${Z.join(`
186
- `)}`}function K9($){let Z=[`=== ${$.name} ===`,`ID: ${$.id}`,`Tipo: ${$.scheduleType}`,`Horario: ${$.time}`];if($.dateOrDay)Z.push(`Data/Dia: ${$.dateOrDay}`);if(Z.push(`Acao: ${$.action}`,`Alvo: ${$.target}`,`Status: ${$.enabled?"ativo":"desativado"}`,`Tarefa Windows: ${$.taskName}`,`Criado: ${u3($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${u3($.lastRun)}`);return Z.join(`
187
- `)}function _7($){let Z=$.toLowerCase().trim(),Y=Z.match(/^(\d{1,2}):(\d{2})$/);if(Y){let z=parseInt(Y[1]),X=parseInt(Y[2]);if(z>=0&&z<=23&&X>=0&&X<=59)return`${String(z).padStart(2,"0")}:${String(X).padStart(2,"0")}`}let Q=Z.match(/^(\d{1,2})h(\d{2})?$/);if(Q){let z=parseInt(Q[1]),X=parseInt(Q[2]||"0");if(z>=0&&z<=23&&X>=0&&X<=59)return`${String(z).padStart(2,"0")}:${String(X).padStart(2,"0")}`}let J=Z.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/);if(J){let z=parseInt(J[1]),X=parseInt(J[2]||"0"),K=J[3]==="pm";if(z===12)z=K?12:0;else if(K)z+=12;if(z>=0&&z<=23&&X>=0&&X<=59)return`${String(z).padStart(2,"0")}:${String(X).padStart(2,"0")}`}return null}function x7($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return p3(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let z=new Date(Y);return z.setDate(z.getDate()+1),p3(z)}let Q=Z.match(/^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})$/);if(Q){let z=parseInt(Q[1]),X=parseInt(Q[2]),K=parseInt(Q[3]);if(z>=1&&z<=31&&X>=1&&X<=12&&K>=2024)return`${String(X).padStart(2,"0")}/${String(z).padStart(2,"0")}/${K}`}let J=Z.match(/^(\d{1,2})[/.-](\d{1,2})$/);if(J){let z=parseInt(J[1]),X=parseInt(J[2]);if(z>=1&&z<=31&&X>=1&&X<=12)return`${String(X).padStart(2,"0")}/${String(z).padStart(2,"0")}/${Y.getFullYear()}`}return null}function v7($){let Z=$.toLowerCase().trim();return{dom:"SUN",domingo:"SUN",seg:"MON",segunda:"MON","segunda-feira":"MON",ter:"TUE",terca:"TUE","ter\xE7a":"TUE","terca-feira":"TUE","ter\xE7a-feira":"TUE",qua:"WED",quarta:"WED","quarta-feira":"WED",qui:"THU",quinta:"THU","quinta-feira":"THU",sex:"FRI",sexta:"FRI","sexta-feira":"FRI",sab:"SAT",sabado:"SAT","s\xE1bado":"SAT",sun:"SUN",sunday:"SUN",mon:"MON",monday:"MON",tue:"TUE",tuesday:"TUE",wed:"WED",wednesday:"WED",thu:"THU",thursday:"THU",fri:"FRI",friday:"FRI",sat:"SAT",saturday:"SAT"}[Z]??null}async function A7($){let Z=hV($),Y=[];switch($.scheduleType){case"once":if(Y.push("/SC","ONCE"),$.dateOrDay)Y.push("/SD",$.dateOrDay);break;case"daily":Y.push("/SC","DAILY");break;case"weekly":if(Y.push("/SC","WEEKLY"),$.dateOrDay)Y.push("/D",$.dateOrDay);break}Y.push("/ST",$.time),Y.push("/TR",Z),Y.push("/F");try{await u$("Create",$.taskName,Y)}catch{}}async function V9($,Z){try{await u$("Delete",$,["/F"])}catch{}if(Z)fV(Z)}function i3(){let $=I7(X9,"scripts");if(!T7($))d3($,{recursive:!0});return $}function m3($,Z,Y){let Q=i3(),J=I7(Q,`toast_${$}.ps1`),z=`# Toast notification script for smolerclaw
195
+ `)}`}function b6($){let Z=[`=== ${$.name} ===`,`ID: ${$.id}`,`Tipo: ${$.scheduleType}`,`Horario: ${$.time}`];if($.dateOrDay)Z.push(`Data/Dia: ${$.dateOrDay}`);if(Z.push(`Acao: ${$.action}`,`Alvo: ${$.target}`,`Status: ${$.enabled?"ativo":"desativado"}`,`Tarefa Windows: ${$.taskName}`,`Criado: ${yQ($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${yQ($.lastRun)}`);return Z.join(`
196
+ `)}function r4($){let Z=$.toLowerCase().trim(),Y=Z.match(/^(\d{1,2}):(\d{2})$/);if(Y){let J=parseInt(Y[1]),X=parseInt(Y[2]);if(J>=0&&J<=23&&X>=0&&X<=59)return`${String(J).padStart(2,"0")}:${String(X).padStart(2,"0")}`}let Q=Z.match(/^(\d{1,2})h(\d{2})?$/);if(Q){let J=parseInt(Q[1]),X=parseInt(Q[2]||"0");if(J>=0&&J<=23&&X>=0&&X<=59)return`${String(J).padStart(2,"0")}:${String(X).padStart(2,"0")}`}let z=Z.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/);if(z){let J=parseInt(z[1]),X=parseInt(z[2]||"0"),K=z[3]==="pm";if(J===12)J=K?12:0;else if(K)J+=12;if(J>=0&&J<=23&&X>=0&&X<=59)return`${String(J).padStart(2,"0")}:${String(X).padStart(2,"0")}`}return null}function n4($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return _Q(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let J=new Date(Y);return J.setDate(J.getDate()+1),_Q(J)}let Q=Z.match(/^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})$/);if(Q){let J=parseInt(Q[1]),X=parseInt(Q[2]),K=parseInt(Q[3]);if(J>=1&&J<=31&&X>=1&&X<=12&&K>=2024)return`${String(X).padStart(2,"0")}/${String(J).padStart(2,"0")}/${K}`}let z=Z.match(/^(\d{1,2})[/.-](\d{1,2})$/);if(z){let J=parseInt(z[1]),X=parseInt(z[2]);if(J>=1&&J<=31&&X>=1&&X<=12)return`${String(X).padStart(2,"0")}/${String(J).padStart(2,"0")}/${Y.getFullYear()}`}return null}function a4($){let Z=$.toLowerCase().trim();return{dom:"SUN",domingo:"SUN",seg:"MON",segunda:"MON","segunda-feira":"MON",ter:"TUE",terca:"TUE","ter\xE7a":"TUE","terca-feira":"TUE","ter\xE7a-feira":"TUE",qua:"WED",quarta:"WED","quarta-feira":"WED",qui:"THU",quinta:"THU","quinta-feira":"THU",sex:"FRI",sexta:"FRI","sexta-feira":"FRI",sab:"SAT",sabado:"SAT","s\xE1bado":"SAT",sun:"SUN",sunday:"SUN",mon:"MON",monday:"MON",tue:"TUE",tuesday:"TUE",wed:"WED",wednesday:"WED",thu:"THU",thursday:"THU",fri:"FRI",friday:"FRI",sat:"SAT",saturday:"SAT"}[Z]??null}async function m4($){let Z=EU($),Y=[];switch($.scheduleType){case"once":if(Y.push("/SC","ONCE"),$.dateOrDay)Y.push("/SD",$.dateOrDay);break;case"daily":Y.push("/SC","DAILY");break;case"weekly":if(Y.push("/SC","WEEKLY"),$.dateOrDay)Y.push("/D",$.dateOrDay);break}Y.push("/ST",$.time),Y.push("/TR",Z),Y.push("/F");try{await r0("Create",$.taskName,Y)}catch{}}async function y6($,Z){try{await r0("Delete",$,["/F"])}catch{}if(Z)CU(Z)}function mQ(){let $=p4(f6,"scripts");if(!u4($))xQ($,{recursive:!0});return $}function bQ($,Z,Y){let Q=mQ(),z=p4(Q,`toast_${$}.ps1`),J=`# Toast notification script for smolerclaw
188
197
  # Job ID: ${$}
189
198
  # Generated: ${new Date().toISOString()}
190
199
 
@@ -210,82 +219,82 @@ $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
210
219
  $xml.LoadXml($template)
211
220
  $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
212
221
  [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show($toast)
213
- `,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(z,"utf-8")]);return bV(J,K),J}function fV($){let Z=I7(i3(),`toast_${$}.ps1`);try{if(T7(Z))yV(Z)}catch{}}function hV($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${m3($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${m3($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function gV(){if(!L)return;for(let $ of f){if(!$.enabled)continue;try{if((await u$("Query",$.taskName)).exitCode!==0)await A7($)}catch{await A7($)}}}function a3(){}async function n3(){let $=0;for(let Z of f){if(L)await V9(Z.taskName,Z.id);$++}return f=[],A1(),`${$} agendamento(s) removido(s).`}function mV(){let $=c3();if(!T7($)){f=[];return}try{f=JSON.parse(kV($,"utf-8"))}catch{f=[]}}function A1(){P(c3(),JSON.stringify(f,null,2))}function uV(){return _V().slice(0,8)}function f7($){let Z=$.toLowerCase();return f.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function pV($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${dV($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function dV($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function u3($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function p3($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}g();import{existsSync as s3,mkdirSync as cV,readFileSync as lV}from"fs";import{join as oV}from"path";import{randomUUID as iV}from"crypto";var t3="",j0=[],e3=()=>oV(t3,"finance.json");function aV(){P(e3(),JSON.stringify(j0,null,2))}function nV(){let $=e3();if(!s3($)){j0=[];return}try{j0=JSON.parse(lV($,"utf-8"))}catch{j0=[]}}function $Y($){if(t3=$,!s3($))cV($,{recursive:!0});nV()}function p8($,Z,Y,Q){let J={id:rV(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return j0=[...j0,J],aV(),J}function h7($,Z){let Y=new Date,Q=$||Y.getFullYear(),J=Z!==void 0?Z:Y.getMonth(),z=j0.filter((U)=>{let W=new Date(U.date);return W.getFullYear()===Q&&W.getMonth()===J});if(z.length===0)return`Nenhuma transacao em ${r3(J)}/${Q}.`;let X=z.filter((U)=>U.type==="entrada").reduce((U,W)=>U+W.amount,0),K=z.filter((U)=>U.type==="saida").reduce((U,W)=>U+W.amount,0),V=X-K,G=new Map;for(let U of z.filter((W)=>W.type==="saida"))G.set(U.category,(G.get(U.category)||0)+U.amount);let q=[`--- Resumo ${r3(J)}/${Q} ---`,`Entradas: R$ ${X.toFixed(2)}`,`Saidas: R$ ${K.toFixed(2)}`,`Saldo: R$ ${V.toFixed(2)} ${V>=0?"":"(NEGATIVO)"}`];if(G.size>0){q.push(""),q.push("Saidas por categoria:");let U=[...G.entries()].sort((W,B)=>B[1]-W[1]);for(let[W,B]of U){let M=K>0?Math.round(B/K*100):0;q.push(` ${W.padEnd(15)} R$ ${B.toFixed(2)} (${M}%)`)}}return q.join(`
214
- `)}function G9($=10){let Z=[...j0].sort((Q,J)=>new Date(J.date).getTime()-new Date(Q.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
215
- ${Z.map((Q)=>{let J=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Q.type==="entrada"?"+":"-";return` [${J}] ${z} R$ ${Q.amount.toFixed(2)} ${Q.category} \u2014 ${Q.description} [${Q.id}]`}).join(`
216
- `)}`}function rV(){return iV().slice(0,8)}function r3($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}d$();var q9={debug:0,info:1,warn:2,error:3};function sV(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in q9)return $;if(process.env.DEBUG)return"debug";return"warn"}function tV($){return q9[$]>=q9[sV()]}function eV($,Z,Y){let J=`[${new Date().toISOString()}] ${$.toUpperCase()} ${Z}`;if(Y&&Object.keys(Y).length>0){let z=Object.entries(Y).map(([X,K])=>`${X}=${K instanceof Error?K.message:JSON.stringify(K)}`).join(" ");return`${J} | ${z}`}return J}function g7($,Z,Y){if(!tV($))return;let Q=eV($,Z,Y);process.stderr.write(Q+`
217
- `)}var x={debug:($,Z)=>g7("debug",$,Z),info:($,Z)=>g7("info",$,Z),warn:($,Z)=>g7("warn",$,Z),error:($,Z)=>g7("error",$,Z)};var ZY={maxSingleAmount:1e4,dailyAlertThreshold:1000,duplicateWindowMs:300000,blockOnFailure:!1},D0={...ZY},m7=[],u7=[];function YY($){D0={...ZY,...$},m7=[],u7=[]}function d8($,Z,Y,Q){let J=[],z=null;if(Z<=0)return{allowed:!1,warnings:[],blocked:"Valor deve ser positivo."};if(!Y.trim())return{allowed:!1,warnings:[],blocked:"Categoria obrigatoria."};if(!Q.trim())return{allowed:!1,warnings:[],blocked:"Descricao obrigatoria."};if(Z>D0.maxSingleAmount){let G=`Valor alto: R$ ${Z.toFixed(2)} excede limite de R$ ${D0.maxSingleAmount.toFixed(2)}`;if(D0.blockOnFailure)z=G;else J.push(G)}let X=Date.now(),K=m7.find((G)=>G.type===$&&G.amount===Math.abs(Z)&&G.category===Y.toLowerCase().trim()&&X-G.timestamp<D0.duplicateWindowMs);if(K){let G=Math.round((X-K.timestamp)/1000);J.push(`Possivel duplicata: mesma transacao registrada ha ${G}s atras`)}if($==="saida"){let G=QY(),U=u7.filter((W)=>W.type==="saida"&&W.date===G).reduce((W,B)=>W+B.amount,0)+Math.abs(Z);if(U>D0.dailyAlertThreshold)J.push(`Alerta: gasto diario projetado R$ ${U.toFixed(2)} excede limite de R$ ${D0.dailyAlertThreshold.toFixed(2)}`)}let V=z===null;return $G($,Z,Y,Q,V,J),{allowed:V,warnings:J,blocked:z}}function c8($,Z,Y){let Q=Math.abs(Z),J=Date.now(),z={type:$,amount:Q,category:Y.toLowerCase().trim(),timestamp:J},X=J-D0.duplicateWindowMs*2;m7=[...m7.filter((V)=>V.timestamp>X),z];let K=QY();u7=[...u7.filter((V)=>V.date===K),{type:$,amount:Q,date:K}]}function l8($){if($.blocked)return`BLOQUEADO: ${$.blocked}`;if($.warnings.length===0)return"";return $.warnings.map((Z)=>`AVISO: ${Z}`).join(`
218
- `)}function QY(){return new Date().toISOString().slice(0,10)}function $G($,Z,Y,Q,J,z){let X=!J?"error":z.length>0?"warning":"info";if(s("status:update",{source:"finance-guard",message:`${$==="entrada"?"+":"-"} R$ ${Math.abs(Z).toFixed(2)} ${Y} \u2014 ${Q}${z.length>0?` (${z.length} aviso${z.length>1?"s":""})`:""}`,level:X,timestamp:Date.now()}),z.length>0)x.debug("Finance guard warnings",{type:$,amount:Z,category:Y,warnings:z})}g();import{existsSync as JY,mkdirSync as ZG,readFileSync as YG}from"fs";import{join as QG}from"path";import{randomUUID as JG}from"crypto";var zY="",P0=[],XY=()=>QG(zY,"decisions.json");function zG(){P(XY(),JSON.stringify(P0,null,2))}function XG(){let $=XY();if(!JY($)){P0=[];return}try{P0=JSON.parse(YG($,"utf-8"))}catch{P0=[]}}function KY($){if(zY=$,!JY($))ZG($,{recursive:!0});XG()}function VY($,Z,Y,Q,J=[]){let z={id:KG(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:J.map((X)=>X.toLowerCase()),date:new Date().toISOString()};return P0=[...P0,z],zG(),z}function n0($){let Z=$.toLowerCase();return P0.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.chosen.toLowerCase().includes(Z)||Y.context.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))).sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime())}function p7($=15){return[...P0].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function T1($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Y)=>{let Q=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${Q}] ${Y.title}${J} {${Y.id}}`});return`Decisoes (${$.length}):
222
+ `,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(J,"utf-8")]);return WU(z,K),z}function CU($){let Z=p4(mQ(),`toast_${$}.ps1`);try{if(u4(Z))BU(Z)}catch{}}function EU($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${bQ($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${bQ($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function RU(){if(!j)return;for(let $ of u){if(!$.enabled)continue;try{if((await r0("Query",$.taskName)).exitCode!==0)await m4($)}catch{await m4($)}}}function uQ(){}async function pQ(){let $=0;for(let Z of u){if(j)await y6(Z.taskName,Z.id);$++}return u=[],b$(),`${$} agendamento(s) removido(s).`}function FU(){let $=vQ();if(!u4($)){u=[];return}try{u=JSON.parse(HU($,"utf-8"))}catch{u=[]}}function b$(){P(vQ(),JSON.stringify(u,null,2))}function LU(){return OU().slice(0,8)}function s4($){let Z=$.toLowerCase();return u.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function jU($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${AU($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function AU($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function yQ($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function _Q($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}l();import{existsSync as cQ,mkdirSync as PU,readFileSync as DU}from"fs";import{join as TU}from"path";import{randomUUID as IU}from"crypto";var lQ="",D1=[],oQ=()=>TU(lQ,"finance.json");function SU(){P(oQ(),JSON.stringify(D1,null,2))}function wU(){let $=oQ();if(!cQ($)){D1=[];return}try{D1=JSON.parse(DU($,"utf-8"))}catch{D1=[]}}function iQ($){if(lQ=$,!cQ($))PU($,{recursive:!0});wU()}function a2($,Z,Y,Q){let z={id:kU(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return D1=[...D1,z],SU(),z}function t4($,Z){let Y=new Date,Q=$||Y.getFullYear(),z=Z!==void 0?Z:Y.getMonth(),J=D1.filter((q)=>{let H=new Date(q.date);return H.getFullYear()===Q&&H.getMonth()===z});if(J.length===0)return`Nenhuma transacao em ${dQ(z)}/${Q}.`;let X=J.filter((q)=>q.type==="entrada").reduce((q,H)=>q+H.amount,0),K=J.filter((q)=>q.type==="saida").reduce((q,H)=>q+H.amount,0),G=X-K,V=new Map;for(let q of J.filter((H)=>H.type==="saida"))V.set(q.category,(V.get(q.category)||0)+q.amount);let U=[`--- Resumo ${dQ(z)}/${Q} ---`,`Entradas: R$ ${X.toFixed(2)}`,`Saidas: R$ ${K.toFixed(2)}`,`Saldo: R$ ${G.toFixed(2)} ${G>=0?"":"(NEGATIVO)"}`];if(V.size>0){U.push(""),U.push("Saidas por categoria:");let q=[...V.entries()].sort((H,B)=>B[1]-H[1]);for(let[H,B]of q){let O=K>0?Math.round(B/K*100):0;U.push(` ${H.padEnd(15)} R$ ${B.toFixed(2)} (${O}%)`)}}return U.join(`
223
+ `)}function _6($=10){let Z=[...D1].sort((Q,z)=>new Date(z.date).getTime()-new Date(Q.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
224
+ ${Z.map((Q)=>{let z=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Q.type==="entrada"?"+":"-";return` [${z}] ${J} R$ ${Q.amount.toFixed(2)} ${Q.category} \u2014 ${Q.description} [${Q.id}]`}).join(`
225
+ `)}`}function kU(){return IU().slice(0,8)}function dQ($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}u0();var x6={debug:0,info:1,warn:2,error:3};function fU(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in x6)return $;if(process.env.DEBUG)return"debug";return"warn"}function bU($){return x6[$]>=x6[fU()]}function yU($,Z,Y){let z=`[${new Date().toISOString()}] ${$.toUpperCase()} ${Z}`;if(Y&&Object.keys(Y).length>0){let J=Object.entries(Y).map(([X,K])=>`${X}=${K instanceof Error?K.message:JSON.stringify(K)}`).join(" ");return`${z} | ${J}`}return z}function e4($,Z,Y){if(!bU($))return;let Q=yU($,Z,Y);process.stderr.write(Q+`
226
+ `)}var m={debug:($,Z)=>e4("debug",$,Z),info:($,Z)=>e4("info",$,Z),warn:($,Z)=>e4("warn",$,Z),error:($,Z)=>e4("error",$,Z)};var rQ={maxSingleAmount:1e4,dailyAlertThreshold:1000,duplicateWindowMs:300000,blockOnFailure:!1},T1={...rQ},$5=[],Z5=[];function nQ($){T1={...rQ,...$},$5=[],Z5=[]}function s2($,Z,Y,Q){let z=[],J=null;if(Z<=0)return{allowed:!1,warnings:[],blocked:"Valor deve ser positivo."};if(!Y.trim())return{allowed:!1,warnings:[],blocked:"Categoria obrigatoria."};if(!Q.trim())return{allowed:!1,warnings:[],blocked:"Descricao obrigatoria."};if(Z>T1.maxSingleAmount){let V=`Valor alto: R$ ${Z.toFixed(2)} excede limite de R$ ${T1.maxSingleAmount.toFixed(2)}`;if(T1.blockOnFailure)J=V;else z.push(V)}let X=Date.now(),K=$5.find((V)=>V.type===$&&V.amount===Math.abs(Z)&&V.category===Y.toLowerCase().trim()&&X-V.timestamp<T1.duplicateWindowMs);if(K){let V=Math.round((X-K.timestamp)/1000);z.push(`Possivel duplicata: mesma transacao registrada ha ${V}s atras`)}if($==="saida"){let V=aQ(),q=Z5.filter((H)=>H.type==="saida"&&H.date===V).reduce((H,B)=>H+B.amount,0)+Math.abs(Z);if(q>T1.dailyAlertThreshold)z.push(`Alerta: gasto diario projetado R$ ${q.toFixed(2)} excede limite de R$ ${T1.dailyAlertThreshold.toFixed(2)}`)}let G=J===null;return _U($,Z,Y,Q,G,z),{allowed:G,warnings:z,blocked:J}}function t2($,Z,Y){let Q=Math.abs(Z),z=Date.now(),J={type:$,amount:Q,category:Y.toLowerCase().trim(),timestamp:z},X=z-T1.duplicateWindowMs*2;$5=[...$5.filter((G)=>G.timestamp>X),J];let K=aQ();Z5=[...Z5.filter((G)=>G.date===K),{type:$,amount:Q,date:K}]}function e2($){if($.blocked)return`BLOQUEADO: ${$.blocked}`;if($.warnings.length===0)return"";return $.warnings.map((Z)=>`AVISO: ${Z}`).join(`
227
+ `)}function aQ(){return new Date().toISOString().slice(0,10)}function _U($,Z,Y,Q,z,J){let X=!z?"error":J.length>0?"warning":"info";if(Q0("status:update",{source:"finance-guard",message:`${$==="entrada"?"+":"-"} R$ ${Math.abs(Z).toFixed(2)} ${Y} \u2014 ${Q}${J.length>0?` (${J.length} aviso${J.length>1?"s":""})`:""}`,level:X,timestamp:Date.now()}),J.length>0)m.debug("Finance guard warnings",{type:$,amount:Z,category:Y,warnings:J})}l();import{existsSync as sQ,mkdirSync as xU,readFileSync as vU}from"fs";import{join as hU}from"path";import{randomUUID as gU}from"crypto";var tQ="",I1=[],eQ=()=>hU(tQ,"decisions.json");function mU(){P(eQ(),JSON.stringify(I1,null,2))}function uU(){let $=eQ();if(!sQ($)){I1=[];return}try{I1=JSON.parse(vU($,"utf-8"))}catch{I1=[]}}function $z($){if(tQ=$,!sQ($))xU($,{recursive:!0});uU()}function Zz($,Z,Y,Q,z=[]){let J={id:pU(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:z.map((X)=>X.toLowerCase()),date:new Date().toISOString()};return I1=[...I1,J],mU(),J}function s1($){let Z=$.toLowerCase();return I1.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.chosen.toLowerCase().includes(Z)||Y.context.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))).sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime())}function Y5($=15){return[...I1].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function y$($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Y)=>{let Q=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${Q}] ${Y.title}${z} {${Y.id}}`});return`Decisoes (${$.length}):
219
228
  ${Z.join(`
220
- `)}`}function KG(){return JG().slice(0,8)}i8();g();import{existsSync as MY,mkdirSync as BG,readFileSync as MG}from"fs";import{join as CG}from"path";import{randomUUID as NG}from"crypto";var CY="",w={people:[],interactions:[],delegations:[]},NY=()=>CG(CY,"people.json");function l7(){P(NY(),JSON.stringify(w,null,2))}function OG(){let $=NY();if(!MY($)){w={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(MG($,"utf-8"));w={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{w={people:[],interactions:[],delegations:[]}}}function OY($){if(CY=$,!MY($))BG($,{recursive:!0});OG()}function o7($,Z,Y,Q){let J={id:j9(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),createdAt:new Date().toISOString()};return w={...w,people:[...w.people,J]},l7(),J}function e$($){let Z=$.toLowerCase();return w.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function i7($){if($)return w.people.filter((Z)=>Z.group===$);return[...w.people]}function FY($,Z,Y,Q){let J=e$($);if(!J)return null;let z={id:j9(),personId:J.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return w={...w,interactions:[...w.interactions,z]},l7(),z}function FG($,Z=10){let Y=e$($);if(!Y)return[];return[...w.interactions].filter((Q)=>Q.personId===Y.id).reverse().sort((Q,J)=>new Date(J.date).getTime()-new Date(Q.date).getTime()).slice(0,Z)}function I1(){let $=new Date,Z=[];for(let Y of w.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let J=w.people.find((z)=>z.id===Y.personId);if(J)Z.push({person:J,interaction:Y})}}return Z.sort((Y,Q)=>new Date(Y.interaction.followUpDate).getTime()-new Date(Q.interaction.followUpDate).getTime())}function a7($,Z,Y){let Q=e$($);if(!Q)return null;let J={id:j9(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return w={...w,delegations:[...w.delegations,J]},l7(),J}function RY($,Z,Y){if(!w.delegations.find((J)=>J.id===$))return null;return w={...w,delegations:w.delegations.map((J)=>J.id===$?{...J,status:Z,notes:Y||J.notes}:J)},l7(),w.delegations.find((J)=>J.id===$)||null}function r0($,Z=!0){let Y=[...w.delegations];if($){let J=e$($);if(!J)return[];Y=Y.filter((z)=>z.personId===J.id)}if(Z)Y=Y.filter((J)=>J.status!=="concluido");let Q=new Date;return Y=Y.map((J)=>{if(J.status==="pendente"&&J.dueDate){let z=new Date(J.dueDate);if(!isNaN(z.getTime())&&z<Q)return{...J,status:"atrasado"}}return J}),Y.sort((J,z)=>{if(J.status==="atrasado"&&z.status!=="atrasado")return-1;if(z.status==="atrasado"&&J.status!=="atrasado")return 1;let X=J.dueDate?new Date(J.dueDate).getTime():1/0,K=z.dueDate?new Date(z.dueDate).getTime():1/0;return X-K})}var EY={equipe:"Equipe",familia:"Familia",contato:"Contato"};function n7($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let J of $){let z=Z.get(J.group)||[];Z.set(J.group,[...z,J])}let Y=[],Q=["equipe","familia","contato"];for(let J of Q){let z=Z.get(J);if(!z?.length)continue;let X=z.map((K)=>{let V=K.role?` (${K.role})`:"",G=K.contact?` \u2014 ${K.contact}`:"";return` ${K.name}${V}${G} [${K.id}]`});Y.push(`--- ${EY[J]} ---
229
+ `)}`}function pU(){return gU().slice(0,8)}Z8();l();import{existsSync as Gz,mkdirSync as nU,readFileSync as aU}from"fs";import{join as sU}from"path";import{randomUUID as tU}from"crypto";var Vz="",b={people:[],interactions:[],delegations:[]},Uz=()=>sU(Vz,"people.json");function J5(){P(Uz(),JSON.stringify(b,null,2))}function eU(){let $=Uz();if(!Gz($)){b={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(aU($,"utf-8"));b={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{b={people:[],interactions:[],delegations:[]}}}function qz($){if(Vz=$,!Gz($))nU($,{recursive:!0});eU()}function X5($,Z,Y,Q){let z={id:n6(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),createdAt:new Date().toISOString()};return b={...b,people:[...b.people,z]},J5(),z}function z1($){let Z=$.toLowerCase();return b.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function K5($){if($)return b.people.filter((Z)=>Z.group===$);return[...b.people]}function Hz($,Z,Y,Q){let z=z1($);if(!z)return null;let J={id:n6(),personId:z.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return b={...b,interactions:[...b.interactions,J]},J5(),J}function $q($,Z=10){let Y=z1($);if(!Y)return[];return[...b.interactions].filter((Q)=>Q.personId===Y.id).reverse().sort((Q,z)=>new Date(z.date).getTime()-new Date(Q.date).getTime()).slice(0,Z)}function _$(){let $=new Date,Z=[];for(let Y of b.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let z=b.people.find((J)=>J.id===Y.personId);if(z)Z.push({person:z,interaction:Y})}}return Z.sort((Y,Q)=>new Date(Y.interaction.followUpDate).getTime()-new Date(Q.interaction.followUpDate).getTime())}function G5($,Z,Y){let Q=z1($);if(!Q)return null;let z={id:n6(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return b={...b,delegations:[...b.delegations,z]},J5(),z}function Wz($,Z,Y){if(!b.delegations.find((z)=>z.id===$))return null;return b={...b,delegations:b.delegations.map((z)=>z.id===$?{...z,status:Z,notes:Y||z.notes}:z)},J5(),b.delegations.find((z)=>z.id===$)||null}function t1($,Z=!0){let Y=[...b.delegations];if($){let z=z1($);if(!z)return[];Y=Y.filter((J)=>J.personId===z.id)}if(Z)Y=Y.filter((z)=>z.status!=="concluido");let Q=new Date;return Y=Y.map((z)=>{if(z.status==="pendente"&&z.dueDate){let J=new Date(z.dueDate);if(!isNaN(J.getTime())&&J<Q)return{...z,status:"atrasado"}}return z}),Y.sort((z,J)=>{if(z.status==="atrasado"&&J.status!=="atrasado")return-1;if(J.status==="atrasado"&&z.status!=="atrasado")return 1;let X=z.dueDate?new Date(z.dueDate).getTime():1/0,K=J.dueDate?new Date(J.dueDate).getTime():1/0;return X-K})}var Bz={equipe:"Equipe",familia:"Familia",contato:"Contato"};function V5($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let z of $){let J=Z.get(z.group)||[];Z.set(z.group,[...J,z])}let Y=[],Q=["equipe","familia","contato"];for(let z of Q){let J=Z.get(z);if(!J?.length)continue;let X=J.map((K)=>{let G=K.role?` (${K.role})`:"",V=K.contact?` \u2014 ${K.contact}`:"";return` ${K.name}${G}${V} [${K.id}]`});Y.push(`--- ${Bz[z]} ---
221
230
  ${X.join(`
222
231
  `)}`)}return Y.join(`
223
232
 
224
- `)}function r7($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${EY[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=FG($.id,5);if(Y.length>0){Z.push(`
225
- Interacoes recentes:`);for(let J of Y){let z=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${z}] ${J.type}: ${J.summary}`)}}let Q=r0($.id);if(Q.length>0){Z.push(`
226
- Tarefas delegadas:`);for(let J of Q){let z=J.status==="atrasado"?"!!":J.status==="em_andamento"?">>":" ",X=J.dueDate?` (${D9(J.dueDate)})`:"";Z.push(` ${z} ${J.task}${X} [${J.status}]`)}}return Z.join(`
227
- `)}function s7($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let J=w.people.find((K)=>K.id===Y.personId)?.name||"?",z=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",X=Y.dueDate?` (${D9(Y.dueDate)})`:"";return`${z}${J}: ${Y.task}${X} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
233
+ `)}function U5($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${Bz[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=$q($.id,5);if(Y.length>0){Z.push(`
234
+ Interacoes recentes:`);for(let z of Y){let J=new Date(z.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${J}] ${z.type}: ${z.summary}`)}}let Q=t1($.id);if(Q.length>0){Z.push(`
235
+ Tarefas delegadas:`);for(let z of Q){let J=z.status==="atrasado"?"!!":z.status==="em_andamento"?">>":" ",X=z.dueDate?` (${a6(z.dueDate)})`:"";Z.push(` ${J} ${z.task}${X} [${z.status}]`)}}return Z.join(`
236
+ `)}function q5($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let z=b.people.find((K)=>K.id===Y.personId)?.name||"?",J=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",X=Y.dueDate?` (${a6(Y.dueDate)})`:"";return`${J}${z}: ${Y.task}${X} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
228
237
  ${Z.join(`
229
- `)}`}function t7($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${D9(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
238
+ `)}`}function H5($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${a6(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
230
239
  ${Z.join(`
231
- `)}`}function LY(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
232
- `);let Z=w.people.filter((G)=>G.group==="equipe").length,Y=w.people.filter((G)=>G.group==="familia").length,Q=w.people.filter((G)=>G.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let J=I1();if(J.length>0){$.push(`
233
- !! ${J.length} follow-up(s) pendente(s):`);for(let{person:G,interaction:q}of J.slice(0,5))$.push(` ${G.name}: ${q.summary}`)}let z=r0(),X=z.filter((G)=>G.status==="atrasado"),K=z.filter((G)=>G.status==="pendente"||G.status==="em_andamento");if(X.length>0){$.push(`
234
- !! ${X.length} delegacao(oes) atrasada(s):`);for(let G of X.slice(0,5)){let q=w.people.find((U)=>U.id===G.personId);$.push(` ${q?.name}: ${G.task}`)}}if(K.length>0)$.push(`
235
- ${K.length} delegacao(oes) em andamento`);let V=[...w.interactions].sort((G,q)=>new Date(q.date).getTime()-new Date(G.date).getTime()).slice(0,3);if(V.length>0){$.push(`
236
- Ultimas interacoes:`);for(let G of V){let q=w.people.find((W)=>W.id===G.personId),U=new Date(G.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${U}] ${q?.name}: ${G.summary}`)}}return $.push(`
240
+ `)}`}function Oz(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
241
+ `);let Z=b.people.filter((V)=>V.group==="equipe").length,Y=b.people.filter((V)=>V.group==="familia").length,Q=b.people.filter((V)=>V.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let z=_$();if(z.length>0){$.push(`
242
+ !! ${z.length} follow-up(s) pendente(s):`);for(let{person:V,interaction:U}of z.slice(0,5))$.push(` ${V.name}: ${U.summary}`)}let J=t1(),X=J.filter((V)=>V.status==="atrasado"),K=J.filter((V)=>V.status==="pendente"||V.status==="em_andamento");if(X.length>0){$.push(`
243
+ !! ${X.length} delegacao(oes) atrasada(s):`);for(let V of X.slice(0,5)){let U=b.people.find((q)=>q.id===V.personId);$.push(` ${U?.name}: ${V.task}`)}}if(K.length>0)$.push(`
244
+ ${K.length} delegacao(oes) em andamento`);let G=[...b.interactions].sort((V,U)=>new Date(U.date).getTime()-new Date(V.date).getTime()).slice(0,3);if(G.length>0){$.push(`
245
+ Ultimas interacoes:`);for(let V of G){let U=b.people.find((H)=>H.id===V.personId),q=new Date(V.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${q}] ${U?.name}: ${V.summary}`)}}return $.push(`
237
246
  ========================`),$.join(`
238
- `)}function j9(){return NG().slice(0,8)}function D9($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),J=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(J.getTime()===Q.getTime())return"hoje";let z=new Date(Q);if(z.setDate(z.getDate()+1),J.getTime()===z.getTime())return"amanha";let X=Math.floor((J.getTime()-Q.getTime())/86400000);if(X<0)return`${Math.abs(X)}d atras`;if(X<=7)return`em ${X}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}g();import{existsSync as jY,mkdirSync as RG,readFileSync as EG}from"fs";import{join as LG}from"path";import{randomUUID as jG}from"crypto";var DY="",l=[],PY=()=>LG(DY,"materials.json");function P9(){P(PY(),JSON.stringify(l,null,2))}function DG(){let $=PY();if(!jY($)){l=[];return}try{l=JSON.parse(EG($,"utf-8"))}catch{l=[]}}function AY($){if(DY=$,!jY($))RG($,{recursive:!0});DG()}function e7($,Z,Y="geral",Q=[]){let J=new Date().toISOString(),z=Z.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=$.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=[...new Set([...Q.map((G)=>G.toLowerCase()),...z,...X])],V={id:PG(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:K,createdAt:J,updatedAt:J};return l=[...l,V],P9(),V}function TY($,Z){let Y=l.find((G)=>G.id===$);if(!Y)return null;let Q=Z.content??Y.content,J=Z.title??Y.title,z=Q.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=J.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=Z.tags??Y.tags,V=[...new Set([...K.map((G)=>G.toLowerCase()),...z,...X])];return l=l.map((G)=>G.id===$?{...G,title:J.trim(),content:Q.trim(),category:(Z.category??G.category).toLowerCase().trim(),tags:V,updatedAt:new Date().toISOString()}:G),P9(),l.find((G)=>G.id===$)||null}function $5($){let Z=l.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return l=[...l.slice(0,Z),...l.slice(Z+1)],P9(),!0}function IY($){return l.find((Z)=>Z.id===$)||null}function S1($){let Z=$.toLowerCase().trim();if(!Z)return[...l];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),J=Y||Q?Z.slice(1):Z;return l.filter((z)=>{if(Y)return z.tags.some((X)=>X.includes(J));if(Q)return z.category.includes(J);return z.title.toLowerCase().includes(J)||z.content.toLowerCase().includes(J)||z.category.toLowerCase().includes(J)||z.tags.some((X)=>X.includes(J))}).sort((z,X)=>new Date(X.updatedAt).getTime()-new Date(z.updatedAt).getTime())}function w1($=30,Z){let Y=[...l];if(Z){let Q=Z.toLowerCase().trim();Y=Y.filter((J)=>J.category===Q)}return Y.sort((Q,J)=>new Date(J.updatedAt).getTime()-new Date(Q.updatedAt).getTime()).slice(0,$)}function SY(){let $=new Map;for(let Z of l)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,Y])=>({category:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function wY(){if(l.length===0)return"";let $=SY(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=l.filter((J)=>J.category===Y).sort((J,z)=>new Date(z.updatedAt).getTime()-new Date(J.updatedAt).getTime());Z.push(`
239
- [${Y}]`);for(let J of Q){let z=J.content.length>200?J.content.slice(0,200).replace(/\n/g," ")+"...":J.content.replace(/\n/g," "),X=J.tags.length>0?` [${J.tags.map((K)=>`#${K}`).join(" ")}]`:"";Z.push(` \u2022 ${J.title}: ${z}${X}`)}}return Z.join(`
240
- `)}function A0($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((Y)=>{let Q=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.tags.length>0?` [${Y.tags.map((X)=>`#${X}`).join(" ")}]`:"",z=Y.content.length>60?Y.content.slice(0,60).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${Q}] (${Y.category}) ${Y.title} \u2014 ${z}${J} {${Y.id}}`});return`Materiais (${$.length}):
247
+ `)}function n6(){return tU().slice(0,8)}function a6($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),z=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(z.getTime()===Q.getTime())return"hoje";let J=new Date(Q);if(J.setDate(J.getDate()+1),z.getTime()===J.getTime())return"amanha";let X=Math.floor((z.getTime()-Q.getTime())/86400000);if(X<0)return`${Math.abs(X)}d atras`;if(X<=7)return`em ${X}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}l();import{existsSync as Nz,mkdirSync as Zq,readFileSync as Yq}from"fs";import{join as Qq}from"path";import{randomUUID as zq}from"crypto";var Mz="",a=[],Cz=()=>Qq(Mz,"materials.json");function s6(){P(Cz(),JSON.stringify(a,null,2))}function Jq(){let $=Cz();if(!Nz($)){a=[];return}try{a=JSON.parse(Yq($,"utf-8"))}catch{a=[]}}function Ez($){if(Mz=$,!Nz($))Zq($,{recursive:!0});Jq()}function W5($,Z,Y="geral",Q=[]){let z=new Date().toISOString(),J=Z.match(/#(\w+)/g)?.map((V)=>V.slice(1).toLowerCase())||[],X=$.match(/#(\w+)/g)?.map((V)=>V.slice(1).toLowerCase())||[],K=[...new Set([...Q.map((V)=>V.toLowerCase()),...J,...X])],G={id:Xq(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:K,createdAt:z,updatedAt:z};return a=[...a,G],s6(),G}function Rz($,Z){let Y=a.find((V)=>V.id===$);if(!Y)return null;let Q=Z.content??Y.content,z=Z.title??Y.title,J=Q.match(/#(\w+)/g)?.map((V)=>V.slice(1).toLowerCase())||[],X=z.match(/#(\w+)/g)?.map((V)=>V.slice(1).toLowerCase())||[],K=Z.tags??Y.tags,G=[...new Set([...K.map((V)=>V.toLowerCase()),...J,...X])];return a=a.map((V)=>V.id===$?{...V,title:z.trim(),content:Q.trim(),category:(Z.category??V.category).toLowerCase().trim(),tags:G,updatedAt:new Date().toISOString()}:V),s6(),a.find((V)=>V.id===$)||null}function B5($){let Z=a.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return a=[...a.slice(0,Z),...a.slice(Z+1)],s6(),!0}function Fz($){return a.find((Z)=>Z.id===$)||null}function x$($){let Z=$.toLowerCase().trim();if(!Z)return[...a];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),z=Y||Q?Z.slice(1):Z;return a.filter((J)=>{if(Y)return J.tags.some((X)=>X.includes(z));if(Q)return J.category.includes(z);return J.title.toLowerCase().includes(z)||J.content.toLowerCase().includes(z)||J.category.toLowerCase().includes(z)||J.tags.some((X)=>X.includes(z))}).sort((J,X)=>new Date(X.updatedAt).getTime()-new Date(J.updatedAt).getTime())}function v$($=30,Z){let Y=[...a];if(Z){let Q=Z.toLowerCase().trim();Y=Y.filter((z)=>z.category===Q)}return Y.sort((Q,z)=>new Date(z.updatedAt).getTime()-new Date(Q.updatedAt).getTime()).slice(0,$)}function Lz(){let $=new Map;for(let Z of a)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,Y])=>({category:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function jz(){if(a.length===0)return"";let $=Lz(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=a.filter((z)=>z.category===Y).sort((z,J)=>new Date(J.updatedAt).getTime()-new Date(z.updatedAt).getTime());Z.push(`
248
+ [${Y}]`);for(let z of Q){let J=z.content.length>200?z.content.slice(0,200).replace(/\n/g," ")+"...":z.content.replace(/\n/g," "),X=z.tags.length>0?` [${z.tags.map((K)=>`#${K}`).join(" ")}]`:"";Z.push(` \u2022 ${z.title}: ${J}${X}`)}}return Z.join(`
249
+ `)}function S1($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((Y)=>{let Q=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Y.tags.length>0?` [${Y.tags.map((X)=>`#${X}`).join(" ")}]`:"",J=Y.content.length>60?Y.content.slice(0,60).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${Q}] (${Y.category}) ${Y.title} \u2014 ${J}${z} {${Y.id}}`});return`Materiais (${$.length}):
241
250
  ${Z.join(`
242
- `)}`}function kY($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),Y=new Date($.updatedAt).toLocaleDateString("pt-BR"),Q=$.tags.length>0?`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`:"",J=Z===Y?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${Y}`;return`--- Material {${$.id}} ---
251
+ `)}`}function Az($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),Y=new Date($.updatedAt).toLocaleDateString("pt-BR"),Q=$.tags.length>0?`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`:"",z=Z===Y?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${Y}`;return`--- Material {${$.id}} ---
243
252
  Titulo: ${$.title}
244
253
  Categoria: ${$.category}
245
254
 
246
255
  ${$.content}
247
256
 
248
257
  ${Q}
249
- ${J}`}function bY(){let $=SY();if($.length===0)return"Nenhuma categoria.";return`Categorias:
258
+ ${z}`}function Pz(){let $=Lz();if($.length===0)return"Nenhuma categoria.";return`Categorias:
250
259
  ${$.map((Y)=>` @${Y.category} (${Y.count})`).join(`
251
- `)}`}function PG(){return jG().slice(0,8)}g();import{existsSync as T$,mkdirSync as AG,readFileSync as Y5}from"fs";import{join as B$,basename as TG}from"path";import{randomUUID as IG}from"crypto";var k1="",S$=[],I$=[],v$=[],T0=null,yY=()=>B$(k1,"projects.json"),_Y=()=>B$(k1,"work-sessions.json"),xY=()=>B$(k1,"opportunities.json"),vY=()=>B$(k1,"active-project.txt");function SG(){P(yY(),JSON.stringify(S$,null,2))}function T9(){P(_Y(),JSON.stringify(I$,null,2))}function fY(){P(xY(),JSON.stringify(v$,null,2))}function wG(){P(vY(),T0||"")}function kG(){S$=A9(yY,[]),I$=A9(_Y,[]),v$=A9(xY,[]);let $=vY();if(T$($))try{T0=Y5($,"utf-8").trim()||null}catch{T0=null}}function A9($,Z){let Y=$();if(!T$(Y))return Z;try{return JSON.parse(Y5(Y,"utf-8"))}catch(Q){if(process.env.DEBUG)console.error(`[projects] Failed to load ${Y}: ${Q instanceof Error?Q.message:Q}`);return Z}}function hY($){if(k1=$,!T$($))AG($,{recursive:!0});kG()}function I9($,Z,Y="",Q=[],J=[]){let z={id:S9(),name:$.trim(),path:Z.trim(),description:Y.trim(),tags:Q.map((X)=>X.trim().toLowerCase()).filter(Boolean),techStack:J.map((X)=>X.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return S$=[...S$,z],SG(),z}function Q5($){let Z=$.toLowerCase().trim();return S$.find((Y)=>Y.id===$)||S$.find((Y)=>Y.name.toLowerCase()===Z)||S$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function b1($=!1){return($?S$.filter((Y)=>Y.active):[...S$]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function y1($){let Z=Q5($);if(!Z)return null;return T0=Z.id,wG(),Z}function I0(){if(!T0)return null;return S$.find(($)=>$.id===T0)||null}function J5($,Z=""){if(!S$.find((J)=>J.id===$))return null;bG($);let Q={id:S9(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return I$=[...I$,Q],T9(),Q}function z5($,Z){let Y=I$.find((X)=>X.id===$);if(!Y||Y.endedAt)return null;let Q=new Date,J=new Date(Y.startedAt),z=Math.round((Q.getTime()-J.getTime())/60000);return I$=I$.map((X)=>X.id===$?{...X,endedAt:Q.toISOString(),durationMinutes:z,notes:Z?`${X.notes}
252
- ${Z}`.trim():X.notes}:X),T9(),I$.find((X)=>X.id===$)||null}function bG($){let Z=new Date;I$=I$.map((Y)=>{if(Y.projectId===$&&!Y.endedAt){let Q=new Date(Y.startedAt),J=Math.round((Z.getTime()-Q.getTime())/60000);return{...Y,endedAt:Z.toISOString(),durationMinutes:J}}return Y}),T9()}function S0($){return I$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function yG($,Z,Y){let Q=Y||new Date;return I$.filter((J)=>{if(J.projectId!==$)return!1;let z=new Date(J.startedAt);return z>=Z&&z<=Q})}async function _G($,Z="1 day ago"){if(!T$(B$($,".git")))return null;try{let Y=await Z5(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!Y.ok||!Y.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Q=Y.stdout.trim().split(`
253
- `).filter(Boolean),J=[...new Set(Q.map((M)=>M.split("|||")[0]))],z=Q.map((M)=>M.split("|||")[1]||"").filter(Boolean),X=await Z5(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),K=await Z5(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),V=0,G=0,q=0;if(K.ok&&K.stdout.trim())for(let M of K.stdout.trim().split(`
254
- `)){let N=M.match(/(\d+)\s+files?\s+changed/),F=M.match(/(\d+)\s+insertions?/),j=M.match(/(\d+)\s+deletions?/);if(N)V+=parseInt(N[1]);if(F)G+=parseInt(F[1]);if(j)q+=parseInt(j[1])}let U=await Z5(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),W=new Map;if(U.ok&&U.stdout.trim())for(let M of U.stdout.trim().split(`
255
- `).filter(Boolean))W.set(M,(W.get(M)||0)+1);let B=[...W.entries()].sort((M,N)=>N[1]-M[1]).slice(0,10).map(([M])=>M);return{commits:Q.length,authors:J,filesChanged:V,insertions:G,deletions:q,topFiles:B,messages:z}}catch{return null}}async function Z5($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Q,J]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),z=await Y.exited;return{stdout:Q.trim(),stderr:J.trim(),ok:z===0}}function gY($,Z,Y,Q=[],J="media",z=null){let X=new Date().toISOString(),K={id:S9(),title:$.trim(),description:Z.trim(),source:Y.trim(),techRequired:Q.map((V)=>V.toLowerCase()),priority:J,status:"nova",deadline:z,createdAt:X,updatedAt:X};return v$=[...v$,K],fY(),K}function mY($,Z){if(!v$.find((Q)=>Q.id===$))return null;return v$=v$.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),fY(),v$.find((Q)=>Q.id===$)||null}function X5($,Z){let Y=[...v$];if($)Y=Y.filter((Q)=>Q.status===$);if(Z&&Z.length>0){let Q=Z.map((J)=>J.toLowerCase());Y=Y.filter((J)=>J.techRequired.some((z)=>Q.includes(z)))}return Y.sort((Q,J)=>{let z={alta:3,media:2,baixa:1};return(z[J.priority]||0)-(z[Q.priority]||0)})}async function K5($,Z="today",Y="pt"){let Q=Q5($);if(!Q)return null;let z=new Date(new Date);switch(Z){case"today":z.setHours(0,0,0,0);break;case"week":z.setDate(z.getDate()-7);break;case"month":z.setDate(z.getDate()-30);break}let X=Z==="today"?"1 day ago":Z==="week"?"7 days ago":"30 days ago",K=await _G(Q.path,X),V=yG(Q.id,z),G=V.reduce((W,B)=>W+B.durationMinutes,0),q=0;try{let W=B$(k1,"tasks.json");if(T$(W))q=JSON.parse(Y5(W,"utf-8")).filter((M)=>{if(!M.done)return!1;return new Date(M.createdAt)>=z}).length}catch{}let U=xG(Q,Z,K,V,G,q,Y);return{project:Q,period:Z,gitSummary:K,sessions:V,totalMinutes:G,completedTasks:q,markdown:U}}function xG($,Z,Y,Q,J,z,X){let K=X==="pt",V=[],G=new Date,q=G.toLocaleDateString(K?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(V.push(`# ${K?"Relatorio de Progresso":"Work Progress Report"}`),V.push(`**${K?"Projeto":"Project"}:** ${$.name}`),V.push(`**${K?"Periodo":"Period"}:** ${Z} (${q})`),V.push(`**${K?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)V.push(`**Tech:** ${$.techStack.join(", ")}`);V.push("");let U=Math.floor(J/60),W=J%60;if(V.push(`## ${K?"Tempo Trabalhado":"Time Tracked"}`),V.push(`- **${K?"Total":"Total"}:** ${U}h ${W}m`),V.push(`- **${K?"Sessoes":"Sessions"}:** ${Q.length}`),z>0)V.push(`- **${K?"Tarefas concluidas":"Tasks completed"}:** ${z}`);if(V.push(""),Y&&Y.commits>0){if(V.push(`## ${K?"Atividade Git":"Git Activity"}`),V.push(`- **Commits:** ${Y.commits}`),Y.authors.length>0)V.push(`- **${K?"Autores":"Authors"}:** ${Y.authors.join(", ")}`);if(V.push(`- **${K?"Arquivos alterados":"Files changed"}:** ${Y.filesChanged}`),V.push(`- **${K?"Linhas":"Lines"}:** +${Y.insertions} / -${Y.deletions}`),Y.messages.length>0){V.push(""),V.push(`### ${K?"Commits recentes":"Recent commits"}`);for(let B of Y.messages.slice(0,15))V.push(`- ${B}`)}if(Y.topFiles.length>0){V.push(""),V.push(`### ${K?"Arquivos mais alterados":"Most changed files"}`);for(let B of Y.topFiles.slice(0,8))V.push(`- \`${B}\``)}V.push("")}else V.push(`## ${K?"Atividade Git":"Git Activity"}`),V.push(K?"_Nenhum commit no periodo._":"_No commits in this period._"),V.push("");if(Q.length>0){V.push(`## ${K?"Sessoes de Trabalho":"Work Sessions"}`);for(let B of Q){let M=new Date(B.startedAt).toLocaleTimeString(K?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),N=B.durationMinutes>0?`${B.durationMinutes}m`:K?"em andamento":"ongoing",F=B.notes?` \u2014 ${B.notes}`:"";V.push(`- ${M} (${N})${F}`)}V.push("")}return V.push("---"),V.push(K?`_Gerado por smolerclaw em ${G.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${G.toLocaleString("en-US")}_`),V.join(`
256
- `)}function V5($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===T0?" [ATIVO]":"",J=Y.active?"":" (inativo)",z=Y.techStack.length>0?` [${Y.techStack.join(", ")}]`:"";return` ${Y.name}${Q}${J}${z} \u2014 ${Y.path} {${Y.id}}`});return`Projetos (${$.length}):
260
+ `)}`}function Xq(){return zq().slice(0,8)}l();import{existsSync as y0,mkdirSync as Kq,readFileSync as N5}from"fs";import{join as R0,basename as Gq}from"path";import{randomUUID as Vq}from"crypto";var h$="",x0=[],_0=[],c0=[],w1=null,Dz=()=>R0(h$,"projects.json"),Tz=()=>R0(h$,"work-sessions.json"),Iz=()=>R0(h$,"opportunities.json"),Sz=()=>R0(h$,"active-project.txt");function Uq(){P(Dz(),JSON.stringify(x0,null,2))}function e6(){P(Tz(),JSON.stringify(_0,null,2))}function wz(){P(Iz(),JSON.stringify(c0,null,2))}function qq(){P(Sz(),w1||"")}function Hq(){x0=t6(Dz,[]),_0=t6(Tz,[]),c0=t6(Iz,[]);let $=Sz();if(y0($))try{w1=N5($,"utf-8").trim()||null}catch{w1=null}}function t6($,Z){let Y=$();if(!y0(Y))return Z;try{return JSON.parse(N5(Y,"utf-8"))}catch(Q){if(process.env.DEBUG)console.error(`[projects] Failed to load ${Y}: ${Q instanceof Error?Q.message:Q}`);return Z}}function kz($){if(h$=$,!y0($))Kq($,{recursive:!0});Hq()}function $Z($,Z,Y="",Q=[],z=[]){let J={id:ZZ(),name:$.trim(),path:Z.trim(),description:Y.trim(),tags:Q.map((X)=>X.trim().toLowerCase()).filter(Boolean),techStack:z.map((X)=>X.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return x0=[...x0,J],Uq(),J}function M5($){let Z=$.toLowerCase().trim();return x0.find((Y)=>Y.id===$)||x0.find((Y)=>Y.name.toLowerCase()===Z)||x0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function g$($=!1){return($?x0.filter((Y)=>Y.active):[...x0]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function m$($){let Z=M5($);if(!Z)return null;return w1=Z.id,qq(),Z}function k1(){if(!w1)return null;return x0.find(($)=>$.id===w1)||null}function C5($,Z=""){if(!x0.find((z)=>z.id===$))return null;Wq($);let Q={id:ZZ(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return _0=[..._0,Q],e6(),Q}function E5($,Z){let Y=_0.find((X)=>X.id===$);if(!Y||Y.endedAt)return null;let Q=new Date,z=new Date(Y.startedAt),J=Math.round((Q.getTime()-z.getTime())/60000);return _0=_0.map((X)=>X.id===$?{...X,endedAt:Q.toISOString(),durationMinutes:J,notes:Z?`${X.notes}
261
+ ${Z}`.trim():X.notes}:X),e6(),_0.find((X)=>X.id===$)||null}function Wq($){let Z=new Date;_0=_0.map((Y)=>{if(Y.projectId===$&&!Y.endedAt){let Q=new Date(Y.startedAt),z=Math.round((Z.getTime()-Q.getTime())/60000);return{...Y,endedAt:Z.toISOString(),durationMinutes:z}}return Y}),e6()}function f1($){return _0.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function Bq($,Z,Y){let Q=Y||new Date;return _0.filter((z)=>{if(z.projectId!==$)return!1;let J=new Date(z.startedAt);return J>=Z&&J<=Q})}async function Oq($,Z="1 day ago"){if(!y0(R0($,".git")))return null;try{let Y=await O5(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!Y.ok||!Y.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Q=Y.stdout.trim().split(`
262
+ `).filter(Boolean),z=[...new Set(Q.map((O)=>O.split("|||")[0]))],J=Q.map((O)=>O.split("|||")[1]||"").filter(Boolean),X=await O5(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),K=await O5(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),G=0,V=0,U=0;if(K.ok&&K.stdout.trim())for(let O of K.stdout.trim().split(`
263
+ `)){let M=O.match(/(\d+)\s+files?\s+changed/),C=O.match(/(\d+)\s+insertions?/),F=O.match(/(\d+)\s+deletions?/);if(M)G+=parseInt(M[1]);if(C)V+=parseInt(C[1]);if(F)U+=parseInt(F[1])}let q=await O5(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),H=new Map;if(q.ok&&q.stdout.trim())for(let O of q.stdout.trim().split(`
264
+ `).filter(Boolean))H.set(O,(H.get(O)||0)+1);let B=[...H.entries()].sort((O,M)=>M[1]-O[1]).slice(0,10).map(([O])=>O);return{commits:Q.length,authors:z,filesChanged:G,insertions:V,deletions:U,topFiles:B,messages:J}}catch{return null}}async function O5($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Q,z]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),J=await Y.exited;return{stdout:Q.trim(),stderr:z.trim(),ok:J===0}}function fz($,Z,Y,Q=[],z="media",J=null){let X=new Date().toISOString(),K={id:ZZ(),title:$.trim(),description:Z.trim(),source:Y.trim(),techRequired:Q.map((G)=>G.toLowerCase()),priority:z,status:"nova",deadline:J,createdAt:X,updatedAt:X};return c0=[...c0,K],wz(),K}function bz($,Z){if(!c0.find((Q)=>Q.id===$))return null;return c0=c0.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),wz(),c0.find((Q)=>Q.id===$)||null}function R5($,Z){let Y=[...c0];if($)Y=Y.filter((Q)=>Q.status===$);if(Z&&Z.length>0){let Q=Z.map((z)=>z.toLowerCase());Y=Y.filter((z)=>z.techRequired.some((J)=>Q.includes(J)))}return Y.sort((Q,z)=>{let J={alta:3,media:2,baixa:1};return(J[z.priority]||0)-(J[Q.priority]||0)})}async function F5($,Z="today",Y="pt"){let Q=M5($);if(!Q)return null;let J=new Date(new Date);switch(Z){case"today":J.setHours(0,0,0,0);break;case"week":J.setDate(J.getDate()-7);break;case"month":J.setDate(J.getDate()-30);break}let X=Z==="today"?"1 day ago":Z==="week"?"7 days ago":"30 days ago",K=await Oq(Q.path,X),G=Bq(Q.id,J),V=G.reduce((H,B)=>H+B.durationMinutes,0),U=0;try{let H=R0(h$,"tasks.json");if(y0(H))U=JSON.parse(N5(H,"utf-8")).filter((O)=>{if(!O.done)return!1;return new Date(O.createdAt)>=J}).length}catch{}let q=Nq(Q,Z,K,G,V,U,Y);return{project:Q,period:Z,gitSummary:K,sessions:G,totalMinutes:V,completedTasks:U,markdown:q}}function Nq($,Z,Y,Q,z,J,X){let K=X==="pt",G=[],V=new Date,U=V.toLocaleDateString(K?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(G.push(`# ${K?"Relatorio de Progresso":"Work Progress Report"}`),G.push(`**${K?"Projeto":"Project"}:** ${$.name}`),G.push(`**${K?"Periodo":"Period"}:** ${Z} (${U})`),G.push(`**${K?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)G.push(`**Tech:** ${$.techStack.join(", ")}`);G.push("");let q=Math.floor(z/60),H=z%60;if(G.push(`## ${K?"Tempo Trabalhado":"Time Tracked"}`),G.push(`- **${K?"Total":"Total"}:** ${q}h ${H}m`),G.push(`- **${K?"Sessoes":"Sessions"}:** ${Q.length}`),J>0)G.push(`- **${K?"Tarefas concluidas":"Tasks completed"}:** ${J}`);if(G.push(""),Y&&Y.commits>0){if(G.push(`## ${K?"Atividade Git":"Git Activity"}`),G.push(`- **Commits:** ${Y.commits}`),Y.authors.length>0)G.push(`- **${K?"Autores":"Authors"}:** ${Y.authors.join(", ")}`);if(G.push(`- **${K?"Arquivos alterados":"Files changed"}:** ${Y.filesChanged}`),G.push(`- **${K?"Linhas":"Lines"}:** +${Y.insertions} / -${Y.deletions}`),Y.messages.length>0){G.push(""),G.push(`### ${K?"Commits recentes":"Recent commits"}`);for(let B of Y.messages.slice(0,15))G.push(`- ${B}`)}if(Y.topFiles.length>0){G.push(""),G.push(`### ${K?"Arquivos mais alterados":"Most changed files"}`);for(let B of Y.topFiles.slice(0,8))G.push(`- \`${B}\``)}G.push("")}else G.push(`## ${K?"Atividade Git":"Git Activity"}`),G.push(K?"_Nenhum commit no periodo._":"_No commits in this period._"),G.push("");if(Q.length>0){G.push(`## ${K?"Sessoes de Trabalho":"Work Sessions"}`);for(let B of Q){let O=new Date(B.startedAt).toLocaleTimeString(K?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),M=B.durationMinutes>0?`${B.durationMinutes}m`:K?"em andamento":"ongoing",C=B.notes?` \u2014 ${B.notes}`:"";G.push(`- ${O} (${M})${C}`)}G.push("")}return G.push("---"),G.push(K?`_Gerado por smolerclaw em ${V.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${V.toLocaleString("en-US")}_`),G.join(`
265
+ `)}function L5($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===w1?" [ATIVO]":"",z=Y.active?"":" (inativo)",J=Y.techStack.length>0?` [${Y.techStack.join(", ")}]`:"";return` ${Y.name}${Q}${z}${J} \u2014 ${Y.path} {${Y.id}}`});return`Projetos (${$.length}):
257
266
  ${Z.join(`
258
- `)}`}function G5($){let Z=$.id===T0?" [ATIVO]":"",Y=[`--- Projeto {${$.id}}${Z} ---`,`Nome: ${$.name}`,`Caminho: ${$.path}`];if($.description)Y.push(`Descricao: ${$.description}`);if($.techStack.length>0)Y.push(`Tech: ${$.techStack.join(", ")}`);if($.tags.length>0)Y.push(`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`);Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(`Status: ${$.active?"ativo":"inativo"}`);let Q=S0($.id);if(Q){let J=new Date(Q.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta: desde ${J}`)}return Y.join(`
259
- `)}function q5($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((Y)=>{let Q={alta:"!!!",media:"!!",baixa:"!"}[Y.priority],J=Y.techRequired.length>0?` [${Y.techRequired.join(", ")}]`:"",z=Y.deadline?` \u2014 prazo: ${Y.deadline}`:"";return` ${Q} (${Y.status}) ${Y.title}${J}${z} \u2014 ${Y.source} {${Y.id}}`});return`Oportunidades (${$.length}):
267
+ `)}`}function j5($){let Z=$.id===w1?" [ATIVO]":"",Y=[`--- Projeto {${$.id}}${Z} ---`,`Nome: ${$.name}`,`Caminho: ${$.path}`];if($.description)Y.push(`Descricao: ${$.description}`);if($.techStack.length>0)Y.push(`Tech: ${$.techStack.join(", ")}`);if($.tags.length>0)Y.push(`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`);Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(`Status: ${$.active?"ativo":"inativo"}`);let Q=f1($.id);if(Q){let z=new Date(Q.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta: desde ${z}`)}return Y.join(`
268
+ `)}function A5($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((Y)=>{let Q={alta:"!!!",media:"!!",baixa:"!"}[Y.priority],z=Y.techRequired.length>0?` [${Y.techRequired.join(", ")}]`:"",J=Y.deadline?` \u2014 prazo: ${Y.deadline}`:"";return` ${Q} (${Y.status}) ${Y.title}${z}${J} \u2014 ${Y.source} {${Y.id}}`});return`Oportunidades (${$.length}):
260
269
  ${Z.join(`
261
- `)}`}function U5(){let $=I0();if(!$)return"";let Z=S0($.id),Y=v$.filter((J)=>J.status==="nova").length,Q=["--- Projetos ---"];if(Q.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let J=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Q.push(`Sessao aberta desde ${J}`)}if(Y>0)Q.push(`${Y} oportunidade(s) nova(s) pendente(s)`);return Q.join(`
262
- `)}function H5($){let Z=S$.find((J)=>J.path===$);if(Z)return Z;if(!T$(B$($,".git")))return null;let Y=[];if(T$(B$($,"package.json")))try{let J=JSON.parse(Y5(B$($,"package.json"),"utf-8"));if(J.dependencies?.typescript||J.devDependencies?.typescript)Y.push("typescript");if(J.dependencies?.react)Y.push("react");if(J.dependencies?.next)Y.push("nextjs");if(J.dependencies?.vue)Y.push("vue");if(T$(B$($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(T$(B$($,"Cargo.toml")))Y.push("rust");if(T$(B$($,"go.mod")))Y.push("go");if(T$(B$($,"requirements.txt"))||T$(B$($,"pyproject.toml")))Y.push("python");let Q=TG($);return I9(Q,$,"",[],Y)}function S9(){return IG().slice(0,8)}g();o();import{existsSync as b9,mkdirSync as vG,readFileSync as dY}from"fs";import{join as cY,basename as fG}from"path";var lY=2,oY="pitwall-baselines.json",hG=0.1,gG=0.05,mG=5000000,uG=512000,uY=2048,pG=120000,M5="",e=[];function iY($){if(M5=$,!b9($))vG($,{recursive:!0});rG()}async function pY($,Z){let Q=[...q1(),$],J=process.cpuUsage(),z=Bun.nanoseconds(),X=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),K=setTimeout(()=>X.kill(),pG),V=X.pid,G=dG(V),[,q]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),U=await X.exited;clearTimeout(K);let W=Bun.nanoseconds(),B=process.cpuUsage(J),M=await G,N=q.length>uY?`...${q.slice(-uY)}`:q;return{durationNs:W-z,peakMemoryBytes:M,cpuUserUs:B.user,cpuSystemUs:B.system,exitCode:U,stderr:N.trim()}}async function y9($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),J=Z.scriptKey||nG($);if(Z.warmup&&Q>1)await pY($,Y);let z=[];for(let q=0;q<Q;q++)z.push(await pY($,Y));let X=z[z.length-1],K=z.map((q)=>q.durationNs),V={durationNs:w9(K),peakMemoryBytes:Math.max(...z.map((q)=>q.peakMemoryBytes)),cpuUserUs:w9(z.map((q)=>q.cpuUserUs)),cpuSystemUs:w9(z.map((q)=>q.cpuSystemUs))},G=Q>1?{min:Math.min(...K),max:Math.max(...K),median:V.durationNs,stddev:aG(K)}:null;return{scriptKey:J,command:$,metrics:V,spread:G,exitCode:X.exitCode,stderr:X.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function dG($){try{if(L){let Z=`(Get-Process -Id ${$} -ErrorAction SilentlyContinue).PeakWorkingSet64`,Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>Y.kill(),5000),J=await new Response(Y.stdout).text();await Y.exited,clearTimeout(Q);let z=parseInt(J.trim(),10);if(!isNaN(z)&&z>0)return z}else{let Z=`/proc/${$}/status`;if(b9(Z)){let Q=dY(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function aY($,Z=[]){let Y=e.find((z)=>z.scriptKey===$.scriptKey),Q=new Date().toISOString();if(Y){let z=Y.runs+1,X={durationNs:Math.round((Y.metrics.durationNs*Y.runs+$.metrics.durationNs)/z),peakMemoryBytes:Math.round((Y.metrics.peakMemoryBytes*Y.runs+$.metrics.peakMemoryBytes)/z),cpuUserUs:Math.round((Y.metrics.cpuUserUs*Y.runs+$.metrics.cpuUserUs)/z),cpuSystemUs:Math.round((Y.metrics.cpuSystemUs*Y.runs+$.metrics.cpuSystemUs)/z)},K={...Y,metrics:X,spread:$.spread||Y.spread,updatedAt:Q,runs:z,tags:[...new Set([...Y.tags,...Z])]};return e=e.map((V)=>V.scriptKey===$.scriptKey?K:V),C5(),K}let J={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return e=[...e,J],C5(),J}function cG($){return e.find((Z)=>Z.scriptKey===$)||null}function nY(){return[...e].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function _9($){let Z=e.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return e=[...e.slice(0,Z),...e.slice(Z+1)],C5(),!0}function rY($,Z=[]){_9($.scriptKey);let Y=new Date().toISOString(),Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return e=[...e,Q],C5(),Q}function x9($){let Z=cG($.scriptKey),Y=[];if(Z)Y.push(W5("duration",Z.metrics.durationNs,$.metrics.durationNs,mG),W5("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,uG),W5("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),W5("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((z)=>z.severity==="regression"),J=iG($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:J}}function W5($,Z,Y,Q){let J=Y-Z;if(Z===0||Math.abs(J)<Q)return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:0,absoluteDelta:J,severity:"ok"};let z=J/Z,X="ok";if(z>hG)X="regression";else if(z>gG)X="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(z*1e4)/100,absoluteDelta:J,severity:X}}function $0($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function k9($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function B5($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function lG($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function oG($){switch($){case"duration":return"Duracao";case"memory":return"Memoria (peak)";case"cpu_user":return"CPU (user)";case"cpu_system":return"CPU (sys)";default:return $}}function iG($,Z,Y,Q){let J=[];if(Q)J.push("=== PIT WALL: REGRESSAO DETECTADA ===");else J.push("=== Pit Wall: Relatorio de Performance ===");if(J.push(`Script: ${$.scriptKey}`),J.push(`Comando: ${$.command}`),J.push(`Execucoes: ${$.iterations}`),$.exitCode!==0)J.push(`Exit code: ${$.exitCode} (FALHA)`);if(J.push(""),J.push("--- Metricas Atuais ---"),J.push(` Duracao: ${$0($.metrics.durationNs)}`),J.push(` Memoria: ${k9($.metrics.peakMemoryBytes)}`),J.push(` CPU (user): ${B5($.metrics.cpuUserUs)}`),J.push(` CPU (sys): ${B5($.metrics.cpuSystemUs)}`),$.spread){J.push(""),J.push("--- Dispersao ---"),J.push(` Min: ${$0($.spread.min)}`),J.push(` Max: ${$0($.spread.max)}`),J.push(` Mediana: ${$0($.spread.median)}`),J.push(` Stddev: ${$0($.spread.stddev)}`);let z=$.spread.median>0?($.spread.stddev/$.spread.median*100).toFixed(1):"0";if(J.push(` CV: ${z}%`),parseFloat(z)>15)J.push(" (!) Alta variancia \u2014 resultados podem ser inst\xE1veis")}if($.exitCode!==0&&$.stderr)J.push(""),J.push("--- Stderr ---"),J.push($.stderr.slice(0,500));if(J.push(""),!Z)return J.push("Nenhum baseline salvo para este script."),J.push("Use pitwall_save_baseline para definir o baseline atual."),J.join(`
263
- `);J.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${sY(Z.updatedAt)}) ---`),J.push(` Duracao: ${$0(Z.metrics.durationNs)}`),J.push(` Memoria: ${k9(Z.metrics.peakMemoryBytes)}`),J.push(` CPU (user): ${B5(Z.metrics.cpuUserUs)}`),J.push(` CPU (sys): ${B5(Z.metrics.cpuSystemUs)}`),J.push(""),J.push("--- Comparacao ---");for(let z of Y){let X=z.deltaPercent>=0?"+":"",K=oG(z.metric);J.push(` ${lG(z.severity)} ${K}: ${X}${z.deltaPercent}%`)}if(J.push(""),Q)J.push("*** ALERTA: Regressao de performance > 10% detectada! ***"),J.push("Revise as mudancas recentes no codigo.");else if(Y.some((z)=>z.severity==="warning"))J.push("Atencao: algumas metricas estao proximas do limite (5-10%).");else J.push("Performance dentro do esperado.");return J.join(`
264
- `)}function sY($){let Z=Date.now()-new Date($).getTime(),Y=Math.floor(Z/60000);if(Y<60)return`ha ${Y}min`;let Q=Math.floor(Y/60);if(Q<24)return`ha ${Q}h`;return`ha ${Math.floor(Q/24)}d`}function tY($){if($.length===0)return"Nenhum baseline salvo no Pit Wall.";let Z=["=== Pit Wall: Baselines ===",""];for(let Y of $){let Q=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"",J=sY(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${$0(Y.metrics.durationNs)} | Memoria: ${k9(Y.metrics.peakMemoryBytes)} | ${Y.runs} runs | ${J}${Q}`),Y.spread){let z=Y.spread.median>0?(Y.spread.stddev/Y.spread.median*100).toFixed(1):"0";Z.push(` Spread: ${$0(Y.spread.min)} ~ ${$0(Y.spread.max)} (CV ${z}%)`)}Z.push("")}return Z.join(`
265
- `)}function w9($){if($.length===0)return 0;let Z=[...$].sort((Q,J)=>Q-J),Y=Math.floor(Z.length/2);return Z.length%2!==0?Z[Y]:Math.round((Z[Y-1]+Z[Y])/2)}function aG($){if($.length<2)return 0;let Z=$.reduce((Q,J)=>Q+J,0)/$.length,Y=$.reduce((Q,J)=>Q+(J-Z)**2,0)/($.length-1);return Math.round(Math.sqrt(Y))}function nG($){let Z=$.trim().split(/\s+/);if(Z.length>=3&&["bun","npm","yarn","pnpm"].includes(Z[0])&&Z[1]==="run")return Z[2];if(Z.length>=2&&["bun","npm","yarn","pnpm"].includes(Z[0]))return Z[1];return fG(Z[0])}function rG(){let $=cY(M5,oY);if(!b9($)){e=[];return}try{let Z=JSON.parse(dY($,"utf-8"));if(Z.version!==lY&&Z.version!==1){e=[];return}e=(Z.baselines||[]).map(sG)}catch{e=[]}}function sG($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function C5(){if(!M5)return;let $=cY(M5,oY);P($,JSON.stringify({baselines:e,version:lY},null,2))}o();import{readdirSync as tG,readFileSync as eG,lstatSync as $q}from"fs";import{join as Zq,resolve as a8,relative as v9,dirname as Yq,extname as Qq}from"path";var Jq=[".ts",".tsx",".mts",".cts"],zq=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],Xq=new Set(p1),eY=5000,Kq=5000,$Q=new Map;function Vq($){let Z=$Q.get($);if(Z&&Date.now()-Z.ts<Kq)return Z.graph;return null}function Gq($,Z){$Q.set($,{graph:Z,ts:Date.now()})}var qq=[/^import\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/gm,/^import\s+['"]([^'"]+)['"]/gm,/^export\s+(?:type\s+)?(?:\*|{[^}]*})\s+from\s+['"]([^'"]+)['"]/gm,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function Uq($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of qq){Q.lastIndex=0;let J;while((J=Q.exec(Y))!==null){let z=J[1];if(z.startsWith("./")||z.startsWith("../"))Z.add(z)}}return[...Z]}function Hq($){let Z=[];function Y(Q){if(Z.length>=eY)return;let J;try{J=tG(Q)}catch{return}for(let z of J){if(Z.length>=eY)return;if(Xq.has(z))continue;let X=Zq(Q,z),K;try{K=$q(X)}catch{continue}if(K.isSymbolicLink())continue;if(K.isDirectory())Y(X);else if(K.isFile()&&Jq.includes(Qq(z)))Z.push(X)}}return Y($),Z}function Wq($,Z,Y){let Q=Yq(Z),J=a8(Q,$);if(Y.has(J))return J;for(let z of zq){let X=J+z;if(Y.has(X))return X}return null}function f9($){let Z=a8($),Y=Vq(Z);if(Y)return Y;let Q=Hq(Z),J=new Set(Q),z=new Map,X=new Map;for(let V of Q)z.set(V,new Set),X.set(V,new Set);for(let V of Q){let G;try{G=eG(V,"utf-8")}catch{continue}let q=Uq(G),U=z.get(V);for(let W of q){let B=Wq(W,V,J);if(B){U.add(B);let M=X.get(B)||new Set;M.add(V),X.set(B,M)}}}let K={imports:z,importedBy:X,files:Q,root:Z};return Gq(Z,K),K}function h9($,Z){let Y=a8(Z),Q=$.importedBy.get(Y)||new Set,J=[...Q],z=new Set([Y]),X=[],K=new Map,V=0;for(let M of Q)X.push({file:M,depth:1}),z.add(M),K.set(M,1);let G=[],q=0;while(q<X.length){let{file:M,depth:N}=X[q++];if(N>V)V=N;if(!Q.has(M))G.push(M);let F=$.importedBy.get(M)||new Set;for(let j of F)if(!z.has(j))z.add(j),K.set(j,N+1),X.push({file:j,depth:N+1})}let U=ZQ(Y,$.importedBy,new Set,0),W=(M)=>v9($.root,M).replace(/\\/g,"/"),B=new Map;for(let[M,N]of K)B.set(W(M),N);return{target:W(Y),directDependents:J.map(W),transitiveDependents:G.map(W),depthMap:B,totalAffected:J.length+G.length,depth:V,tree:YQ(U,$.root)}}function ZQ($,Z,Y,Q){Y.add($);let J=Z.get($)||new Set,z=[];for(let X of J)if(!Y.has(X))z.push(ZQ(X,Z,Y,Q+1));return{file:$,depth:Q,children:z}}function YQ($,Z){return{file:v9(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>YQ(Y,Z))}}function QQ($,Z){let Y=a8(Z),Q=h9($,Z),J=(M)=>a8($.root,M),z=new Set([...Q.directDependents.map(J),...Q.transitiveDependents.map(J)]);z.add(Y);let X=new Map;for(let M of z)X.set(M,0);for(let M of z){let N=$.importedBy.get(M)||new Set;for(let F of N)if(z.has(F)&&F!==M)X.set(M,(X.get(M)||0)+1)}let K=[];for(let[M,N]of X)if(N===0&&M!==Y)K.push(M);let V=[],G=new Set,q=0;while(q<K.length){let M=K[q++];V.push(M),G.add(M);let N=$.imports.get(M)||new Set;for(let F of N)if(z.has(F)&&!G.has(F)&&F!==Y){let j=(X.get(F)||1)-1;if(X.set(F,j),j===0)K.push(F)}}for(let M of z)if(!G.has(M)&&M!==Y)V.push(M);let U=[Y,...V],W=(M)=>v9($.root,M).replace(/\\/g,"/"),B=U.map((M)=>{let F=[...$.imports.get(M)||new Set].filter((n)=>z.has(n)).map(W),j=W(M),p=M===Y?0:Q.depthMap.get(j)||1;return{file:j,depth:p,dependsOn:F}});return{target:W(Y),order:B,totalFiles:B.length}}function JQ($){let Z=[];if(Z.push("=== Blast Radius Analysis ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Arquivos afetados: ${$.totalAffected}`),Z.push(`Profundidade maxima: ${$.depth}`),Z.push(""),$.directDependents.length>0){Z.push(`--- Dependentes diretos (${$.directDependents.length}) ---`);for(let Y of $.directDependents)Z.push(` ${Y}`);Z.push("")}if($.transitiveDependents.length>0){Z.push(`--- Dependentes transitivos (${$.transitiveDependents.length}) ---`);for(let Y of $.transitiveDependents){let Q=$.depthMap.get(Y)||0;Z.push(` ${Y} (depth ${Q})`)}Z.push("")}if($.totalAffected===0)Z.push("Nenhum arquivo depende deste modulo. Blast radius = 0."),Z.push("");return Z.push("--- Arvore de impacto ---"),zQ($.tree,Z,"",!0),Z.join(`
266
- `)}function zQ($,Z,Y,Q){let J=Q?"\u2514\u2500 ":"\u251C\u2500 ",z=$.depth===0?`[ALVO] ${$.file}`:$.file;Z.push(`${Y}${J}${z}`);let X=Y+(Q?" ":"\u2502 ");for(let K=0;K<$.children.length;K++)zQ($.children[K],Z,X,K===$.children.length-1)}function XQ($){let Z=[];Z.push("=== Plano de Refatoracao ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Total de arquivos: ${$.totalFiles}`),Z.push(""),Z.push("Ordem segura de atualizacao:"),Z.push("");for(let Y=0;Y<$.order.length;Y++){let Q=$.order[Y],J=`${Y+1}`.padStart(3),z=Q.depth===0?"[ALVO]":`[depth ${Q.depth}]`;if(Z.push(` ${J}. ${Q.file} ${z}`),Q.dependsOn.length>0)Z.push(` depende de: ${Q.dependsOn.join(", ")}`)}return Z.push(""),Z.push("Estrategia: Altere o alvo primeiro, depois atualize"),Z.push("os dependentes de fora para dentro (folhas primeiro)."),Z.join(`
267
- `)}g();import{existsSync as g9,mkdirSync as Bq,readFileSync as VQ}from"fs";import{join as GQ}from"path";import{randomUUID as Mq}from"crypto";var m9=[{name:"maintainability",weight:0.3,description:"Code readability, modularity, ease of modification"},{name:"performance",weight:0.25,description:"Response time, throughput, resource efficiency"},{name:"learning_curve",weight:0.2,description:"Team familiarity, documentation quality, community support"},{name:"infrastructure_cost",weight:0.25,description:"Hosting, licensing, operational overhead"}],u9="",Z0=[],Y0=[],qQ=()=>GQ(u9,"engine-tradeoffs.json"),UQ=()=>GQ(u9,"engine-incidents.json");function Cq(){P(qQ(),JSON.stringify(Z0,null,2))}function Nq(){P(UQ(),JSON.stringify(Y0,null,2))}function Oq(){let $=qQ();if(!g9($)){Z0=[];return}try{Z0=JSON.parse(VQ($,"utf-8"))}catch{Z0=[]}}function Fq(){let $=UQ();if(!g9($)){Y0=[];return}try{Y0=JSON.parse(VQ($,"utf-8"))}catch{Y0=[]}}function HQ($){if(u9=$,!g9($))Bq($,{recursive:!0});Oq(),Fq()}function WQ($,Z,Y=m9){let Q=Y.reduce((q,U)=>q+U.weight,0);if(Math.abs(Q-1)>0.01)Y=Y.map((U)=>({...U,weight:U.weight/Q}));let J={};for(let q of Z){let U=0;for(let W of Y){let B=q.scores[W.name]??3;U+=B*W.weight}J[q.name]=Math.round(U*100)/100}let X=Object.entries(J).sort(([,q],[,U])=>U-q)[0]?.[0]||Z[0]?.name||"N/A",K=Z.find((q)=>q.name===X),V=Rq($,Z,Y,J,X,K),G={id:jQ(),context:$,options:Z,criteria:Y,recommendation:X,weightedScores:J,adr:V,createdAt:new Date().toISOString()};return Z0=[...Z0,G],Cq(),G}function Rq($,Z,Y,Q,J,z){let K=new Date().toISOString().split("T")[0],V=[`# ADR: ${$.title}`,"",`**Date:** ${K}`,"**Status:** Proposed","","## Context","",$.background,""];if($.constraints.length>0){V.push("### Constraints"),V.push("");for(let U of $.constraints)V.push(`- ${U}`);V.push("")}if($.stakeholders.length>0){V.push("### Stakeholders"),V.push("");for(let U of $.stakeholders)V.push(`- ${U}`);V.push("")}V.push("## Options Considered"),V.push("");for(let U of Z){if(V.push(`### ${U.name}`),V.push(""),V.push(U.description),V.push(""),U.pros.length>0){V.push("**Pros:**");for(let W of U.pros)V.push(`- ${W}`);V.push("")}if(U.cons.length>0){V.push("**Cons:**");for(let W of U.cons)V.push(`- ${W}`);V.push("")}}V.push("## Evaluation Matrix"),V.push("");let G=["Criterion (Weight)",...Z.map((U)=>U.name)];V.push(`| ${G.join(" | ")} |`),V.push(`| ${G.map(()=>"---").join(" | ")} |`);for(let U of Y){let W=Math.round(U.weight*100),B=[`${U.name} (${W}%)`,...Z.map((M)=>{return`${M.scores[U.name]??3}/5`})];V.push(`| ${B.join(" | ")} |`)}let q=["**Weighted Total**",...Z.map((U)=>`**${Q[U.name]?.toFixed(2)??"0.00"}**`)];if(V.push(`| ${q.join(" | ")} |`),V.push(""),V.push("## Decision"),V.push(""),V.push(`**Recommended:** ${J}`),V.push(""),z){if(V.push(`Based on the weighted evaluation, **${J}** scores highest with a weighted total of ${Q[J]?.toFixed(2)}.`),V.push(""),z.pros.length>0){V.push("Key advantages:");for(let U of z.pros.slice(0,3))V.push(`- ${U}`);V.push("")}}if(V.push("## Consequences"),V.push(""),V.push("### Positive"),V.push(""),z&&z.pros.length>0)for(let U of z.pros)V.push(`- ${U}`);else V.push("- *To be determined based on implementation*");if(V.push(""),V.push("### Negative"),V.push(""),z&&z.cons.length>0)for(let U of z.cons)V.push(`- ${U}`);else V.push("- *To be determined based on implementation*");return V.push(""),V.push("---"),V.push(""),V.push("*Generated by Decision Engine*"),V.join(`
268
- `)}function KQ($){let Z=$.toLowerCase(),Y=[/error/gi,/exception/gi,/fail/gi,/crash/gi,/timeout/gi,/null/gi,/undefined/gi,/nan/gi,/overflow/gi,/underflow/gi,/memory/gi,/leak/gi,/deadlock/gi,/race/gi,/condition/gi,/connection/gi,/refused/gi,/denied/gi,/unauthorized/gi,/invalid/gi,/missing/gi,/corrupt/gi,/malformed/gi],Q=new Set;for(let V of Y){let G=Z.match(V);if(G)for(let q of G)Q.add(q.toLowerCase())}let J=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,z=$.match(J)||[];for(let V of z)if(V.length>3&&!V.match(/^(the|and|for|with|from|this|that)$/i))Q.add(V.toLowerCase());let X=/[A-Z]{2,}_[A-Z0-9_]+|E[0-9]{3,}/g,K=$.match(X)||[];for(let V of K)Q.add(V.toLowerCase());return[...Q]}function Eq($,Z){if($.length===0||Z.length===0)return 0;let Y=new Set($),Q=new Set(Z),J=0;for(let X of Y)if(Q.has(X))J++;let z=Y.size+Q.size-J;return z>0?J/z:0}function BQ($,Z){let Y=Z?`${$}
269
- ${Z}`:$,Q=KQ(Y),J=[];for(let V of Y0){let G=`${V.title} ${V.description} ${V.stacktrace||""} ${V.rootCause} ${V.solution}`,q=KQ(G),U=Eq(Q,q);if(U>0.1){let W=Q.filter((N)=>q.includes(N)),B=[];for(let N of V.relatedDecisions){let F=n0(N);if(F.length>0)B.push(F[0])}let M=[];if(V.solution)M.push(`Apply solution: ${V.solution}`);if(V.rootCause)M.push(`Investigate root cause: ${V.rootCause}`);for(let N of B)M.push(`Review decision: ${N.title}`);J.push({incident:V,similarity:U,matchedKeywords:W,relatedDecisions:B,suggestedActions:M})}}J.sort((V,G)=>G.similarity-V.similarity);let z=n0($.slice(0,50)),X=S1($.slice(0,50)),K=Lq($,J,z,X);return{query:$,matches:J.slice(0,5),materialsFound:X.slice(0,5),summary:K}}function Lq($,Z,Y,Q){let J=["# Incident Correlation Report",""];if(J.push("## Query"),J.push(""),J.push("```"),J.push($.slice(0,500)),J.push("```"),J.push(""),Z.length>0){J.push("## Similar Past Incidents"),J.push("");for(let z of Z.slice(0,3)){let X=Math.round(z.similarity*100);if(J.push(`### ${z.incident.title} (${X}% match)`),J.push(""),J.push(`**Root Cause:** ${z.incident.rootCause}`),J.push(""),J.push(`**Solution:** ${z.incident.solution}`),J.push(""),z.matchedKeywords.length>0)J.push(`**Matched Keywords:** ${z.matchedKeywords.slice(0,5).join(", ")}`),J.push("");if(z.suggestedActions.length>0){J.push("**Suggested Actions:**");for(let K of z.suggestedActions.slice(0,3))J.push(`- ${K}`);J.push("")}}}else J.push("## Similar Past Incidents"),J.push(""),J.push("*No matching incidents found in the database.*"),J.push("");if(Y.length>0){J.push("## Related Decisions"),J.push("");for(let z of Y.slice(0,3))J.push(`- **${z.title}** (${z.date.split("T")[0]}): ${z.chosen}`);J.push("")}if(Q.length>0){J.push("## Relevant Materials"),J.push("");for(let z of Q.slice(0,3)){let X=z.content.length>100?z.content.slice(0,100).replace(/\n/g," ")+"...":z.content.replace(/\n/g," ");J.push(`- **${z.title}** (${z.category}): ${X}`)}J.push("")}return J.push("---"),J.push(""),J.push("*Generated by Decision Engine Post-Mortem Correlator*"),J.join(`
270
- `)}function MQ($,Z,Y,Q,J,z=[],X=[]){let K={id:jQ(),title:$.trim(),description:Z.trim(),stacktrace:J?.trim(),rootCause:Y.trim(),solution:Q.trim(),relatedDecisions:z,tags:X.map((V)=>V.toLowerCase()),createdAt:new Date().toISOString()};return Y0=[...Y0,K],Nq(),K}function CQ($){let Z=$.toLowerCase();return Y0.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.description.toLowerCase().includes(Z)||Y.rootCause.toLowerCase().includes(Z)||Y.solution.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function NQ($=10){return[...Y0].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function OQ($=10){return[...Z0].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function FQ($){let Z=$.toLowerCase();return Z0.filter((Y)=>Y.context.title.toLowerCase().includes(Z)||Y.context.background.toLowerCase().includes(Z)||Y.recommendation.toLowerCase().includes(Z)||Y.options.some((Q)=>Q.name.toLowerCase().includes(Z)||Q.description.toLowerCase().includes(Z))).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function RQ($){return Z0.find((Z)=>Z.id===$)||null}function EQ($){if($.length===0)return"Nenhuma analise de trade-off registrada.";let Z=$.map((Y)=>{return` [${new Date(Y.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}] ${Y.context.title} \u2192 ${Y.recommendation} {${Y.id}}`});return`Trade-offs (${$.length}):
270
+ `)}`}function P5(){let $=k1();if(!$)return"";let Z=f1($.id),Y=c0.filter((z)=>z.status==="nova").length,Q=["--- Projetos ---"];if(Q.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let z=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Q.push(`Sessao aberta desde ${z}`)}if(Y>0)Q.push(`${Y} oportunidade(s) nova(s) pendente(s)`);return Q.join(`
271
+ `)}function D5($){let Z=x0.find((z)=>z.path===$);if(Z)return Z;if(!y0(R0($,".git")))return null;let Y=[];if(y0(R0($,"package.json")))try{let z=JSON.parse(N5(R0($,"package.json"),"utf-8"));if(z.dependencies?.typescript||z.devDependencies?.typescript)Y.push("typescript");if(z.dependencies?.react)Y.push("react");if(z.dependencies?.next)Y.push("nextjs");if(z.dependencies?.vue)Y.push("vue");if(y0(R0($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(y0(R0($,"Cargo.toml")))Y.push("rust");if(y0(R0($,"go.mod")))Y.push("go");if(y0(R0($,"requirements.txt"))||y0(R0($,"pyproject.toml")))Y.push("python");let Q=Gq($);return $Z(Q,$,"",[],Y)}function ZZ(){return Vq().slice(0,8)}l();s();import{existsSync as zZ,mkdirSync as Mq,readFileSync as xz}from"fs";import{join as vz,basename as Cq}from"path";var hz=2,gz="pitwall-baselines.json",Eq=0.1,Rq=0.05,Fq=5000000,Lq=512000,yz=2048,jq=120000,S5="",J0=[];function mz($){if(S5=$,!zZ($))Mq($,{recursive:!0});kq()}async function _z($,Z){let Q=[...B$(),$],z=process.cpuUsage(),J=Bun.nanoseconds(),X=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),K=setTimeout(()=>X.kill(),jq),G=X.pid,V=Aq(G),[,U]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),q=await X.exited;clearTimeout(K);let H=Bun.nanoseconds(),B=process.cpuUsage(z),O=await V,M=U.length>yz?`...${U.slice(-yz)}`:U;return{durationNs:H-J,peakMemoryBytes:O,cpuUserUs:B.user,cpuSystemUs:B.system,exitCode:q,stderr:M.trim()}}async function JZ($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),z=Z.scriptKey||wq($);if(Z.warmup&&Q>1)await _z($,Y);let J=[];for(let U=0;U<Q;U++)J.push(await _z($,Y));let X=J[J.length-1],K=J.map((U)=>U.durationNs),G={durationNs:YZ(K),peakMemoryBytes:Math.max(...J.map((U)=>U.peakMemoryBytes)),cpuUserUs:YZ(J.map((U)=>U.cpuUserUs)),cpuSystemUs:YZ(J.map((U)=>U.cpuSystemUs))},V=Q>1?{min:Math.min(...K),max:Math.max(...K),median:G.durationNs,stddev:Sq(K)}:null;return{scriptKey:z,command:$,metrics:G,spread:V,exitCode:X.exitCode,stderr:X.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function Aq($){try{if(j){let Z=`(Get-Process -Id ${$} -ErrorAction SilentlyContinue).PeakWorkingSet64`,Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>Y.kill(),5000),z=await new Response(Y.stdout).text();await Y.exited,clearTimeout(Q);let J=parseInt(z.trim(),10);if(!isNaN(J)&&J>0)return J}else{let Z=`/proc/${$}/status`;if(zZ(Z)){let Q=xz(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function uz($,Z=[]){let Y=J0.find((J)=>J.scriptKey===$.scriptKey),Q=new Date().toISOString();if(Y){let J=Y.runs+1,X={durationNs:Math.round((Y.metrics.durationNs*Y.runs+$.metrics.durationNs)/J),peakMemoryBytes:Math.round((Y.metrics.peakMemoryBytes*Y.runs+$.metrics.peakMemoryBytes)/J),cpuUserUs:Math.round((Y.metrics.cpuUserUs*Y.runs+$.metrics.cpuUserUs)/J),cpuSystemUs:Math.round((Y.metrics.cpuSystemUs*Y.runs+$.metrics.cpuSystemUs)/J)},K={...Y,metrics:X,spread:$.spread||Y.spread,updatedAt:Q,runs:J,tags:[...new Set([...Y.tags,...Z])]};return J0=J0.map((G)=>G.scriptKey===$.scriptKey?K:G),w5(),K}let z={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return J0=[...J0,z],w5(),z}function Pq($){return J0.find((Z)=>Z.scriptKey===$)||null}function pz(){return[...J0].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function XZ($){let Z=J0.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return J0=[...J0.slice(0,Z),...J0.slice(Z+1)],w5(),!0}function dz($,Z=[]){XZ($.scriptKey);let Y=new Date().toISOString(),Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return J0=[...J0,Q],w5(),Q}function KZ($){let Z=Pq($.scriptKey),Y=[];if(Z)Y.push(T5("duration",Z.metrics.durationNs,$.metrics.durationNs,Fq),T5("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,Lq),T5("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),T5("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((J)=>J.severity==="regression"),z=Iq($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:z}}function T5($,Z,Y,Q){let z=Y-Z;if(Z===0||Math.abs(z)<Q)return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:0,absoluteDelta:z,severity:"ok"};let J=z/Z,X="ok";if(J>Eq)X="regression";else if(J>Rq)X="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(J*1e4)/100,absoluteDelta:z,severity:X}}function J1($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function QZ($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function I5($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function Dq($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function Tq($){switch($){case"duration":return"Duracao";case"memory":return"Memoria (peak)";case"cpu_user":return"CPU (user)";case"cpu_system":return"CPU (sys)";default:return $}}function Iq($,Z,Y,Q){let z=[];if(Q)z.push("=== PIT WALL: REGRESSAO DETECTADA ===");else z.push("=== Pit Wall: Relatorio de Performance ===");if(z.push(`Script: ${$.scriptKey}`),z.push(`Comando: ${$.command}`),z.push(`Execucoes: ${$.iterations}`),$.exitCode!==0)z.push(`Exit code: ${$.exitCode} (FALHA)`);if(z.push(""),z.push("--- Metricas Atuais ---"),z.push(` Duracao: ${J1($.metrics.durationNs)}`),z.push(` Memoria: ${QZ($.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${I5($.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${I5($.metrics.cpuSystemUs)}`),$.spread){z.push(""),z.push("--- Dispersao ---"),z.push(` Min: ${J1($.spread.min)}`),z.push(` Max: ${J1($.spread.max)}`),z.push(` Mediana: ${J1($.spread.median)}`),z.push(` Stddev: ${J1($.spread.stddev)}`);let J=$.spread.median>0?($.spread.stddev/$.spread.median*100).toFixed(1):"0";if(z.push(` CV: ${J}%`),parseFloat(J)>15)z.push(" (!) Alta variancia \u2014 resultados podem ser inst\xE1veis")}if($.exitCode!==0&&$.stderr)z.push(""),z.push("--- Stderr ---"),z.push($.stderr.slice(0,500));if(z.push(""),!Z)return z.push("Nenhum baseline salvo para este script."),z.push("Use pitwall_save_baseline para definir o baseline atual."),z.join(`
272
+ `);z.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${cz(Z.updatedAt)}) ---`),z.push(` Duracao: ${J1(Z.metrics.durationNs)}`),z.push(` Memoria: ${QZ(Z.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${I5(Z.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${I5(Z.metrics.cpuSystemUs)}`),z.push(""),z.push("--- Comparacao ---");for(let J of Y){let X=J.deltaPercent>=0?"+":"",K=Tq(J.metric);z.push(` ${Dq(J.severity)} ${K}: ${X}${J.deltaPercent}%`)}if(z.push(""),Q)z.push("*** ALERTA: Regressao de performance > 10% detectada! ***"),z.push("Revise as mudancas recentes no codigo.");else if(Y.some((J)=>J.severity==="warning"))z.push("Atencao: algumas metricas estao proximas do limite (5-10%).");else z.push("Performance dentro do esperado.");return z.join(`
273
+ `)}function cz($){let Z=Date.now()-new Date($).getTime(),Y=Math.floor(Z/60000);if(Y<60)return`ha ${Y}min`;let Q=Math.floor(Y/60);if(Q<24)return`ha ${Q}h`;return`ha ${Math.floor(Q/24)}d`}function lz($){if($.length===0)return"Nenhum baseline salvo no Pit Wall.";let Z=["=== Pit Wall: Baselines ===",""];for(let Y of $){let Q=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"",z=cz(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${J1(Y.metrics.durationNs)} | Memoria: ${QZ(Y.metrics.peakMemoryBytes)} | ${Y.runs} runs | ${z}${Q}`),Y.spread){let J=Y.spread.median>0?(Y.spread.stddev/Y.spread.median*100).toFixed(1):"0";Z.push(` Spread: ${J1(Y.spread.min)} ~ ${J1(Y.spread.max)} (CV ${J}%)`)}Z.push("")}return Z.join(`
274
+ `)}function YZ($){if($.length===0)return 0;let Z=[...$].sort((Q,z)=>Q-z),Y=Math.floor(Z.length/2);return Z.length%2!==0?Z[Y]:Math.round((Z[Y-1]+Z[Y])/2)}function Sq($){if($.length<2)return 0;let Z=$.reduce((Q,z)=>Q+z,0)/$.length,Y=$.reduce((Q,z)=>Q+(z-Z)**2,0)/($.length-1);return Math.round(Math.sqrt(Y))}function wq($){let Z=$.trim().split(/\s+/);if(Z.length>=3&&["bun","npm","yarn","pnpm"].includes(Z[0])&&Z[1]==="run")return Z[2];if(Z.length>=2&&["bun","npm","yarn","pnpm"].includes(Z[0]))return Z[1];return Cq(Z[0])}function kq(){let $=vz(S5,gz);if(!zZ($)){J0=[];return}try{let Z=JSON.parse(xz($,"utf-8"));if(Z.version!==hz&&Z.version!==1){J0=[];return}J0=(Z.baselines||[]).map(fq)}catch{J0=[]}}function fq($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function w5(){if(!S5)return;let $=vz(S5,gz);P($,JSON.stringify({baselines:J0,version:hz},null,2))}s();import{readdirSync as bq,readFileSync as yq,lstatSync as _q}from"fs";import{join as xq,resolve as Y8,relative as GZ,dirname as vq,extname as hq}from"path";var gq=[".ts",".tsx",".mts",".cts"],mq=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],uq=new Set(s$),oz=5000,pq=5000,iz=new Map;function dq($){let Z=iz.get($);if(Z&&Date.now()-Z.ts<pq)return Z.graph;return null}function cq($,Z){iz.set($,{graph:Z,ts:Date.now()})}var lq=[/^import\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/gm,/^import\s+['"]([^'"]+)['"]/gm,/^export\s+(?:type\s+)?(?:\*|{[^}]*})\s+from\s+['"]([^'"]+)['"]/gm,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function oq($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of lq){Q.lastIndex=0;let z;while((z=Q.exec(Y))!==null){let J=z[1];if(J.startsWith("./")||J.startsWith("../"))Z.add(J)}}return[...Z]}function iq($){let Z=[];function Y(Q){if(Z.length>=oz)return;let z;try{z=bq(Q)}catch{return}for(let J of z){if(Z.length>=oz)return;if(uq.has(J))continue;let X=xq(Q,J),K;try{K=_q(X)}catch{continue}if(K.isSymbolicLink())continue;if(K.isDirectory())Y(X);else if(K.isFile()&&gq.includes(hq(J)))Z.push(X)}}return Y($),Z}function rq($,Z,Y){let Q=vq(Z),z=Y8(Q,$);if(Y.has(z))return z;for(let J of mq){let X=z+J;if(Y.has(X))return X}return null}function VZ($){let Z=Y8($),Y=dq(Z);if(Y)return Y;let Q=iq(Z),z=new Set(Q),J=new Map,X=new Map;for(let G of Q)J.set(G,new Set),X.set(G,new Set);for(let G of Q){let V;try{V=yq(G,"utf-8")}catch{continue}let U=oq(V),q=J.get(G);for(let H of U){let B=rq(H,G,z);if(B){q.add(B);let O=X.get(B)||new Set;O.add(G),X.set(B,O)}}}let K={imports:J,importedBy:X,files:Q,root:Z};return cq(Z,K),K}function UZ($,Z){let Y=Y8(Z),Q=$.importedBy.get(Y)||new Set,z=[...Q],J=new Set([Y]),X=[],K=new Map,G=0;for(let O of Q)X.push({file:O,depth:1}),J.add(O),K.set(O,1);let V=[],U=0;while(U<X.length){let{file:O,depth:M}=X[U++];if(M>G)G=M;if(!Q.has(O))V.push(O);let C=$.importedBy.get(O)||new Set;for(let F of C)if(!J.has(F))J.add(F),K.set(F,M+1),X.push({file:F,depth:M+1})}let q=rz(Y,$.importedBy,new Set,0),H=(O)=>GZ($.root,O).replace(/\\/g,"/"),B=new Map;for(let[O,M]of K)B.set(H(O),M);return{target:H(Y),directDependents:z.map(H),transitiveDependents:V.map(H),depthMap:B,totalAffected:z.length+V.length,depth:G,tree:nz(q,$.root)}}function rz($,Z,Y,Q){Y.add($);let z=Z.get($)||new Set,J=[];for(let X of z)if(!Y.has(X))J.push(rz(X,Z,Y,Q+1));return{file:$,depth:Q,children:J}}function nz($,Z){return{file:GZ(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>nz(Y,Z))}}function az($,Z){let Y=Y8(Z),Q=UZ($,Z),z=(O)=>Y8($.root,O),J=new Set([...Q.directDependents.map(z),...Q.transitiveDependents.map(z)]);J.add(Y);let X=new Map;for(let O of J)X.set(O,0);for(let O of J){let M=$.importedBy.get(O)||new Set;for(let C of M)if(J.has(C)&&C!==O)X.set(O,(X.get(O)||0)+1)}let K=[];for(let[O,M]of X)if(M===0&&O!==Y)K.push(O);let G=[],V=new Set,U=0;while(U<K.length){let O=K[U++];G.push(O),V.add(O);let M=$.imports.get(O)||new Set;for(let C of M)if(J.has(C)&&!V.has(C)&&C!==Y){let F=(X.get(C)||1)-1;if(X.set(C,F),F===0)K.push(C)}}for(let O of J)if(!V.has(O)&&O!==Y)G.push(O);let q=[Y,...G],H=(O)=>GZ($.root,O).replace(/\\/g,"/"),B=q.map((O)=>{let C=[...$.imports.get(O)||new Set].filter((d)=>J.has(d)).map(H),F=H(O),k=O===Y?0:Q.depthMap.get(F)||1;return{file:F,depth:k,dependsOn:C}});return{target:H(Y),order:B,totalFiles:B.length}}function sz($){let Z=[];if(Z.push("=== Blast Radius Analysis ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Arquivos afetados: ${$.totalAffected}`),Z.push(`Profundidade maxima: ${$.depth}`),Z.push(""),$.directDependents.length>0){Z.push(`--- Dependentes diretos (${$.directDependents.length}) ---`);for(let Y of $.directDependents)Z.push(` ${Y}`);Z.push("")}if($.transitiveDependents.length>0){Z.push(`--- Dependentes transitivos (${$.transitiveDependents.length}) ---`);for(let Y of $.transitiveDependents){let Q=$.depthMap.get(Y)||0;Z.push(` ${Y} (depth ${Q})`)}Z.push("")}if($.totalAffected===0)Z.push("Nenhum arquivo depende deste modulo. Blast radius = 0."),Z.push("");return Z.push("--- Arvore de impacto ---"),tz($.tree,Z,"",!0),Z.join(`
275
+ `)}function tz($,Z,Y,Q){let z=Q?"\u2514\u2500 ":"\u251C\u2500 ",J=$.depth===0?`[ALVO] ${$.file}`:$.file;Z.push(`${Y}${z}${J}`);let X=Y+(Q?" ":"\u2502 ");for(let K=0;K<$.children.length;K++)tz($.children[K],Z,X,K===$.children.length-1)}function ez($){let Z=[];Z.push("=== Plano de Refatoracao ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Total de arquivos: ${$.totalFiles}`),Z.push(""),Z.push("Ordem segura de atualizacao:"),Z.push("");for(let Y=0;Y<$.order.length;Y++){let Q=$.order[Y],z=`${Y+1}`.padStart(3),J=Q.depth===0?"[ALVO]":`[depth ${Q.depth}]`;if(Z.push(` ${z}. ${Q.file} ${J}`),Q.dependsOn.length>0)Z.push(` depende de: ${Q.dependsOn.join(", ")}`)}return Z.push(""),Z.push("Estrategia: Altere o alvo primeiro, depois atualize"),Z.push("os dependentes de fora para dentro (folhas primeiro)."),Z.join(`
276
+ `)}l();import{existsSync as qZ,mkdirSync as nq,readFileSync as ZJ}from"fs";import{join as YJ}from"path";import{randomUUID as aq}from"crypto";var HZ=[{name:"maintainability",weight:0.3,description:"Code readability, modularity, ease of modification"},{name:"performance",weight:0.25,description:"Response time, throughput, resource efficiency"},{name:"learning_curve",weight:0.2,description:"Team familiarity, documentation quality, community support"},{name:"infrastructure_cost",weight:0.25,description:"Hosting, licensing, operational overhead"}],WZ="",X1=[],K1=[],QJ=()=>YJ(WZ,"engine-tradeoffs.json"),zJ=()=>YJ(WZ,"engine-incidents.json");function sq(){P(QJ(),JSON.stringify(X1,null,2))}function tq(){P(zJ(),JSON.stringify(K1,null,2))}function eq(){let $=QJ();if(!qZ($)){X1=[];return}try{X1=JSON.parse(ZJ($,"utf-8"))}catch{X1=[]}}function $H(){let $=zJ();if(!qZ($)){K1=[];return}try{K1=JSON.parse(ZJ($,"utf-8"))}catch{K1=[]}}function JJ($){if(WZ=$,!qZ($))nq($,{recursive:!0});eq(),$H()}function XJ($,Z,Y=HZ){let Q=Y.reduce((U,q)=>U+q.weight,0);if(Math.abs(Q-1)>0.01)Y=Y.map((q)=>({...q,weight:q.weight/Q}));let z={};for(let U of Z){let q=0;for(let H of Y){let B=U.scores[H.name]??3;q+=B*H.weight}z[U.name]=Math.round(q*100)/100}let X=Object.entries(z).sort(([,U],[,q])=>q-U)[0]?.[0]||Z[0]?.name||"N/A",K=Z.find((U)=>U.name===X),G=ZH($,Z,Y,z,X,K),V={id:NJ(),context:$,options:Z,criteria:Y,recommendation:X,weightedScores:z,adr:G,createdAt:new Date().toISOString()};return X1=[...X1,V],sq(),V}function ZH($,Z,Y,Q,z,J){let K=new Date().toISOString().split("T")[0],G=[`# ADR: ${$.title}`,"",`**Date:** ${K}`,"**Status:** Proposed","","## Context","",$.background,""];if($.constraints.length>0){G.push("### Constraints"),G.push("");for(let q of $.constraints)G.push(`- ${q}`);G.push("")}if($.stakeholders.length>0){G.push("### Stakeholders"),G.push("");for(let q of $.stakeholders)G.push(`- ${q}`);G.push("")}G.push("## Options Considered"),G.push("");for(let q of Z){if(G.push(`### ${q.name}`),G.push(""),G.push(q.description),G.push(""),q.pros.length>0){G.push("**Pros:**");for(let H of q.pros)G.push(`- ${H}`);G.push("")}if(q.cons.length>0){G.push("**Cons:**");for(let H of q.cons)G.push(`- ${H}`);G.push("")}}G.push("## Evaluation Matrix"),G.push("");let V=["Criterion (Weight)",...Z.map((q)=>q.name)];G.push(`| ${V.join(" | ")} |`),G.push(`| ${V.map(()=>"---").join(" | ")} |`);for(let q of Y){let H=Math.round(q.weight*100),B=[`${q.name} (${H}%)`,...Z.map((O)=>{return`${O.scores[q.name]??3}/5`})];G.push(`| ${B.join(" | ")} |`)}let U=["**Weighted Total**",...Z.map((q)=>`**${Q[q.name]?.toFixed(2)??"0.00"}**`)];if(G.push(`| ${U.join(" | ")} |`),G.push(""),G.push("## Decision"),G.push(""),G.push(`**Recommended:** ${z}`),G.push(""),J){if(G.push(`Based on the weighted evaluation, **${z}** scores highest with a weighted total of ${Q[z]?.toFixed(2)}.`),G.push(""),J.pros.length>0){G.push("Key advantages:");for(let q of J.pros.slice(0,3))G.push(`- ${q}`);G.push("")}}if(G.push("## Consequences"),G.push(""),G.push("### Positive"),G.push(""),J&&J.pros.length>0)for(let q of J.pros)G.push(`- ${q}`);else G.push("- *To be determined based on implementation*");if(G.push(""),G.push("### Negative"),G.push(""),J&&J.cons.length>0)for(let q of J.cons)G.push(`- ${q}`);else G.push("- *To be determined based on implementation*");return G.push(""),G.push("---"),G.push(""),G.push("*Generated by Decision Engine*"),G.join(`
277
+ `)}function $J($){let Z=$.toLowerCase(),Y=[/error/gi,/exception/gi,/fail/gi,/crash/gi,/timeout/gi,/null/gi,/undefined/gi,/nan/gi,/overflow/gi,/underflow/gi,/memory/gi,/leak/gi,/deadlock/gi,/race/gi,/condition/gi,/connection/gi,/refused/gi,/denied/gi,/unauthorized/gi,/invalid/gi,/missing/gi,/corrupt/gi,/malformed/gi],Q=new Set;for(let G of Y){let V=Z.match(G);if(V)for(let U of V)Q.add(U.toLowerCase())}let z=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,J=$.match(z)||[];for(let G of J)if(G.length>3&&!G.match(/^(the|and|for|with|from|this|that)$/i))Q.add(G.toLowerCase());let X=/[A-Z]{2,}_[A-Z0-9_]+|E[0-9]{3,}/g,K=$.match(X)||[];for(let G of K)Q.add(G.toLowerCase());return[...Q]}function YH($,Z){if($.length===0||Z.length===0)return 0;let Y=new Set($),Q=new Set(Z),z=0;for(let X of Y)if(Q.has(X))z++;let J=Y.size+Q.size-z;return J>0?z/J:0}function KJ($,Z){let Y=Z?`${$}
278
+ ${Z}`:$,Q=$J(Y),z=[];for(let G of K1){let V=`${G.title} ${G.description} ${G.stacktrace||""} ${G.rootCause} ${G.solution}`,U=$J(V),q=YH(Q,U);if(q>0.1){let H=Q.filter((M)=>U.includes(M)),B=[];for(let M of G.relatedDecisions){let C=s1(M);if(C.length>0)B.push(C[0])}let O=[];if(G.solution)O.push(`Apply solution: ${G.solution}`);if(G.rootCause)O.push(`Investigate root cause: ${G.rootCause}`);for(let M of B)O.push(`Review decision: ${M.title}`);z.push({incident:G,similarity:q,matchedKeywords:H,relatedDecisions:B,suggestedActions:O})}}z.sort((G,V)=>V.similarity-G.similarity);let J=s1($.slice(0,50)),X=x$($.slice(0,50)),K=QH($,z,J,X);return{query:$,matches:z.slice(0,5),materialsFound:X.slice(0,5),summary:K}}function QH($,Z,Y,Q){let z=["# Incident Correlation Report",""];if(z.push("## Query"),z.push(""),z.push("```"),z.push($.slice(0,500)),z.push("```"),z.push(""),Z.length>0){z.push("## Similar Past Incidents"),z.push("");for(let J of Z.slice(0,3)){let X=Math.round(J.similarity*100);if(z.push(`### ${J.incident.title} (${X}% match)`),z.push(""),z.push(`**Root Cause:** ${J.incident.rootCause}`),z.push(""),z.push(`**Solution:** ${J.incident.solution}`),z.push(""),J.matchedKeywords.length>0)z.push(`**Matched Keywords:** ${J.matchedKeywords.slice(0,5).join(", ")}`),z.push("");if(J.suggestedActions.length>0){z.push("**Suggested Actions:**");for(let K of J.suggestedActions.slice(0,3))z.push(`- ${K}`);z.push("")}}}else z.push("## Similar Past Incidents"),z.push(""),z.push("*No matching incidents found in the database.*"),z.push("");if(Y.length>0){z.push("## Related Decisions"),z.push("");for(let J of Y.slice(0,3))z.push(`- **${J.title}** (${J.date.split("T")[0]}): ${J.chosen}`);z.push("")}if(Q.length>0){z.push("## Relevant Materials"),z.push("");for(let J of Q.slice(0,3)){let X=J.content.length>100?J.content.slice(0,100).replace(/\n/g," ")+"...":J.content.replace(/\n/g," ");z.push(`- **${J.title}** (${J.category}): ${X}`)}z.push("")}return z.push("---"),z.push(""),z.push("*Generated by Decision Engine Post-Mortem Correlator*"),z.join(`
279
+ `)}function GJ($,Z,Y,Q,z,J=[],X=[]){let K={id:NJ(),title:$.trim(),description:Z.trim(),stacktrace:z?.trim(),rootCause:Y.trim(),solution:Q.trim(),relatedDecisions:J,tags:X.map((G)=>G.toLowerCase()),createdAt:new Date().toISOString()};return K1=[...K1,K],tq(),K}function VJ($){let Z=$.toLowerCase();return K1.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.description.toLowerCase().includes(Z)||Y.rootCause.toLowerCase().includes(Z)||Y.solution.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function UJ($=10){return[...K1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function qJ($=10){return[...X1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function HJ($){let Z=$.toLowerCase();return X1.filter((Y)=>Y.context.title.toLowerCase().includes(Z)||Y.context.background.toLowerCase().includes(Z)||Y.recommendation.toLowerCase().includes(Z)||Y.options.some((Q)=>Q.name.toLowerCase().includes(Z)||Q.description.toLowerCase().includes(Z))).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function WJ($){return X1.find((Z)=>Z.id===$)||null}function BJ($){if($.length===0)return"Nenhuma analise de trade-off registrada.";let Z=$.map((Y)=>{return` [${new Date(Y.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}] ${Y.context.title} \u2192 ${Y.recommendation} {${Y.id}}`});return`Trade-offs (${$.length}):
271
280
  ${Z.join(`
272
- `)}`}function LQ($){if($.length===0)return"Nenhum incidente registrado.";let Z=$.map((Y)=>{let Q=new Date(Y.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.resolvedAt?"\u2713":"\u25CB",z=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${J} [${Q}] ${Y.title}${z} {${Y.id}}`});return`Incidentes (${$.length}):
281
+ `)}`}function OJ($){if($.length===0)return"Nenhum incidente registrado.";let Z=$.map((Y)=>{let Q=new Date(Y.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Y.resolvedAt?"\u2713":"\u25CB",J=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${z} [${Q}] ${Y.title}${J} {${Y.id}}`});return`Incidentes (${$.length}):
273
282
  ${Z.join(`
274
- `)}`}function jQ(){return Mq().slice(0,8)}g();import{existsSync as r8,mkdirSync as DQ,readFileSync as p9,readdirSync as jq,writeFileSync as PQ}from"fs";import{join as t0}from"path";import{homedir as Dq}from"os";import{createHash as Pq}from"crypto";var Aq=20,AQ=3,Tq=0.6,Iq={productivity:["create_task","complete_task","save_memo","search_memos"],automation:["create_workflow","run_workflow","run_command"],knowledge:["save_material","search_materials","query_memory"],people:["delegate_to_person","log_interaction","get_people_dashboard"]},Sq={multiple_file_reads:{pattern:/read_file.*read_file.*read_file/,suggestion:"Use search_files or find_files to locate content across multiple files at once."},manual_git_flow:{pattern:/run_command.*git add.*run_command.*git commit/,suggestion:"Use /commit command for AI-assisted commit messages."},repetitive_search:{pattern:/search_files.*search_files.*search_files/,suggestion:"Consider creating a workflow to automate this search pattern."}},n8="",w0="",j$={events:[],sessionStart:Date.now()},s0=new Map,Q0=[],L$=[],_1=!1,TQ=null,IQ=()=>t0(n8,"usage-patterns.json"),SQ=()=>t0(n8,"insights.json");function wQ($,Z){if(n8=t0($,"docs-engine"),w0=t0(Dq(),".config","smolerclaw","materials","manual"),TQ=Z||null,!r8(n8))DQ(n8,{recursive:!0});if(!r8(w0))DQ(w0,{recursive:!0});pq(),cq(),lq(),j$={events:[],sessionStart:Date.now()},_1=!0}function d9($){if(!_1)return;let Z={...$,timestamp:Date.now()},Y=[...j$.events,Z].slice(-Aq);j$={...j$,events:Y},wq(Z),setImmediate(()=>kq(Z))}function wq($){let Z=`${$.type}:${$.name}`,Y=s0.get(Z);if(Y){let Q=Y.count+1,J=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;s0.set(Z,{action:Z,count:Q,avgDurationMs:J,lastUsed:$.timestamp})}else s0.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function kq($){let Z=j$.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:J}]of Object.entries(Sq))if(Q.test(Z)){if(!Q0.find((X)=>X.type==="inefficient_pattern"&&X.relatedActions.includes($.name)&&Date.now()-new Date(X.createdAt).getTime()<3600000)){let X={id:e0(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:J,relatedActions:j$.events.slice(-5).map((K)=>K.name),confidence:0.8,createdAt:new Date().toISOString()};kQ(X)}}}async function x1(){if(!_1)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=bq();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=yq();$.insightsGenerated+=Y.length;let Q=_q();$.insightsGenerated+=Q.length;for(let J of[...Z,...Y,...Q])if(kQ(J),await vq(J))$.manualUpdates++;return uq(),dq(),j$={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
275
- `),$}function bq(){let $=[],Z=xq(j$.events);for(let Y of Z)if(Y.count>=AQ){let Q={id:e0(),type:"repetitive_task",title:`Tarefa repetitiva: ${Y.actions.slice(0,3).join(" -> ")}`,description:`Este padrao de acoes foi executado ${Y.count} vezes nesta sessao.`,recommendation:"Considere criar um workflow para automatizar esta sequencia.",relatedActions:Y.actions,confidence:Math.min(0.5+Y.count*0.1,1),createdAt:new Date().toISOString()};$.push(Q)}return $}function yq(){let $=[],Z=new Set;for(let Y of j$.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(Iq)){let J=Q.filter((X)=>Z.has(X)),z=Q.filter((X)=>!Z.has(X));if(J.length>0&&z.length>0){let X=J.length/Q.length;if(X>=Tq){let K={id:e0(),type:"underutilized_tool",title:`Ferramentas subutilizadas: ${Y}`,description:`Voce usa ${J.join(", ")} mas nao ${z.join(", ")}.`,recommendation:`Experimente as ferramentas ${z.slice(0,2).join(" e ")} para aumentar sua produtividade.`,relatedActions:z,confidence:X,createdAt:new Date().toISOString()};$.push(K)}}}return $}function _q(){let $=[];if(Date.now()-j$.sessionStart>1800000&&!j$.events.some((Q)=>Q.name==="save_memo"))$.push({id:e0(),type:"tip",title:"Dica: Capture insights em memos",description:"Sessao longa detectada sem uso de memos.",recommendation:"Use save_memo ou /memo para capturar ideias importantes durante o trabalho.",relatedActions:["save_memo"],confidence:0.6,createdAt:new Date().toISOString()});let Y=j$.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!j$.events.some((Q)=>Q.name.includes("workflow")))$.push({id:e0(),type:"tip",title:"Dica: Automatize com workflows",description:`${Y} comandos executados nesta sessao.`,recommendation:"Crie um workflow para automatizar sequencias de comandos frequentes.",relatedActions:["create_workflow","run_workflow"],confidence:0.7,createdAt:new Date().toISOString()});return $}function xq($){let Z=new Map,Y=$.map((Q)=>Q.name);for(let Q=2;Q<=4;Q++)for(let J=0;J<=Y.length-Q;J++){let z=Y.slice(J,J+Q),X=z.join("|"),K=Z.get(X);if(K)Z.set(X,{...K,count:K.count+1});else Z.set(X,{actions:z,count:1})}return[...Z.values()].filter((Q)=>Q.count>=AQ)}function kQ($){if(!Q0.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))Q0=[...Q0,$],TQ?.($)}function bQ($=5){return[...Q0].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function vq($){try{let Z=gq($.type),Y=`${$.id}.md`,Q=t0(w0,Y),J=L$.find((V)=>V.id===$.id),z=J?J.version+1:1,X={id:$.id,title:$.title,category:Z,content:hq($),tags:mq($),source:"auto_generated",version:z,createdAt:J?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},K=vQ(X);return PQ(Q,K,"utf-8"),L$=L$.filter((V)=>V.id!==X.id),L$=[...L$,X],!0}catch{return!1}}async function yQ($,Z,Y="best_practice",Q=[]){if(!_1)return{success:!1,path:""};try{let J=e0(),z=`${iq($)}-${J.slice(0,4)}.md`,X=t0(w0,z),K={id:J,title:$,category:Y,content:Z,tags:Q,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},V=vQ(K);return PQ(X,V,"utf-8"),L$=[...L$,K],{success:!0,path:X,entry:K}}catch{return{success:!1,path:""}}}function fq($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return L$.map((Q)=>{let J=0,z=`${Q.title} ${Q.content} ${Q.tags.join(" ")}`.toLowerCase();for(let X of Y)if(z.includes(X))J++;return{entry:Q,score:J}}).filter((Q)=>Q.score>0).sort((Q,J)=>J.score-Q.score).map((Q)=>Q.entry)}function _Q($){let Z=$?fq($):L$;if(Z.length===0)return"Nenhum conteudo encontrado no manual. Execute /reflect para gerar insights baseados no seu uso.";let Y=Z.slice(0,5).map((Q)=>{let J=xQ[Q.category]||Q.category;return[`## ${Q.title}`,`*Categoria: ${J}*`,"",Q.content,"",Q.tags.length>0?`Tags: ${Q.tags.map((z)=>`#${z}`).join(" ")}`:""].filter(Boolean).join(`
276
- `)});return["# Manual de Uso Otimizado","",`Baseado em ${L$.length} entradas do manual vivo.`,"",...Y].join(`
277
- `)}var xQ={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function hq($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
278
- `)}function vQ($){let Z=xQ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
283
+ `)}`}function NJ(){return aq().slice(0,8)}l();import{existsSync as z8,mkdirSync as MJ,readFileSync as BZ,readdirSync as zH,writeFileSync as CJ}from"fs";import{join as $$}from"path";import{homedir as JH}from"os";import{createHash as XH}from"crypto";var KH=20,EJ=3,GH=0.6,VH={productivity:["create_task","complete_task","save_memo","search_memos"],automation:["create_workflow","run_workflow","run_command"],knowledge:["save_material","search_materials","query_memory"],people:["delegate_to_person","log_interaction","get_people_dashboard"]},UH={multiple_file_reads:{pattern:/read_file.*read_file.*read_file/,suggestion:"Use search_files or find_files to locate content across multiple files at once."},manual_git_flow:{pattern:/run_command.*git add.*run_command.*git commit/,suggestion:"Use /commit command for AI-assisted commit messages."},repetitive_search:{pattern:/search_files.*search_files.*search_files/,suggestion:"Consider creating a workflow to automate this search pattern."}},Q8="",b1="",k0={events:[],sessionStart:Date.now()},e1=new Map,G1=[],w0=[],u$=!1,RJ=null,FJ=()=>$$(Q8,"usage-patterns.json"),LJ=()=>$$(Q8,"insights.json");function jJ($,Z){if(Q8=$$($,"docs-engine"),b1=$$(JH(),".config","smolerclaw","materials","manual"),RJ=Z||null,!z8(Q8))MJ(Q8,{recursive:!0});if(!z8(b1))MJ(b1,{recursive:!0});jH(),PH(),DH(),k0={events:[],sessionStart:Date.now()},u$=!0}function OZ($){if(!u$)return;let Z={...$,timestamp:Date.now()},Y=[...k0.events,Z].slice(-KH);k0={...k0,events:Y},qH(Z),setImmediate(()=>HH(Z))}function qH($){let Z=`${$.type}:${$.name}`,Y=e1.get(Z);if(Y){let Q=Y.count+1,z=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;e1.set(Z,{action:Z,count:Q,avgDurationMs:z,lastUsed:$.timestamp})}else e1.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function HH($){let Z=k0.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:z}]of Object.entries(UH))if(Q.test(Z)){if(!G1.find((X)=>X.type==="inefficient_pattern"&&X.relatedActions.includes($.name)&&Date.now()-new Date(X.createdAt).getTime()<3600000)){let X={id:Z$(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:z,relatedActions:k0.events.slice(-5).map((K)=>K.name),confidence:0.8,createdAt:new Date().toISOString()};AJ(X)}}}async function p$(){if(!u$)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=WH();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=BH();$.insightsGenerated+=Y.length;let Q=OH();$.insightsGenerated+=Q.length;for(let z of[...Z,...Y,...Q])if(AJ(z),await MH(z))$.manualUpdates++;return LH(),AH(),k0={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
284
+ `),$}function WH(){let $=[],Z=NH(k0.events);for(let Y of Z)if(Y.count>=EJ){let Q={id:Z$(),type:"repetitive_task",title:`Tarefa repetitiva: ${Y.actions.slice(0,3).join(" -> ")}`,description:`Este padrao de acoes foi executado ${Y.count} vezes nesta sessao.`,recommendation:"Considere criar um workflow para automatizar esta sequencia.",relatedActions:Y.actions,confidence:Math.min(0.5+Y.count*0.1,1),createdAt:new Date().toISOString()};$.push(Q)}return $}function BH(){let $=[],Z=new Set;for(let Y of k0.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(VH)){let z=Q.filter((X)=>Z.has(X)),J=Q.filter((X)=>!Z.has(X));if(z.length>0&&J.length>0){let X=z.length/Q.length;if(X>=GH){let K={id:Z$(),type:"underutilized_tool",title:`Ferramentas subutilizadas: ${Y}`,description:`Voce usa ${z.join(", ")} mas nao ${J.join(", ")}.`,recommendation:`Experimente as ferramentas ${J.slice(0,2).join(" e ")} para aumentar sua produtividade.`,relatedActions:J,confidence:X,createdAt:new Date().toISOString()};$.push(K)}}}return $}function OH(){let $=[];if(Date.now()-k0.sessionStart>1800000&&!k0.events.some((Q)=>Q.name==="save_memo"))$.push({id:Z$(),type:"tip",title:"Dica: Capture insights em memos",description:"Sessao longa detectada sem uso de memos.",recommendation:"Use save_memo ou /memo para capturar ideias importantes durante o trabalho.",relatedActions:["save_memo"],confidence:0.6,createdAt:new Date().toISOString()});let Y=k0.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!k0.events.some((Q)=>Q.name.includes("workflow")))$.push({id:Z$(),type:"tip",title:"Dica: Automatize com workflows",description:`${Y} comandos executados nesta sessao.`,recommendation:"Crie um workflow para automatizar sequencias de comandos frequentes.",relatedActions:["create_workflow","run_workflow"],confidence:0.7,createdAt:new Date().toISOString()});return $}function NH($){let Z=new Map,Y=$.map((Q)=>Q.name);for(let Q=2;Q<=4;Q++)for(let z=0;z<=Y.length-Q;z++){let J=Y.slice(z,z+Q),X=J.join("|"),K=Z.get(X);if(K)Z.set(X,{...K,count:K.count+1});else Z.set(X,{actions:J,count:1})}return[...Z.values()].filter((Q)=>Q.count>=EJ)}function AJ($){if(!G1.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))G1=[...G1,$],RJ?.($)}function PJ($=5){return[...G1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function MH($){try{let Z=RH($.type),Y=`${$.id}.md`,Q=$$(b1,Y),z=w0.find((G)=>G.id===$.id),J=z?z.version+1:1,X={id:$.id,title:$.title,category:Z,content:EH($),tags:FH($),source:"auto_generated",version:J,createdAt:z?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},K=SJ(X);return CJ(Q,K,"utf-8"),w0=w0.filter((G)=>G.id!==X.id),w0=[...w0,X],!0}catch{return!1}}async function DJ($,Z,Y="best_practice",Q=[]){if(!u$)return{success:!1,path:""};try{let z=Z$(),J=`${IH($)}-${z.slice(0,4)}.md`,X=$$(b1,J),K={id:z,title:$,category:Y,content:Z,tags:Q,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},G=SJ(K);return CJ(X,G,"utf-8"),w0=[...w0,K],{success:!0,path:X,entry:K}}catch{return{success:!1,path:""}}}function CH($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return w0.map((Q)=>{let z=0,J=`${Q.title} ${Q.content} ${Q.tags.join(" ")}`.toLowerCase();for(let X of Y)if(J.includes(X))z++;return{entry:Q,score:z}}).filter((Q)=>Q.score>0).sort((Q,z)=>z.score-Q.score).map((Q)=>Q.entry)}function TJ($){let Z=$?CH($):w0;if(Z.length===0)return"Nenhum conteudo encontrado no manual. Execute /reflect para gerar insights baseados no seu uso.";let Y=Z.slice(0,5).map((Q)=>{let z=IJ[Q.category]||Q.category;return[`## ${Q.title}`,`*Categoria: ${z}*`,"",Q.content,"",Q.tags.length>0?`Tags: ${Q.tags.map((J)=>`#${J}`).join(" ")}`:""].filter(Boolean).join(`
285
+ `)});return["# Manual de Uso Otimizado","",`Baseado em ${w0.length} entradas do manual vivo.`,"",...Y].join(`
286
+ `)}var IJ={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function EH($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
287
+ `)}function SJ($){let Z=IJ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
279
288
  Tags: ${$.tags.map((Y)=>`#${Y}`).join(" ")}`:""].filter(Boolean).join(`
280
- `)}function gq($){switch($){case"repetitive_task":return"workflow";case"underutilized_tool":return"tool";case"inefficient_pattern":return"best_practice";case"tip":return"shortcut";default:return"best_practice"}}function mq($){let Z=new Set;Z.add($.type.replace(/_/g,"-"));for(let Y of $.relatedActions)if(Y.includes("_"))Z.add(Y.split("_")[0]);return[...Z]}function fQ($){return $.summary}function hQ($){if($.length===0)return"Nenhum insight disponivel.";let Z=$.map((Y)=>{return[`[${{repetitive_task:"Tarefa Repetitiva",underutilized_tool:"Ferramenta Subutilizada",inefficient_pattern:"Padrao Ineficiente",tip:"Dica"}[Y.type]||Y.type}] ${Y.title}`,` ${Y.recommendation}`,` Confianca: ${Math.round(Y.confidence*100)}%`].join(`
289
+ `)}function RH($){switch($){case"repetitive_task":return"workflow";case"underutilized_tool":return"tool";case"inefficient_pattern":return"best_practice";case"tip":return"shortcut";default:return"best_practice"}}function FH($){let Z=new Set;Z.add($.type.replace(/_/g,"-"));for(let Y of $.relatedActions)if(Y.includes("_"))Z.add(Y.split("_")[0]);return[...Z]}function wJ($){return $.summary}function kJ($){if($.length===0)return"Nenhum insight disponivel.";let Z=$.map((Y)=>{return[`[${{repetitive_task:"Tarefa Repetitiva",underutilized_tool:"Ferramenta Subutilizada",inefficient_pattern:"Padrao Ineficiente",tip:"Dica"}[Y.type]||Y.type}] ${Y.title}`,` ${Y.recommendation}`,` Confianca: ${Math.round(Y.confidence*100)}%`].join(`
281
290
  `)});return`Insights (${$.length}):
282
291
 
283
292
  ${Z.join(`
284
293
 
285
- `)}`}function uq(){if(!_1)return;let $=Object.fromEntries(s0);P(IQ(),JSON.stringify($,null,2))}function pq(){let $=IQ();if(!r8($)){s0=new Map;return}try{let Z=JSON.parse(p9($,"utf-8"));s0=new Map(Object.entries(Z))}catch{s0=new Map}}function dq(){if(!_1)return;P(SQ(),JSON.stringify(Q0,null,2))}function cq(){let $=SQ();if(!r8($)){Q0=[];return}try{let Z=JSON.parse(p9($,"utf-8"));Q0=Array.isArray(Z)?Z:[]}catch{Q0=[]}}function lq(){if(!r8(w0)){L$=[];return}try{let $=jq(w0,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=t0(w0,Y.name),J=p9(Q,"utf-8"),z=oq(Y.name,J);if(z)Z.push(z)}L$=Z}catch{L$=[]}}function oq($,Z){try{let Y=Z.split(`
286
- `),Q=Y[0]?.replace(/^#\s*/,"")||$.replace(".md",""),J="best_practice",z=1,X=[];for(let U of Y.slice(1,6)){if(U.startsWith("> Categoria:")){let W=U.replace("> Categoria:","").trim().toLowerCase();if(W==="workflow"||W==="tool"||W==="shortcut"||W==="best_practice")J=W}if(U.startsWith("> Versao:"))z=parseInt(U.replace("> Versao:","").trim())||1}let V=Y.slice(-3).join(`
287
- `).match(/Tags:\s*(.+)/);if(V){let W=V[1].match(/#[\w-]+/g);if(W)X.push(...W.map((B)=>B.slice(1)))}let G=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:G?G[1]:e0(),title:Q,category:J,content:Y.slice(5).join(`
288
- `).trim(),tags:X,source:"auto_generated",version:z,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function e0(){return Pq("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function iq($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}J1();o();d$();p$();import{writeFileSync as sq,unlinkSync as tq,existsSync as eq}from"fs";import{join as $U}from"path";import{tmpdir as ZU}from"os";import{randomUUID as YU}from"crypto";var QU=30000,mQ=50000;var JU=[{pattern:/Set-MpPreference\s.*-Disable/i,reason:"Tentativa de desativar Windows Defender"},{pattern:/Disable-WindowsOptionalFeature.*Defender/i,reason:"Tentativa de desativar Windows Defender"},{pattern:/Stop-Service\s.*WinDefend/i,reason:"Tentativa de parar Windows Defender"},{pattern:/sc\s+(stop|delete|disable)\s+WinDefend/i,reason:"Tentativa de desabilitar Windows Defender via sc"},{pattern:/New-ItemProperty.*DisableAntiSpyware/i,reason:"Tentativa de desativar prote\xE7\xE3o via registro"},{pattern:/Remove-Item\s.*\\Windows\\System32/i,reason:"Tentativa de deletar arquivos do System32"},{pattern:/Remove-Item\s.*\\Windows\\SysWOW64/i,reason:"Tentativa de deletar arquivos do SysWOW64"},{pattern:/Format-Volume/i,reason:"Tentativa de formatar volume"},{pattern:/Clear-Disk/i,reason:"Tentativa de limpar disco"},{pattern:/Stop-Computer/i,reason:"Tentativa de desligar computador"},{pattern:/Restart-Computer/i,reason:"Tentativa de reiniciar computador"},{pattern:/Set-ExecutionPolicy\s+Unrestricted/i,reason:"Tentativa de mudar politica de execu\xE7\xE3o permanentemente"},{pattern:/\bnet\s+user\s+.*\/add/i,reason:"Tentativa de criar usuario"},{pattern:/\bnet\s+localgroup\s+administrators/i,reason:"Tentativa de modificar grupo Administrators"},{pattern:/Invoke-Expression.*DownloadString/i,reason:"Tentativa de execu\xE7\xE3o remota (IEX + download)"},{pattern:/\biex\s*\(\s*\(?\s*New-Object/i,reason:"Tentativa de execu\xE7\xE3o remota (IEX + WebClient)"}],zU=[{pattern:/\\Windows\\System32/i,reason:"Acesso a System32"},{pattern:/\\Windows\\SysWOW64/i,reason:"Acesso a SysWOW64"},{pattern:/HKLM:|HKCU:/i,reason:"Acesso ao registro do Windows"},{pattern:/New-Service|Set-Service|Remove-Service/i,reason:"Manipula\xE7\xE3o de servi\xE7os"},{pattern:/New-NetFirewallRule|Remove-NetFirewallRule/i,reason:"Altera\xE7\xE3o de regras de firewall"},{pattern:/Start-Process\s.*-Verb\s+RunAs/i,reason:"Eleva\xE7\xE3o de privilegios (RunAs)"},{pattern:/Set-ItemProperty\s.*\\CurrentVersion\\Run/i,reason:"Modifica\xE7\xE3o de programas de inicializa\xE7\xE3o"}];function i9($){for(let{pattern:Z,reason:Y}of JU)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of zU)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function e8($){if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>mQ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${mQ}).`,exitCode:1,duration:0};let Z=i9($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};if(!L)return{stdout:"",stderr:"Error: PowerShell scripts only available on Windows.",exitCode:1,duration:0};let Y=YU().slice(0,8),Q=$U(ZU(),`smolerclaw-${Y}.ps1`);try{sq(Q,$,"utf-8");let J=await $6(Q,{timeout:QU});return{stdout:J.stdout,stderr:J.timedOut?"Script timeout exceeded":J.stderr,exitCode:J.exitCode,duration:J.duration}}finally{try{if(eq(Q))tq(Q)}catch{}}}async function N5(){if(!L)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await XU();if($.type==="text")return $;return await KU()}async function XU(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await H2($,{timeout:1e4});if(Z.timedOut)return{type:"error",text:"Clipboard read timeout."};let Y=Z.stdout.trim();if(Y==="___EMPTY___"||!Y)return{type:"empty",text:""};return{type:"text",text:Y}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function KU(){try{let Z=await H2(`
294
+ `)}`}function LH(){if(!u$)return;let $=Object.fromEntries(e1);P(FJ(),JSON.stringify($,null,2))}function jH(){let $=FJ();if(!z8($)){e1=new Map;return}try{let Z=JSON.parse(BZ($,"utf-8"));e1=new Map(Object.entries(Z))}catch{e1=new Map}}function AH(){if(!u$)return;P(LJ(),JSON.stringify(G1,null,2))}function PH(){let $=LJ();if(!z8($)){G1=[];return}try{let Z=JSON.parse(BZ($,"utf-8"));G1=Array.isArray(Z)?Z:[]}catch{G1=[]}}function DH(){if(!z8(b1)){w0=[];return}try{let $=zH(b1,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=$$(b1,Y.name),z=BZ(Q,"utf-8"),J=TH(Y.name,z);if(J)Z.push(J)}w0=Z}catch{w0=[]}}function TH($,Z){try{let Y=Z.split(`
295
+ `),Q=Y[0]?.replace(/^#\s*/,"")||$.replace(".md",""),z="best_practice",J=1,X=[];for(let q of Y.slice(1,6)){if(q.startsWith("> Categoria:")){let H=q.replace("> Categoria:","").trim().toLowerCase();if(H==="workflow"||H==="tool"||H==="shortcut"||H==="best_practice")z=H}if(q.startsWith("> Versao:"))J=parseInt(q.replace("> Versao:","").trim())||1}let G=Y.slice(-3).join(`
296
+ `).match(/Tags:\s*(.+)/);if(G){let H=G[1].match(/#[\w-]+/g);if(H)X.push(...H.map((B)=>B.slice(1)))}let V=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:V?V[1]:Z$(),title:Q,category:z,content:Y.slice(5).join(`
297
+ `).trim(),tags:X,source:"auto_generated",version:J,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function Z$(){return XH("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function IH($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}X$();s();u0();n0();import{writeFileSync as fH,unlinkSync as bH,existsSync as yH}from"fs";import{join as _H}from"path";import{tmpdir as xH}from"os";import{randomUUID as vH}from"crypto";var hH=30000,bJ=50000;var gH=[{pattern:/Set-MpPreference\s.*-Disable/i,reason:"Tentativa de desativar Windows Defender"},{pattern:/Disable-WindowsOptionalFeature.*Defender/i,reason:"Tentativa de desativar Windows Defender"},{pattern:/Stop-Service\s.*WinDefend/i,reason:"Tentativa de parar Windows Defender"},{pattern:/sc\s+(stop|delete|disable)\s+WinDefend/i,reason:"Tentativa de desabilitar Windows Defender via sc"},{pattern:/New-ItemProperty.*DisableAntiSpyware/i,reason:"Tentativa de desativar prote\xE7\xE3o via registro"},{pattern:/Remove-Item\s.*\\Windows\\System32/i,reason:"Tentativa de deletar arquivos do System32"},{pattern:/Remove-Item\s.*\\Windows\\SysWOW64/i,reason:"Tentativa de deletar arquivos do SysWOW64"},{pattern:/Format-Volume/i,reason:"Tentativa de formatar volume"},{pattern:/Clear-Disk/i,reason:"Tentativa de limpar disco"},{pattern:/Stop-Computer/i,reason:"Tentativa de desligar computador"},{pattern:/Restart-Computer/i,reason:"Tentativa de reiniciar computador"},{pattern:/Set-ExecutionPolicy\s+Unrestricted/i,reason:"Tentativa de mudar politica de execu\xE7\xE3o permanentemente"},{pattern:/\bnet\s+user\s+.*\/add/i,reason:"Tentativa de criar usuario"},{pattern:/\bnet\s+localgroup\s+administrators/i,reason:"Tentativa de modificar grupo Administrators"},{pattern:/Invoke-Expression.*DownloadString/i,reason:"Tentativa de execu\xE7\xE3o remota (IEX + download)"},{pattern:/\biex\s*\(\s*\(?\s*New-Object/i,reason:"Tentativa de execu\xE7\xE3o remota (IEX + WebClient)"}],mH=[{pattern:/\\Windows\\System32/i,reason:"Acesso a System32"},{pattern:/\\Windows\\SysWOW64/i,reason:"Acesso a SysWOW64"},{pattern:/HKLM:|HKCU:/i,reason:"Acesso ao registro do Windows"},{pattern:/New-Service|Set-Service|Remove-Service/i,reason:"Manipula\xE7\xE3o de servi\xE7os"},{pattern:/New-NetFirewallRule|Remove-NetFirewallRule/i,reason:"Altera\xE7\xE3o de regras de firewall"},{pattern:/Start-Process\s.*-Verb\s+RunAs/i,reason:"Eleva\xE7\xE3o de privilegios (RunAs)"},{pattern:/Set-ItemProperty\s.*\\CurrentVersion\\Run/i,reason:"Modifica\xE7\xE3o de programas de inicializa\xE7\xE3o"}];function EZ($){for(let{pattern:Z,reason:Y}of gH)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of mH)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function K8($){if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>bJ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${bJ}).`,exitCode:1,duration:0};let Z=EZ($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};if(!j)return{stdout:"",stderr:"Error: PowerShell scripts only available on Windows.",exitCode:1,duration:0};let Y=vH().slice(0,8),Q=_H(xH(),`smolerclaw-${Y}.ps1`);try{fH(Q,$,"utf-8");let z=await o9(Q,{timeout:hH});return{stdout:z.stdout,stderr:z.timedOut?"Script timeout exceeded":z.stderr,exitCode:z.exitCode,duration:z.duration}}finally{try{if(yH(Q))bH(Q)}catch{}}}async function k5(){if(!j)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await uH();if($.type==="text")return $;return await pH()}async function uH(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await x7($,{timeout:1e4});if(Z.timedOut)return{type:"error",text:"Clipboard read timeout."};let Y=Z.stdout.trim();if(Y==="___EMPTY___"||!Y)return{type:"empty",text:""};return{type:"text",text:Y}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function pH(){try{let Z=await x7(`
289
298
  Add-Type -AssemblyName System.Windows.Forms
290
299
  $img = [System.Windows.Forms.Clipboard]::GetImage()
291
300
  if (-not $img) {
@@ -336,7 +345,7 @@ try {
336
345
  if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
337
346
  }
338
347
  `,{timeout:20000});if(Z.timedOut)return{type:"error",text:"OCR timeout."};let Y=Z.stdout.trim();if(Y==="___NO_IMAGE___")return{type:"empty",text:""};if(Y==="___NO_TEXT___")return{type:"image",text:"(Imagem detectada no clipboard, mas sem texto reconhecivel)"};if(Y.startsWith("___OCR_ERROR___"))return{type:"error",text:`OCR falhou: ${Y.replace("___OCR_ERROR___: ","")}`};if(Y)return{type:"image",text:`[OCR do clipboard]
339
- ${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function O5(){if(!L)return"Error: screen context analysis only available on Windows.";let $=`
348
+ ${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function f5(){if(!j)return"Error: screen context analysis only available on Windows.";let $=`
340
349
  $sig = @'
341
350
  [DllImport("user32.dll")]
342
351
  public static extern IntPtr GetForegroundWindow();
@@ -369,7 +378,7 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
369
378
  $marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
370
379
  Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
371
380
  }
372
- `;try{let Z=await q$($,{timeout:15000});if(Z.timedOut)return"Error: screen context analysis timeout";let Y=Z.stdout.trim();if(!Y&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;return Y||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function uQ($,Z){if(!$?.trim())return{success:!1,error:"Title is required."};if(!Z?.trim())return{success:!1,error:"Message is required."};if(!L)return{success:!1,error:"Notifications only available on Windows."};let Y=$.replace(/'/g,"''"),Q=Z.replace(/'/g,"''"),J=`
381
+ `;try{let Z=await O0($,{timeout:15000});if(Z.timedOut)return"Error: screen context analysis timeout";let Y=Z.stdout.trim();if(!Y&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;return Y||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function yJ($,Z){if(!$?.trim())return{success:!1,error:"Title is required."};if(!Z?.trim())return{success:!1,error:"Message is required."};if(!j)return{success:!1,error:"Notifications only available on Windows."};let Y=$.replace(/'/g,"''"),Q=Z.replace(/'/g,"''"),z=`
373
382
  $notificationTitle = '${Y}'
374
383
  $notificationText = '${Q}'
375
384
  [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
@@ -382,49 +391,49 @@ $xml.LoadXml($toastXml.OuterXml)
382
391
  $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
383
392
  [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Smolerclaw').Show($toast)
384
393
  Write-Output 'OK'
385
- `;try{let z=await e8(J);if(z.exitCode===0&&z.stdout.includes("OK"))return{success:!0};return{success:!1,error:z.stderr||"Unknown error sending notification."}}catch(z){return{success:!1,error:z instanceof Error?z.message:String(z)}}}var $4=50000;function h$($){if($.length<=$4)return $;return $.slice(0,$4)+`
386
- ... (output truncated)`}function Z4($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function a9($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje")return Y;if(Z==="amanha"||Z==="amanh\xE3"){let K=new Date(Y);return K.setDate(K.getDate()+1),K}let Q=Z.match(/em\s+(\d+)\s*dias?/);if(Q){let K=new Date(Y);return K.setDate(K.getDate()+parseInt(Q[1])),K}let J=Z.match(/em\s+(\d+)\s*semanas?/);if(J){let K=new Date(Y);return K.setDate(K.getDate()+parseInt(J[1])*7),K}let z={domingo:0,segunda:1,terca:2,ter\u{e7}a:2,quarta:3,quinta:4,sexta:5,sabado:6,s\u{e1}bado:6};for(let[K,V]of Object.entries(z))if(Z.includes(K)){let G=new Date(Y),q=(V-G.getDay()+7)%7||7;return G.setDate(G.getDate()+q),G}let X=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(X){let K=parseInt(X[1]),V=parseInt(X[2])-1,G=X[3]?parseInt(X[3])+(X[3].length===2?2000:0):Y.getFullYear(),q=new Date(G,V,K);if(!isNaN(q.getTime()))return q}return P1(Z)}var R5=[{name:"create_task",description:'Create a task or reminder for the user. If a time is provided, a notification will fire at that time. Supports natural-language times like "18h", "em 30 minutos", "amanha 9h".',input_schema:{type:"object",properties:{title:{type:"string",description:'Task description (e.g. "buscar pao")'},time:{type:"string",description:'When to remind. E.g. "18h", "18:30", "em 30 minutos", "amanha 9h". Optional.'}},required:["title"]}},{name:"complete_task",description:"Mark a task as done by its ID or partial title match.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Task ID or partial title to match"}},required:["reference"]}},{name:"list_tasks",description:"List all pending tasks and reminders. Shows title, due time, and ID.",input_schema:{type:"object",properties:{show_done:{type:"boolean",description:"Include completed tasks. Default false."}},required:[]}}],E5=[{name:"schedule_job",description:"Create a persistent scheduled job using Windows Task Scheduler. Jobs fire even when smolerclaw is not running. Supports one-time, daily, and weekly schedules.",input_schema:{type:"object",properties:{name:{type:"string",description:"Human-readable name for the job"},time:{type:"string",description:'Time in HH:MM format (e.g., "14:00", "09:30")'},message:{type:"string",description:"Message to display in the notification"},schedule_type:{type:"string",enum:["once","daily","weekly"],description:"Schedule type: once (single execution), daily, or weekly. Default: once"},date_or_day:{type:"string",description:'For "once": date in DD/MM/YYYY format or "hoje"/"amanha". For "weekly": day name (e.g., "segunda", "friday"). Optional.'}},required:["name","time","message"]}},{name:"remove_scheduled_job",description:"Remove a scheduled job by its ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"list_scheduled_jobs",description:"List all scheduled jobs. Shows name, schedule, and status.",input_schema:{type:"object",properties:{include_disabled:{type:"boolean",description:"Include disabled jobs. Default false."}},required:[]}},{name:"enable_scheduled_job",description:"Enable a previously disabled scheduled job.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"disable_scheduled_job",description:"Disable a scheduled job without removing it.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"run_scheduled_job_now",description:"Execute a scheduled job immediately (for testing).",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}}],L5=[{name:"add_person",description:"Register a person (team member, family, or contact). Groups: equipe (work team), familia (family/home), contato (other contacts).",input_schema:{type:"object",properties:{name:{type:"string",description:"Person name"},group:{type:"string",enum:["equipe","familia","contato"],description:"Group: equipe, familia, or contato"},role:{type:"string",description:'Role or relationship (e.g. "dev frontend", "esposa", "fornecedor"). Optional.'},contact:{type:"string",description:"Phone, email, or other contact info. Optional."}},required:["name","group"]}},{name:"find_person_info",description:"Look up a person by name or ID. Returns their profile, recent interactions, and pending delegated tasks.",input_schema:{type:"object",properties:{name_or_id:{type:"string",description:"Person name (partial match) or ID"}},required:["name_or_id"]}},{name:"list_people",description:"List all registered people, optionally filtered by group.",input_schema:{type:"object",properties:{group:{type:"string",enum:["equipe","familia","contato"],description:"Filter by group. Optional."}},required:[]}},{name:"log_interaction",description:"Log an interaction with a person. Types: conversa, email, reuniao, ligacao, mensagem, delegacao, entrega, outro. Optionally set a follow-up date for a reminder.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},type:{type:"string",enum:["conversa","email","reuniao","ligacao","mensagem","delegacao","entrega","outro"],description:"Interaction type"},summary:{type:"string",description:"What was discussed or happened"},follow_up:{type:"string",description:'When to follow up (e.g. "em 3 dias", "amanha", "25/03"). Optional.'}},required:["person","type","summary"]}},{name:"delegate_to_person",description:"Delegate/assign a task to a person with optional due date. Use to track what you asked someone to do.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},task:{type:"string",description:"What they need to do"},due_date:{type:"string",description:'Due date (e.g. "sexta", "em 3 dias", "28/03"). Optional.'}},required:["person","task"]}},{name:"update_delegation_status",description:"Update the status of a delegated task. Statuses: pendente, em_andamento, concluido.",input_schema:{type:"object",properties:{delegation_id:{type:"string",description:"Delegation ID"},status:{type:"string",enum:["pendente","em_andamento","concluido"],description:"New status"},notes:{type:"string",description:"Optional notes about the update"}},required:["delegation_id","status"]}},{name:"get_people_dashboard",description:"Show the people management dashboard: summary of team/family/contacts, overdue follow-ups, overdue delegations, and recent interactions.",input_schema:{type:"object",properties:{},required:[]}}],j5=[{name:"save_memo",description:`Save a note/memo to the user's personal knowledge base. Use #hashtags in the content to auto-tag. Use when the user says "anota", "lembra disso", "salva isso", or shares important information.`,input_schema:{type:"object",properties:{content:{type:"string",description:"The memo content. Use #tags for categorization."},tags:{type:"array",items:{type:"string"},description:"Optional additional tags (without #). Auto-extracted #tags from content are always included."}},required:["content"]}},{name:"search_memos",description:`Search the user's memos by keyword or tag. Use #tag to search by tag only. Use plain text for content search. Use when the user asks "o que eu anotei sobre...", "qual era aquela nota...", etc.`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search query. Use #tag for tag search, or plain text for content search."}},required:["query"]}}],D5={name:"draft_email",description:'Create an email draft and open it in Outlook (Windows) or the default mail client. The user can review and send manually. Use when the user says "escreve um email", "manda um email", "rascunho de email", etc.',input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC recipients (optional)"}},required:["to","subject","body"]}},P5=[{name:"record_transaction",description:"Record a financial transaction (income or expense). Use when user mentions spending, receiving money, or financial tracking.",input_schema:{type:"object",properties:{type:{type:"string",enum:["entrada","saida"],description:"Transaction type: entrada (income) or saida (expense)"},amount:{type:"number",description:"Amount in BRL (always positive)"},category:{type:"string",description:"Category (e.g. alimentacao, transporte, salario, freelance)"},description:{type:"string",description:"Description of the transaction"}},required:["type","amount","category","description"]}},{name:"financial_summary",description:"Show monthly financial summary with income, expenses, and balance by category.",input_schema:{type:"object",properties:{},required:[]}},{name:"log_decision",description:'Record an important decision with context and rationale. Use when the user says "decidi", "optei por", "escolhi", or discusses a major choice.',input_schema:{type:"object",properties:{title:{type:"string",description:"Decision title (short)"},context:{type:"string",description:"Why this decision was needed"},chosen:{type:"string",description:"What was decided"},alternatives:{type:"string",description:"What was considered but rejected. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["title","context","chosen"]}},{name:"search_decisions",description:"Search past decisions by keyword or tag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}],A5=[{name:"open_investigation",description:'Start a new investigation to systematically collect evidence. Types: bug (malfunction), feature (material for building), test (test scenarios), audit (code review), incident (runtime issue). Use when the user says "investiga", "analisa", "diagnostica", "verifica", or needs structured evidence collection.',input_schema:{type:"object",properties:{title:{type:"string",description:"Investigation title (short, descriptive)"},type:{type:"string",enum:["bug","feature","test","audit","incident"],description:"Investigation type"},hypothesis:{type:"string",description:"Initial theory or goal to investigate. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["title","type"]}},{name:"collect_evidence",description:"Add a piece of evidence to an active investigation. Sources: file (file content), command (command output), log (log entries), diff (code changes), url (web content), observation (manual note). Use after reading files, running commands, or observing behavior to build the investigation record.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title (partial match)"},source:{type:"string",enum:["file","command","log","diff","url","observation"],description:"Evidence source type"},label:{type:"string",description:"Short description of this evidence"},content:{type:"string",description:"The evidence data (file content, command output, observation text, etc.)"},path:{type:"string",description:"File path or URL associated with this evidence. Optional."}},required:["investigation","source","label","content"]}},{name:"add_finding",description:"Record a conclusion or insight derived from collected evidence. Severity: critical, high, medium, low, info. Link to evidence IDs that support this finding.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"},severity:{type:"string",enum:["critical","high","medium","low","info"],description:"Finding severity"},title:{type:"string",description:"Finding title (short)"},description:{type:"string",description:"Detailed description of the finding"},evidence_ids:{type:"array",items:{type:"string"},description:"IDs of evidence supporting this finding. Optional."}},required:["investigation","severity","title","description"]}},{name:"close_investigation",description:"Close an investigation with a summary and recommendations. Use after all evidence is collected and findings are recorded.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"},summary:{type:"string",description:"Final summary of the investigation"},recommendations:{type:"string",description:"Action items and next steps. Optional."}},required:["investigation","summary"]}},{name:"investigation_status",description:"View the current state of an investigation: evidence collected, findings, and progress. Use to check progress or review before closing.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"}},required:["investigation"]}},{name:"investigation_report",description:"Generate a full structured report (markdown) for an investigation. Includes all evidence, findings, summary, and recommendations.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"}},required:["investigation"]}},{name:"list_investigations",description:"List all investigations, optionally filtered by status or type.",input_schema:{type:"object",properties:{status:{type:"string",enum:["aberta","em_andamento","concluida","arquivada"],description:"Filter by status. Optional."},type:{type:"string",enum:["bug","feature","test","audit","incident"],description:"Filter by type. Optional."},query:{type:"string",description:"Search by keyword. Optional."}},required:[]}}],T5=[{name:"save_material",description:`Save reference material to the assistant's persistent knowledge base. Materials are categorized documents, guides, procedures, or reference info that persists across sessions. Use when the user says "salva esse material", "guarda essa referencia", "adiciona ao conhecimento", etc. Categories: procedimento, referencia, guia, template, contato, projeto, tecnico, geral.`,input_schema:{type:"object",properties:{title:{type:"string",description:"Title of the material"},content:{type:"string",description:"Full content. Use #tags for categorization."},category:{type:"string",description:"Category (e.g. procedimento, referencia, guia, template, contato, projeto, tecnico, geral). Default: geral."},tags:{type:"array",items:{type:"string"},description:"Optional additional tags (without #)."}},required:["title","content"]}},{name:"search_materials",description:"Search the assistant's material knowledge base by keyword, tag (#tag), or category (@category). Use when answering questions that may be covered by saved materials, or when user asks about reference docs.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query. Use #tag for tag search, @category for category search, or plain text."}},required:["query"]}},{name:"list_materials",description:"List all saved materials, optionally filtered by category.",input_schema:{type:"object",properties:{category:{type:"string",description:"Filter by category. Optional."},limit:{type:"number",description:"Max results. Default 30."}},required:[]}},{name:"update_material",description:"Update an existing material by ID. Can change title, content, category, or tags.",input_schema:{type:"object",properties:{id:{type:"string",description:"Material ID"},title:{type:"string",description:"New title. Optional."},content:{type:"string",description:"New content. Optional."},category:{type:"string",description:"New category. Optional."},tags:{type:"array",items:{type:"string"},description:"New tags. Optional."}},required:["id"]}},{name:"delete_material",description:"Delete a material by ID.",input_schema:{type:"object",properties:{id:{type:"string",description:"Material ID"}},required:["id"]}}],I5=[{name:"set_active_project",description:'Set which project the assistant should focus on. Auto-detects from the current directory if not registered. Use when the user says "estou trabalhando no projeto X", "muda pro projeto Y", or starts work.',input_schema:{type:"object",properties:{name_or_id:{type:"string",description:'Project name, ID, or "auto" to detect from current directory.'}},required:["name_or_id"]}},{name:"report_work_progress",description:'Generate a work progress report with git commits, time tracked, and tasks completed. Outputs a structured Markdown document. Use when the user says "relatorio", "como estou no projeto", "resumo do trabalho", "progress report".',input_schema:{type:"object",properties:{project:{type:"string",description:"Project name/ID. Defaults to active project."},period:{type:"string",enum:["today","week","month"],description:"Report period. Default: today."},lang:{type:"string",enum:["pt","en"],description:"Report language. Default: pt."},save_to_file:{type:"string",description:"Optional file path to save the report. If omitted, returns as text."}},required:[]}},{name:"manage_work_session",description:'Start or stop a work session timer for time tracking. Use when the user says "comecei a trabalhar", "parei de trabalhar", "timer", etc.',input_schema:{type:"object",properties:{action:{type:"string",enum:["start","stop","status"],description:"Start, stop, or check session status."},notes:{type:"string",description:"Optional notes for the session."}},required:["action"]}},{name:"add_project",description:"Register a new project for tracking. Use when the user mentions a new project or wants to track a directory.",input_schema:{type:"object",properties:{name:{type:"string",description:"Project name"},path:{type:"string",description:"Filesystem path to the project root"},description:{type:"string",description:"Brief project description. Optional."},tech_stack:{type:"array",items:{type:"string"},description:"Technologies used. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["name","path"]}},{name:"list_projects",description:"List all registered projects with their status and tech stack.",input_schema:{type:"object",properties:{active_only:{type:"boolean",description:"Show only active projects. Default false."}},required:[]}},{name:"fetch_opportunities",description:'List pending opportunities/tasks filtered by tech stack or priority. Use when the user asks "tem alguma demanda nova?", "oportunidades", "o que tem pra fazer?".',input_schema:{type:"object",properties:{status:{type:"string",enum:["nova","em_analise","aceita","recusada","concluida"],description:"Filter by status. Optional."},tech:{type:"array",items:{type:"string"},description:"Filter by required tech. Optional."}},required:[]}},{name:"add_opportunity",description:"Register a new task/opportunity/demand for tracking. Use when the user mentions a potential project, job lead, or new demand.",input_schema:{type:"object",properties:{title:{type:"string",description:"Opportunity title"},description:{type:"string",description:"Details about the opportunity"},source:{type:"string",description:'Where this came from (e.g. "LinkedIn", "email", "contato direto")'},tech_required:{type:"array",items:{type:"string"},description:"Technologies required. Optional."},priority:{type:"string",enum:["alta","media","baixa"],description:"Priority level. Default: media."},deadline:{type:"string",description:'Deadline if any (e.g. "30/04", "em 2 semanas"). Optional.'}},required:["title","description","source"]}},{name:"update_opportunity_status",description:"Update the status of an opportunity.",input_schema:{type:"object",properties:{id:{type:"string",description:"Opportunity ID"},status:{type:"string",enum:["nova","em_analise","aceita","recusada","concluida"],description:"New status"}},required:["id","status"]}}],S5=[{name:"pitwall_benchmark",description:"Benchmark a local script or command \u2014 captures wall-clock time, child process peak memory, and CPU overhead. "+'Compares against saved baseline and alerts on regressions > 10%. Use when the user says "benchmark", "mede a performance", "testa a velocidade", "pit wall".',input_schema:{type:"object",properties:{command:{type:"string",description:'Shell command to benchmark (e.g. "bun run build", "bun test").'},key:{type:"string",description:"Unique label for this benchmark. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs (uses median). Default 1, max 10."},warmup:{type:"boolean",description:"Run one warmup iteration before measuring (discarded). Default false."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_save_baseline",description:'Benchmark a command and save results as the performance baseline for future comparisons. Default: 3 runs with warmup. Use "reset" to replace (not blend) an existing baseline.',input_schema:{type:"object",properties:{command:{type:"string",description:"Command to benchmark and save as baseline."},key:{type:"string",description:"Benchmark label. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs to measure. Default 3."},tags:{type:"array",items:{type:"string"},description:'Tags for this baseline (e.g. "build", "test").'},reset:{type:"boolean",description:"If true, replaces existing baseline entirely. Default false (blends)."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_status",description:'List all saved performance baselines with their metrics, spread, and age. Use when the user asks "quais baselines tenho?", "pit wall status", "mostra as metricas".',input_schema:{type:"object",properties:{},required:[]}},{name:"pitwall_remove_baseline",description:"Remove a saved performance baseline by its key.",input_schema:{type:"object",properties:{key:{type:"string",description:"The script key of the baseline to remove."}},required:["key"]}}],w5=[{name:"analyze_blast_radius",description:"Analyze the blast radius of changing a TypeScript file \u2014 shows all modules that import it (directly and transitively). "+'Use when the user says "blast radius", "impacto da mudanca", "quem depende de", "o que quebra se mudar".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file to analyze (relative or absolute)."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}},{name:"plan_refactor",description:'Generate a safe refactor order for updating dependents of a TypeScript file. Returns a numbered sequence: change the target first, then update dependents bottom-up. Use when the user says "plano de refatoracao", "ordem de atualizacao", "como refatorar seguro".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file being refactored."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}}],k5=[{name:"evaluate_architecture_tradeoffs",description:"Analyze trade-offs between architectural options using a weighted evaluation matrix. Returns an ADR (Architecture Decision Record) with recommendation. Default criteria: Maintainability (30%), Performance (25%), Learning Curve (20%), Infrastructure Cost (25%). Use when comparing technologies, frameworks, patterns, or infrastructure choices.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the decision, e.g., "Redis vs SQLite for session storage".'},background:{type:"string",description:"Context and background of the decision \u2014 why is this decision needed?"},constraints:{type:"array",items:{type:"string"},description:'Project constraints, e.g., "Must run on Kubernetes", "Budget < $100/mo".'},stakeholders:{type:"array",items:{type:"string"},description:'People/teams affected, e.g., "Backend Team", "DevOps".'},options:{type:"array",items:{type:"object",properties:{name:{type:"string",description:'Option name, e.g., "Redis".'},description:{type:"string",description:"Brief description of this option."},scores:{type:"object",description:"Scores for each criterion (1-5). Keys: maintainability, performance, learning_curve, infrastructure_cost."},pros:{type:"array",items:{type:"string"},description:"Advantages of this option."},cons:{type:"array",items:{type:"string"},description:"Disadvantages of this option."}},required:["name","description","scores","pros","cons"]},description:"List of options to compare (minimum 2)."},custom_criteria:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Criterion name."},weight:{type:"number",description:"Weight (0.0-1.0). Must sum to 1.0 across all criteria."},description:{type:"string",description:"What this criterion measures."}},required:["name","weight","description"]},description:"Optional custom criteria. If not provided, uses default criteria."}},required:["title","background","options"]}},{name:"correlate_incident",description:"Analyze an error or bug and search for similar past incidents, related decisions, and relevant materials. Returns correlation matches with suggested solutions and actions based on historical data. Use when debugging, troubleshooting, or investigating an error.",input_schema:{type:"object",properties:{description:{type:"string",description:"Description of the current error or bug."},stacktrace:{type:"string",description:"Optional stacktrace or error output for better matching."}},required:["description"]}},{name:"log_incident",description:"Log a resolved incident for future correlation. This feeds the Post-Mortem database. Use after resolving a bug to help accelerate future debugging.",input_schema:{type:"object",properties:{title:{type:"string",description:"Short title of the incident."},description:{type:"string",description:"Detailed description of what happened."},root_cause:{type:"string",description:"Root cause analysis."},solution:{type:"string",description:"How the incident was resolved."},stacktrace:{type:"string",description:"Optional stacktrace for better correlation."},related_decisions:{type:"array",items:{type:"string"},description:"IDs of related decisions from the Decision Log."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization, e.g., "memory-leak", "timeout", "auth".'}},required:["title","description","root_cause","solution"]}},{name:"list_tradeoff_analyses",description:"List past architecture trade-off analyses. Use to review previous decisions and their rationale.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Maximum number of results (default 10)."},query:{type:"string",description:"Optional search query to filter results."}},required:[]}},{name:"list_incidents",description:"List logged incidents from the Post-Mortem database. Use to review past issues and solutions.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Maximum number of results (default 10)."},query:{type:"string",description:"Optional search query to filter results."}},required:[]}},{name:"get_tradeoff_adr",description:"Get the full ADR (Architecture Decision Record) for a past trade-off analysis by ID. Returns the complete Markdown document.",input_schema:{type:"object",properties:{id:{type:"string",description:"ID of the trade-off analysis."}},required:["id"]}}],b5=[{name:"manage_news_feeds",description:'Manage RSS/Atom news feed sources. Actions: add (add custom feed), remove (remove custom feed), disable (disable a built-in feed), enable (re-enable a disabled built-in), list (show all feeds). Use when the user says "adiciona essa fonte", "remove o feed", "desativa o TechCrunch", "mostra as fontes".',input_schema:{type:"object",properties:{action:{type:"string",enum:["add","remove","disable","enable","list"],description:"Action to perform."},name:{type:"string",description:"Feed name (for add) or name/URL reference (for remove/disable/enable)."},url:{type:"string",description:"RSS/Atom feed URL (required for add)."},category:{type:"string",description:"Category for the feed (required for add). E.g. tech, finance, ai, devops."}},required:["action"]}}],y5=[{name:"archive_session",description:'Archive a conversation session. Archived sessions are preserved but removed from the active list. Use "all" as name to archive all sessions except the current one.',input_schema:{type:"object",properties:{name:{type:"string",description:'Session name to archive, or "all" to archive all except current.'}},required:["name"]}},{name:"unarchive_session",description:"Restore an archived session back to the active sessions list.",input_schema:{type:"object",properties:{name:{type:"string",description:"Archived session name to restore."}},required:["name"]}},{name:"list_archived_sessions",description:"List all archived conversation sessions with message count and last update.",input_schema:{type:"object",properties:{},required:[]}}],_5=[{name:"update_living_manual",description:"Silently update the living manual with a structured insight or best practice. The manual is stored at ~/.config/smolerclaw/materials/manual/ and persists across sessions. Use when you observe a pattern that could help the user work more efficiently, or when they ask to document a workflow. Categories: workflow, tool, shortcut, best_practice.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the manual entry (e.g. "Atalho para commits rapidos")'},content:{type:"string",description:"Full content in markdown format. Include steps, examples, and tips."},category:{type:"string",enum:["workflow","tool","shortcut","best_practice"],description:"Category. Default: best_practice."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization (e.g. "git", "automacao", "produtividade"). Optional.'}},required:["title","content"]}},{name:"explain_optimal_usage",description:'Generate an interactive tutorial explaining how to use smolerclaw more efficiently. Consults the living manual (via RAG or direct read) and recent insights to build a contextual guide. Use when the user asks "como usar melhor?", "dicas de uso", "tutorial", or seems to be using tools inefficiently.',input_schema:{type:"object",properties:{topic:{type:"string",description:'Optional topic to focus on (e.g. "workflows", "git", "tarefas"). If omitted, shows general tips.'}},required:[]}},{name:"trigger_self_reflection",description:"Manually trigger the self-reflection analysis. Analyzes recent actions to detect patterns, generate insights about repetitive tasks, underutilized tools, and inefficient patterns. Updates the living manual with findings. Use at end of session or when user asks for usage analysis.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_usage_insights",description:'Get recent insights generated by the meta-learning engine. Shows detected patterns, tips, and recommendations based on observed usage. Use when the user asks "o que aprendi?", "insights de uso", or wants to see optimization suggestions.',input_schema:{type:"object",properties:{count:{type:"number",description:"Number of recent insights to show. Default 5."}},required:[]}}];async function dQ($,Z,Y){switch($){case"open_application":return await $1(Z.name,Z.argument);case"open_file_default":return await s8(Z.path);case"open_url_browser":return await Z1(Z.url);case"get_running_apps":return await t8();case"get_system_info":return await Y1();case"get_calendar_events":return await f$();case"get_news":{let Q=Z.category;return await L0(Q?[Q]:void 0)}case"create_task":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.time,z=J?P1(J):void 0,X=R7(Q,z||void 0),K=z?` \u2014 lembrete: ${z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${X.title}"${K} [${X.id}]`}case"complete_task":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let J=E7(Q);return J?`Concluida: "${J.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,J=t$(Q);return i0(J)}case"schedule_job":{let{name:Q,time:J,message:z}=Z;if(!Q?.trim()||!J?.trim()||!z?.trim())return"Error: name, time, and message are required.";let X=_7(J);if(!X)return`Error: invalid time format "${J}". Use HH:MM.`;let K=Z.schedule_type||"once",V;if(Z.date_or_day){let q=Z.date_or_day;if(K==="weekly")V=v7(q)??void 0;else V=x7(q)??void 0}if(K==="once"&&!V){let q=new Date,[U,W]=X.split(":").map(Number),B=new Date(q);if(B.setHours(U,W,0,0),B<=q)B.setDate(B.getDate()+1);V=[String(B.getMonth()+1).padStart(2,"0"),String(B.getDate()).padStart(2,"0"),String(B.getFullYear())].join("/")}let G=await S7(Q,K,X,"toast",z,V);return`Agendamento criado: "${G.name}" [${G.id}] \u2014 ${G.scheduleType} \xE0s ${G.time}`}case"remove_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await w7(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,J=m8(Q);return u8(J)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let J=await k7(Q);return J?`Agendamento "${J.name}" ativado.`:`Agendamento nao encontrado: "${Q}"`}case"disable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let J=await b7(Q);return J?`Agendamento "${J.name}" desativado.`:`Agendamento nao encontrado: "${Q}"`}case"run_scheduled_job_now":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await y7(Q)}case"add_person":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let J=Z.group;if(!["equipe","familia","contato"].includes(J))return"Error: group must be equipe, familia, or contato.";let X=o7(Q,J,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${J}) [${X.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let J=e$(Q);if(!J)return`Pessoa nao encontrada: "${Q}"`;return r7(J)}case"list_people":{let Q=Z.group,J=i7(Q);return n7(J)}case"log_interaction":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let{type:J,summary:z}=Z;if(!z?.trim())return"Error: summary is required.";let X=Z.follow_up,K=X?a9(X):void 0;if(!FY(Q,J,z,K||void 0))return`Pessoa nao encontrada: "${Q}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${J} com ${Q}${G}`}case"delegate_to_person":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let J=Z.task;if(!J?.trim())return"Error: task is required.";let z=Z.due_date,X=z?a9(z):void 0,K=a7(Q,J,X||void 0);if(!K)return`Pessoa nao encontrada: "${Q}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${J}"${V} [${K.id}]`}case"update_delegation_status":{let Q=Z.delegation_id;if(!Q?.trim())return"Error: delegation_id is required.";let J=Z.status,z=RY(Q,J,Z.notes);if(!z)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${z.task}" -> ${J}`}case"get_people_dashboard":return LY();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let J=Z.tags||[],z=L7(Q,J);return`Memo salvo${z.tags.length>0?` [${z.tags.map((K)=>"#"+K).join(" ")}]`:""} {${z.id}}`}case"search_memos":{let Q=Z.query;if(!Q?.trim())return a0(g8());let J=j7(Q);return a0(J)}case"record_transaction":{let{type:Q,amount:J,category:z,description:X}=Z;if(!Q||!J||!z||!X)return"Error: all fields required.";let K=d8(Q,J,z,X);if(!K.allowed)return`Error: ${K.blocked}`;let V=p8(Q,J,z,X);c8(Q,J,z);let G=V.type==="entrada"?"+":"-",q=l8(K);return`${G} R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description} [${V.id}]${q?`
387
- `+q:""}`}case"financial_summary":return h7();case"log_decision":{let{title:Q,context:J,chosen:z}=Z;if(!Q||!J||!z)return"Error: title, context, and chosen are required.";let X=VY(Q,J,z,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let Q=Z.query;if(!Q?.trim())return T1(p7());return T1(n0(Q))}case"open_investigation":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.type;if(!["bug","feature","test","audit","incident"].includes(J))return"Error: type must be bug, feature, test, audit, or incident.";let X=H9(Q,J,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${X.title}" (${X.type}) {${X.id}}`}case"collect_evidence":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{source:J,label:z,content:X}=Z;if(!z?.trim()||!X?.trim())return"Error: label and content are required.";let K=W9(Q,J,z,X,Z.path);if(!K)return`Investigacao nao encontrada: "${Q}"`;return`Evidencia coletada: [${K.id}] ${K.source}: ${K.label}`}case"add_finding":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{severity:J,title:z,description:X}=Z;if(!z?.trim()||!X?.trim())return"Error: title and description are required.";let K=Z.evidence_ids||[],V=B9(Q,J,z,X,K);if(!V)return`Investigacao nao encontrada: "${Q}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let J=Z.summary;if(!J?.trim())return"Error: summary is required.";let z=M9(Q,J,Z.recommendations);if(!z)return`Investigacao nao encontrada: "${Q}"`;return`Investigacao concluida: "${z.title}" \u2014 ${z.evidence.length} evidencias, ${z.findings.length} conclusoes`}case"investigation_status":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let J=C9(Q);if(!J)return`Investigacao nao encontrada: "${Q}"`;return R9(J)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let J=F9(Q);if(!J)return`Investigacao nao encontrada: "${Q}"`;return J}case"list_investigations":{let Q=Z.query;if(Q?.trim())return c7(O9(Q));let{status:J,type:z}=Z;return c7(N9(J,z))}case"draft_email":{let{to:Q,subject:J,body:z}=Z;if(!Q?.trim()||!J?.trim()||!z?.trim())return"Error: to, subject, and body are required.";let X={to:Q,subject:J,body:z,cc:Z.cc},K=P7(X),V=await D7(X);return`${K}
388
-
389
- ${V}`}case"save_material":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.content;if(!J?.trim())return"Error: content is required.";let z=Z.category||"geral",X=Z.tags||[],K=e7(Q,J,z,X),V=K.tags.length>0?` [${K.tags.map((G)=>"#"+G).join(" ")}]`:"";return`Material salvo: "${K.title}" (${K.category})${V} {${K.id}}`}case"search_materials":{let Q=Z.query;if(!Q?.trim())return A0(w1());let J=S1(Q);return A0(J)}case"list_materials":{let Q=Z.category,J=Z.limit||30,z=w1(J,Q);return A0(z)}case"update_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let J={};if(Z.title)J.title=Z.title;if(Z.content)J.content=Z.content;if(Z.category)J.category=Z.category;if(Z.tags)J.tags=Z.tags;let z=TY(Q,J);if(!z)return`Material nao encontrado: "${Q}"`;return`Material atualizado: "${z.title}" (${z.category}) {${z.id}}`}case"delete_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";return $5(Q)?"Material removido.":`Material nao encontrado: "${Q}"`}case"execute_powershell_script":{let Q=Z.script;if(!Q?.trim())return"Error: script is required.";let J=i9(Q);if(J.blocked)return`BLOCKED: ${J.reason}
390
- Esse tipo de operacao nao e permitido.`;if(!J.safe&&J.reason);let z=await e8(Q),X=[];if(z.stdout.trim())X.push(`stdout:
391
- ${z.stdout.trim()}`);if(z.stderr.trim())X.push(`stderr:
392
- ${z.stderr.trim()}`);return X.push(`exit: ${z.exitCode} (${z.duration}ms)`),X.join(`
393
-
394
- `)}case"analyze_screen_context":return await O5();case"read_clipboard_content":{let Q=await N5();switch(Q.type){case"text":return`Clipboard (texto):
395
- ${Q.text}`;case"image":return Q.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${Q.text}`}}case"send_notification":{let{title:Q,message:J}=Z,z=await uQ(Q,J);if(z.success)return`Notifica\xE7\xE3o enviada: "${Q}"`;return`Erro ao enviar notifica\xE7\xE3o: ${z.error}`}case"manage_news_feeds":switch(Z.action){case"list":return O7();case"add":{let{name:J,url:z,category:X}=Z;if(!J?.trim())return"Error: name is required for add.";if(!z?.trim())return"Error: url is required for add.";if(!X?.trim())return"Error: category is required for add.";let K=B7(J,z,X);if(typeof K==="string")return K;return`Fonte adicionada: ${K.name} (${K.category}) \u2014 ${K.url}`}case"remove":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return M7(J)?`Fonte removida: ${J}`:`Fonte custom nao encontrada: "${J}"`}case"disable":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return C7(J)?`Fonte desativada: ${J}`:`Fonte built-in nao encontrada ou ja desativada: "${J}"`}case"enable":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return N7(J)?`Fonte reativada: ${J}`:`Fonte nao encontrada ou nao esta desativada: "${J}"`}default:return"Error: action must be add, remove, disable, enable, or list."}case"set_active_project":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";if(Q==="auto"){let z=H5(process.cwd());if(!z)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return y1(z.id),`Projeto ativo: "${z.name}" (${z.path}) \u2014 auto-detectado [${z.id}]`}let J=y1(Q);if(!J)return`Projeto nao encontrado: "${Q}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${J.name}" (${J.path}) [${J.id}]`}case"report_work_progress":{let Q=Z.project||"",J=Z.period||"today",z=Z.lang||"pt",X=Z.save_to_file,K=Q;if(!K){let G=I0();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=G.id}let V=await K5(K,J,z);if(!V)return`Projeto nao encontrado: "${K}"`;if(X)return VU(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
396
-
397
- ${V.markdown}`;return V.markdown}case"manage_work_session":{let Q=Z.action,J=Z.notes||"",z=I0();if(!z)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=J5(z.id,J);if(!X)return"Erro ao iniciar sessao.";return`Sessao iniciada para "${z.name}" as ${new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}. [${X.id}]`}case"stop":{let X=S0(z.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=z5(X.id,J);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${z.name}".`}case"status":{let X=S0(z.id);if(!X)return`Nenhuma sessao aberta para "${z.name}".`;let K=new Date(X.startedAt),V=Math.round((Date.now()-K.getTime())/60000);return`Sessao aberta: "${z.name}" \u2014 ${V} minutos (desde ${K.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let J=Z.path;if(!J?.trim())return"Error: path is required.";let z=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],V=I9(Q,J,z,K,X);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let Q=Z.active_only||!1;return V5(b1(Q))}case"fetch_opportunities":{let{status:Q,tech:J}=Z,z=X5(Q,J);return q5(z)}case"add_opportunity":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.description;if(!J?.trim())return"Error: description is required.";let z=Z.source;if(!z?.trim())return"Error: source is required.";let X=Z.tech_required||[],K=Z.priority||"media",V=Z.deadline||null,G=gY(Q,J,z,X,K,V);return`Oportunidade registrada: "${G.title}" (${G.priority}) [${G.id}]`}case"update_opportunity_status":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let J=Z.status,z=mY(Q,J);if(!z)return`Oportunidade nao encontrada: "${Q}"`;return`Oportunidade atualizada: "${z.title}" -> ${J}`}case"pitwall_benchmark":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let J=Z.key,z=Math.min(Math.max(Z.iterations||1,1),10),X=Z.warmup||!1,K=Z.cwd,V=await y9(Q,{scriptKey:J,cwd:K,iterations:z,warmup:X});if(V.exitCode!==0){let G=x9(V);return`AVISO: Comando terminou com exit code ${V.exitCode}. Metricas podem nao ser confiaveis.
398
-
399
- ${G.markdown}`}return x9(V).markdown}case"pitwall_save_baseline":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let J=Z.key,z=Math.min(Math.max(Z.iterations||3,1),10),X=Z.tags||[],K=Z.reset||!1,V=Z.cwd,G=await y9(Q,{scriptKey:J,cwd:V,iterations:z,warmup:!0});if(G.exitCode!==0)return`Error: Comando falhou (exit code ${G.exitCode}). Corrija o comando antes de salvar baseline.
400
- `+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let q=K?rY(G,X):aY(G,X),U=q.metrics.durationNs/1e6;return`Baseline salvo: "${q.scriptKey}" (${q.runs} run${q.runs>1?"s":""})
401
- Duracao: ${U.toFixed(2)}ms
402
- Memoria: ${(q.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
403
- CPU (user): ${(q.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return tY(nY());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return _9(Q)?`Baseline removido: "${Q}"`:`Baseline nao encontrado: "${Q}"`}case"analyze_blast_radius":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let J=F5(Z.project_dir||process.cwd()),z=F5(J,Q);if(!z.startsWith(J+pQ))return"Error: file must be inside project_dir.";try{let X=f9(J),K=h9(X,z);return JQ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"plan_refactor":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let J=F5(Z.project_dir||process.cwd()),z=F5(J,Q);if(!z.startsWith(J+pQ))return"Error: file must be inside project_dir.";try{let X=f9(J),K=QQ(X,z);return XQ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"archive_session":{if(!Y)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";if(Q==="all"){let J=Y.archiveAll();return J.length>0?`Arquivadas ${J.length} sessoes: ${J.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return Y.archive(Q)?`Sessao arquivada: "${Q}"`:`Falha ao arquivar "${Q}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!Y)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";return Y.unarchive(Q)?`Sessao restaurada: "${Q}"`:`Sessao arquivada nao encontrada: "${Q}"`}case"list_archived_sessions":{if(!Y)return"Error: session manager not initialized.";let Q=Y.listArchived();if(Q.length===0)return"Nenhuma sessao arquivada.";let J=Q.map((z)=>{let X=Y.getArchivedInfo(z),K=X?new Date(X.updated).toLocaleDateString("pt-BR"):"",V=X?`${X.messageCount} msgs`:"";return` ${z.padEnd(20)} ${V.padEnd(10)} ${K}`});return`Sessoes arquivadas (${Q.length}):
404
- ${J.join(`
405
- `)}`}case"evaluate_architecture_tradeoffs":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.background;if(!J?.trim())return"Error: background is required.";let z=Z.options;if(!z||z.length<2)return"Error: at least 2 options are required.";let X={title:Q.trim(),background:J.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},K=z.map((U)=>({name:U.name.trim(),description:U.description.trim(),scores:U.scores,pros:U.pros||[],cons:U.cons||[]})),V=Z.custom_criteria,G=V&&V.length>0?V:m9;return WQ(X,K,G).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let J=Z.stacktrace;return BQ(Q,J).summary}case"log_incident":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.description;if(!J?.trim())return"Error: description is required.";let z=Z.root_cause;if(!z?.trim())return"Error: root_cause is required.";let X=Z.solution;if(!X?.trim())return"Error: solution is required.";let K=MQ(Q,J,z,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
394
+ `;try{let J=await K8(z);if(J.exitCode===0&&J.stdout.includes("OK"))return{success:!0};return{success:!1,error:J.stderr||"Unknown error sending notification."}}catch(J){return{success:!1,error:J instanceof Error?J.message:String(J)}}}var G8=50000;function o0($){if($.length<=G8)return $;return $.slice(0,G8)+`
395
+ ... (output truncated)`}function V8($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function RZ($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje")return Y;if(Z==="amanha"||Z==="amanh\xE3"){let K=new Date(Y);return K.setDate(K.getDate()+1),K}let Q=Z.match(/em\s+(\d+)\s*dias?/);if(Q){let K=new Date(Y);return K.setDate(K.getDate()+parseInt(Q[1])),K}let z=Z.match(/em\s+(\d+)\s*semanas?/);if(z){let K=new Date(Y);return K.setDate(K.getDate()+parseInt(z[1])*7),K}let J={domingo:0,segunda:1,terca:2,ter\u{e7}a:2,quarta:3,quinta:4,sexta:5,sabado:6,s\u{e1}bado:6};for(let[K,G]of Object.entries(J))if(Z.includes(K)){let V=new Date(Y),U=(G-V.getDay()+7)%7||7;return V.setDate(V.getDate()+U),V}let X=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(X){let K=parseInt(X[1]),G=parseInt(X[2])-1,V=X[3]?parseInt(X[3])+(X[3].length===2?2000:0):Y.getFullYear(),U=new Date(V,G,K);if(!isNaN(U.getTime()))return U}return f$(Z)}var y5=[{name:"create_task",description:'Create a task or reminder for the user. If a time is provided, a notification will fire at that time. Supports natural-language times like "18h", "em 30 minutos", "amanha 9h".',input_schema:{type:"object",properties:{title:{type:"string",description:'Task description (e.g. "buscar pao")'},time:{type:"string",description:'When to remind. E.g. "18h", "18:30", "em 30 minutos", "amanha 9h". Optional.'}},required:["title"]}},{name:"complete_task",description:"Mark a task as done by its ID or partial title match.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Task ID or partial title to match"}},required:["reference"]}},{name:"list_tasks",description:"List all pending tasks and reminders. Shows title, due time, and ID.",input_schema:{type:"object",properties:{show_done:{type:"boolean",description:"Include completed tasks. Default false."}},required:[]}}],_5=[{name:"schedule_job",description:"Create a persistent scheduled job using Windows Task Scheduler. Jobs fire even when smolerclaw is not running. Supports one-time, daily, and weekly schedules.",input_schema:{type:"object",properties:{name:{type:"string",description:"Human-readable name for the job"},time:{type:"string",description:'Time in HH:MM format (e.g., "14:00", "09:30")'},message:{type:"string",description:"Message to display in the notification"},schedule_type:{type:"string",enum:["once","daily","weekly"],description:"Schedule type: once (single execution), daily, or weekly. Default: once"},date_or_day:{type:"string",description:'For "once": date in DD/MM/YYYY format or "hoje"/"amanha". For "weekly": day name (e.g., "segunda", "friday"). Optional.'}},required:["name","time","message"]}},{name:"remove_scheduled_job",description:"Remove a scheduled job by its ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"list_scheduled_jobs",description:"List all scheduled jobs. Shows name, schedule, and status.",input_schema:{type:"object",properties:{include_disabled:{type:"boolean",description:"Include disabled jobs. Default false."}},required:[]}},{name:"enable_scheduled_job",description:"Enable a previously disabled scheduled job.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"disable_scheduled_job",description:"Disable a scheduled job without removing it.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"run_scheduled_job_now",description:"Execute a scheduled job immediately (for testing).",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}}],x5=[{name:"add_person",description:"Register a person (team member, family, or contact). Groups: equipe (work team), familia (family/home), contato (other contacts).",input_schema:{type:"object",properties:{name:{type:"string",description:"Person name"},group:{type:"string",enum:["equipe","familia","contato"],description:"Group: equipe, familia, or contato"},role:{type:"string",description:'Role or relationship (e.g. "dev frontend", "esposa", "fornecedor"). Optional.'},contact:{type:"string",description:"Phone, email, or other contact info. Optional."}},required:["name","group"]}},{name:"find_person_info",description:"Look up a person by name or ID. Returns their profile, recent interactions, and pending delegated tasks.",input_schema:{type:"object",properties:{name_or_id:{type:"string",description:"Person name (partial match) or ID"}},required:["name_or_id"]}},{name:"list_people",description:"List all registered people, optionally filtered by group.",input_schema:{type:"object",properties:{group:{type:"string",enum:["equipe","familia","contato"],description:"Filter by group. Optional."}},required:[]}},{name:"log_interaction",description:"Log an interaction with a person. Types: conversa, email, reuniao, ligacao, mensagem, delegacao, entrega, outro. Optionally set a follow-up date for a reminder.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},type:{type:"string",enum:["conversa","email","reuniao","ligacao","mensagem","delegacao","entrega","outro"],description:"Interaction type"},summary:{type:"string",description:"What was discussed or happened"},follow_up:{type:"string",description:'When to follow up (e.g. "em 3 dias", "amanha", "25/03"). Optional.'}},required:["person","type","summary"]}},{name:"delegate_to_person",description:"Delegate/assign a task to a person with optional due date. Use to track what you asked someone to do.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},task:{type:"string",description:"What they need to do"},due_date:{type:"string",description:'Due date (e.g. "sexta", "em 3 dias", "28/03"). Optional.'}},required:["person","task"]}},{name:"update_delegation_status",description:"Update the status of a delegated task. Statuses: pendente, em_andamento, concluido.",input_schema:{type:"object",properties:{delegation_id:{type:"string",description:"Delegation ID"},status:{type:"string",enum:["pendente","em_andamento","concluido"],description:"New status"},notes:{type:"string",description:"Optional notes about the update"}},required:["delegation_id","status"]}},{name:"get_people_dashboard",description:"Show the people management dashboard: summary of team/family/contacts, overdue follow-ups, overdue delegations, and recent interactions.",input_schema:{type:"object",properties:{},required:[]}}],v5=[{name:"save_memo",description:`Save a note/memo to the user's personal knowledge base. Use #hashtags in the content to auto-tag. Use when the user says "anota", "lembra disso", "salva isso", or shares important information.`,input_schema:{type:"object",properties:{content:{type:"string",description:"The memo content. Use #tags for categorization."},tags:{type:"array",items:{type:"string"},description:"Optional additional tags (without #). Auto-extracted #tags from content are always included."}},required:["content"]}},{name:"search_memos",description:`Search the user's memos by keyword or tag. Use #tag to search by tag only. Use plain text for content search. Use when the user asks "o que eu anotei sobre...", "qual era aquela nota...", etc.`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search query. Use #tag for tag search, or plain text for content search."}},required:["query"]}}],h5={name:"draft_email",description:'Create an email draft and open it in Outlook (Windows) or the default mail client. The user can review and send manually. Use when the user says "escreve um email", "manda um email", "rascunho de email", etc.',input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC recipients (optional)"}},required:["to","subject","body"]}},g5=[{name:"record_transaction",description:"Record a financial transaction (income or expense). Use when user mentions spending, receiving money, or financial tracking.",input_schema:{type:"object",properties:{type:{type:"string",enum:["entrada","saida"],description:"Transaction type: entrada (income) or saida (expense)"},amount:{type:"number",description:"Amount in BRL (always positive)"},category:{type:"string",description:"Category (e.g. alimentacao, transporte, salario, freelance)"},description:{type:"string",description:"Description of the transaction"}},required:["type","amount","category","description"]}},{name:"financial_summary",description:"Show monthly financial summary with income, expenses, and balance by category.",input_schema:{type:"object",properties:{},required:[]}},{name:"log_decision",description:'Record an important decision with context and rationale. Use when the user says "decidi", "optei por", "escolhi", or discusses a major choice.',input_schema:{type:"object",properties:{title:{type:"string",description:"Decision title (short)"},context:{type:"string",description:"Why this decision was needed"},chosen:{type:"string",description:"What was decided"},alternatives:{type:"string",description:"What was considered but rejected. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["title","context","chosen"]}},{name:"search_decisions",description:"Search past decisions by keyword or tag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}],m5=[{name:"open_investigation",description:'Start a new investigation to systematically collect evidence. Types: bug (malfunction), feature (material for building), test (test scenarios), audit (code review), incident (runtime issue). Use when the user says "investiga", "analisa", "diagnostica", "verifica", or needs structured evidence collection.',input_schema:{type:"object",properties:{title:{type:"string",description:"Investigation title (short, descriptive)"},type:{type:"string",enum:["bug","feature","test","audit","incident"],description:"Investigation type"},hypothesis:{type:"string",description:"Initial theory or goal to investigate. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["title","type"]}},{name:"collect_evidence",description:"Add a piece of evidence to an active investigation. Sources: file (file content), command (command output), log (log entries), diff (code changes), url (web content), observation (manual note). Use after reading files, running commands, or observing behavior to build the investigation record.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title (partial match)"},source:{type:"string",enum:["file","command","log","diff","url","observation"],description:"Evidence source type"},label:{type:"string",description:"Short description of this evidence"},content:{type:"string",description:"The evidence data (file content, command output, observation text, etc.)"},path:{type:"string",description:"File path or URL associated with this evidence. Optional."}},required:["investigation","source","label","content"]}},{name:"add_finding",description:"Record a conclusion or insight derived from collected evidence. Severity: critical, high, medium, low, info. Link to evidence IDs that support this finding.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"},severity:{type:"string",enum:["critical","high","medium","low","info"],description:"Finding severity"},title:{type:"string",description:"Finding title (short)"},description:{type:"string",description:"Detailed description of the finding"},evidence_ids:{type:"array",items:{type:"string"},description:"IDs of evidence supporting this finding. Optional."}},required:["investigation","severity","title","description"]}},{name:"close_investigation",description:"Close an investigation with a summary and recommendations. Use after all evidence is collected and findings are recorded.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"},summary:{type:"string",description:"Final summary of the investigation"},recommendations:{type:"string",description:"Action items and next steps. Optional."}},required:["investigation","summary"]}},{name:"investigation_status",description:"View the current state of an investigation: evidence collected, findings, and progress. Use to check progress or review before closing.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"}},required:["investigation"]}},{name:"investigation_report",description:"Generate a full structured report (markdown) for an investigation. Includes all evidence, findings, summary, and recommendations.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"}},required:["investigation"]}},{name:"list_investigations",description:"List all investigations, optionally filtered by status or type.",input_schema:{type:"object",properties:{status:{type:"string",enum:["aberta","em_andamento","concluida","arquivada"],description:"Filter by status. Optional."},type:{type:"string",enum:["bug","feature","test","audit","incident"],description:"Filter by type. Optional."},query:{type:"string",description:"Search by keyword. Optional."}},required:[]}}],u5=[{name:"save_material",description:`Save reference material to the assistant's persistent knowledge base. Materials are categorized documents, guides, procedures, or reference info that persists across sessions. Use when the user says "salva esse material", "guarda essa referencia", "adiciona ao conhecimento", etc. Categories: procedimento, referencia, guia, template, contato, projeto, tecnico, geral.`,input_schema:{type:"object",properties:{title:{type:"string",description:"Title of the material"},content:{type:"string",description:"Full content. Use #tags for categorization."},category:{type:"string",description:"Category (e.g. procedimento, referencia, guia, template, contato, projeto, tecnico, geral). Default: geral."},tags:{type:"array",items:{type:"string"},description:"Optional additional tags (without #)."}},required:["title","content"]}},{name:"search_materials",description:"Search the assistant's material knowledge base by keyword, tag (#tag), or category (@category). Use when answering questions that may be covered by saved materials, or when user asks about reference docs.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query. Use #tag for tag search, @category for category search, or plain text."}},required:["query"]}},{name:"list_materials",description:"List all saved materials, optionally filtered by category.",input_schema:{type:"object",properties:{category:{type:"string",description:"Filter by category. Optional."},limit:{type:"number",description:"Max results. Default 30."}},required:[]}},{name:"update_material",description:"Update an existing material by ID. Can change title, content, category, or tags.",input_schema:{type:"object",properties:{id:{type:"string",description:"Material ID"},title:{type:"string",description:"New title. Optional."},content:{type:"string",description:"New content. Optional."},category:{type:"string",description:"New category. Optional."},tags:{type:"array",items:{type:"string"},description:"New tags. Optional."}},required:["id"]}},{name:"delete_material",description:"Delete a material by ID.",input_schema:{type:"object",properties:{id:{type:"string",description:"Material ID"}},required:["id"]}}],p5=[{name:"set_active_project",description:'Set which project the assistant should focus on. Auto-detects from the current directory if not registered. Use when the user says "estou trabalhando no projeto X", "muda pro projeto Y", or starts work.',input_schema:{type:"object",properties:{name_or_id:{type:"string",description:'Project name, ID, or "auto" to detect from current directory.'}},required:["name_or_id"]}},{name:"report_work_progress",description:'Generate a work progress report with git commits, time tracked, and tasks completed. Outputs a structured Markdown document. Use when the user says "relatorio", "como estou no projeto", "resumo do trabalho", "progress report".',input_schema:{type:"object",properties:{project:{type:"string",description:"Project name/ID. Defaults to active project."},period:{type:"string",enum:["today","week","month"],description:"Report period. Default: today."},lang:{type:"string",enum:["pt","en"],description:"Report language. Default: pt."},save_to_file:{type:"string",description:"Optional file path to save the report. If omitted, returns as text."}},required:[]}},{name:"manage_work_session",description:'Start or stop a work session timer for time tracking. Use when the user says "comecei a trabalhar", "parei de trabalhar", "timer", etc.',input_schema:{type:"object",properties:{action:{type:"string",enum:["start","stop","status"],description:"Start, stop, or check session status."},notes:{type:"string",description:"Optional notes for the session."}},required:["action"]}},{name:"add_project",description:"Register a new project for tracking. Use when the user mentions a new project or wants to track a directory.",input_schema:{type:"object",properties:{name:{type:"string",description:"Project name"},path:{type:"string",description:"Filesystem path to the project root"},description:{type:"string",description:"Brief project description. Optional."},tech_stack:{type:"array",items:{type:"string"},description:"Technologies used. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["name","path"]}},{name:"list_projects",description:"List all registered projects with their status and tech stack.",input_schema:{type:"object",properties:{active_only:{type:"boolean",description:"Show only active projects. Default false."}},required:[]}},{name:"fetch_opportunities",description:'List pending opportunities/tasks filtered by tech stack or priority. Use when the user asks "tem alguma demanda nova?", "oportunidades", "o que tem pra fazer?".',input_schema:{type:"object",properties:{status:{type:"string",enum:["nova","em_analise","aceita","recusada","concluida"],description:"Filter by status. Optional."},tech:{type:"array",items:{type:"string"},description:"Filter by required tech. Optional."}},required:[]}},{name:"add_opportunity",description:"Register a new task/opportunity/demand for tracking. Use when the user mentions a potential project, job lead, or new demand.",input_schema:{type:"object",properties:{title:{type:"string",description:"Opportunity title"},description:{type:"string",description:"Details about the opportunity"},source:{type:"string",description:'Where this came from (e.g. "LinkedIn", "email", "contato direto")'},tech_required:{type:"array",items:{type:"string"},description:"Technologies required. Optional."},priority:{type:"string",enum:["alta","media","baixa"],description:"Priority level. Default: media."},deadline:{type:"string",description:'Deadline if any (e.g. "30/04", "em 2 semanas"). Optional.'}},required:["title","description","source"]}},{name:"update_opportunity_status",description:"Update the status of an opportunity.",input_schema:{type:"object",properties:{id:{type:"string",description:"Opportunity ID"},status:{type:"string",enum:["nova","em_analise","aceita","recusada","concluida"],description:"New status"}},required:["id","status"]}}],d5=[{name:"pitwall_benchmark",description:"Benchmark a local script or command \u2014 captures wall-clock time, child process peak memory, and CPU overhead. "+'Compares against saved baseline and alerts on regressions > 10%. Use when the user says "benchmark", "mede a performance", "testa a velocidade", "pit wall".',input_schema:{type:"object",properties:{command:{type:"string",description:'Shell command to benchmark (e.g. "bun run build", "bun test").'},key:{type:"string",description:"Unique label for this benchmark. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs (uses median). Default 1, max 10."},warmup:{type:"boolean",description:"Run one warmup iteration before measuring (discarded). Default false."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_save_baseline",description:'Benchmark a command and save results as the performance baseline for future comparisons. Default: 3 runs with warmup. Use "reset" to replace (not blend) an existing baseline.',input_schema:{type:"object",properties:{command:{type:"string",description:"Command to benchmark and save as baseline."},key:{type:"string",description:"Benchmark label. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs to measure. Default 3."},tags:{type:"array",items:{type:"string"},description:'Tags for this baseline (e.g. "build", "test").'},reset:{type:"boolean",description:"If true, replaces existing baseline entirely. Default false (blends)."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_status",description:'List all saved performance baselines with their metrics, spread, and age. Use when the user asks "quais baselines tenho?", "pit wall status", "mostra as metricas".',input_schema:{type:"object",properties:{},required:[]}},{name:"pitwall_remove_baseline",description:"Remove a saved performance baseline by its key.",input_schema:{type:"object",properties:{key:{type:"string",description:"The script key of the baseline to remove."}},required:["key"]}}],c5=[{name:"analyze_blast_radius",description:"Analyze the blast radius of changing a TypeScript file \u2014 shows all modules that import it (directly and transitively). "+'Use when the user says "blast radius", "impacto da mudanca", "quem depende de", "o que quebra se mudar".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file to analyze (relative or absolute)."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}},{name:"plan_refactor",description:'Generate a safe refactor order for updating dependents of a TypeScript file. Returns a numbered sequence: change the target first, then update dependents bottom-up. Use when the user says "plano de refatoracao", "ordem de atualizacao", "como refatorar seguro".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file being refactored."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}}],l5=[{name:"evaluate_architecture_tradeoffs",description:"Analyze trade-offs between architectural options using a weighted evaluation matrix. Returns an ADR (Architecture Decision Record) with recommendation. Default criteria: Maintainability (30%), Performance (25%), Learning Curve (20%), Infrastructure Cost (25%). Use when comparing technologies, frameworks, patterns, or infrastructure choices.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the decision, e.g., "Redis vs SQLite for session storage".'},background:{type:"string",description:"Context and background of the decision \u2014 why is this decision needed?"},constraints:{type:"array",items:{type:"string"},description:'Project constraints, e.g., "Must run on Kubernetes", "Budget < $100/mo".'},stakeholders:{type:"array",items:{type:"string"},description:'People/teams affected, e.g., "Backend Team", "DevOps".'},options:{type:"array",items:{type:"object",properties:{name:{type:"string",description:'Option name, e.g., "Redis".'},description:{type:"string",description:"Brief description of this option."},scores:{type:"object",description:"Scores for each criterion (1-5). Keys: maintainability, performance, learning_curve, infrastructure_cost."},pros:{type:"array",items:{type:"string"},description:"Advantages of this option."},cons:{type:"array",items:{type:"string"},description:"Disadvantages of this option."}},required:["name","description","scores","pros","cons"]},description:"List of options to compare (minimum 2)."},custom_criteria:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Criterion name."},weight:{type:"number",description:"Weight (0.0-1.0). Must sum to 1.0 across all criteria."},description:{type:"string",description:"What this criterion measures."}},required:["name","weight","description"]},description:"Optional custom criteria. If not provided, uses default criteria."}},required:["title","background","options"]}},{name:"correlate_incident",description:"Analyze an error or bug and search for similar past incidents, related decisions, and relevant materials. Returns correlation matches with suggested solutions and actions based on historical data. Use when debugging, troubleshooting, or investigating an error.",input_schema:{type:"object",properties:{description:{type:"string",description:"Description of the current error or bug."},stacktrace:{type:"string",description:"Optional stacktrace or error output for better matching."}},required:["description"]}},{name:"log_incident",description:"Log a resolved incident for future correlation. This feeds the Post-Mortem database. Use after resolving a bug to help accelerate future debugging.",input_schema:{type:"object",properties:{title:{type:"string",description:"Short title of the incident."},description:{type:"string",description:"Detailed description of what happened."},root_cause:{type:"string",description:"Root cause analysis."},solution:{type:"string",description:"How the incident was resolved."},stacktrace:{type:"string",description:"Optional stacktrace for better correlation."},related_decisions:{type:"array",items:{type:"string"},description:"IDs of related decisions from the Decision Log."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization, e.g., "memory-leak", "timeout", "auth".'}},required:["title","description","root_cause","solution"]}},{name:"list_tradeoff_analyses",description:"List past architecture trade-off analyses. Use to review previous decisions and their rationale.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Maximum number of results (default 10)."},query:{type:"string",description:"Optional search query to filter results."}},required:[]}},{name:"list_incidents",description:"List logged incidents from the Post-Mortem database. Use to review past issues and solutions.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Maximum number of results (default 10)."},query:{type:"string",description:"Optional search query to filter results."}},required:[]}},{name:"get_tradeoff_adr",description:"Get the full ADR (Architecture Decision Record) for a past trade-off analysis by ID. Returns the complete Markdown document.",input_schema:{type:"object",properties:{id:{type:"string",description:"ID of the trade-off analysis."}},required:["id"]}}],o5=[{name:"manage_news_feeds",description:'Manage RSS/Atom news feed sources. Actions: add (add custom feed), remove (remove custom feed), disable (disable a built-in feed), enable (re-enable a disabled built-in), list (show all feeds). Use when the user says "adiciona essa fonte", "remove o feed", "desativa o TechCrunch", "mostra as fontes".',input_schema:{type:"object",properties:{action:{type:"string",enum:["add","remove","disable","enable","list"],description:"Action to perform."},name:{type:"string",description:"Feed name (for add) or name/URL reference (for remove/disable/enable)."},url:{type:"string",description:"RSS/Atom feed URL (required for add)."},category:{type:"string",description:"Category for the feed (required for add). E.g. tech, finance, ai, devops."}},required:["action"]}}],i5=[{name:"archive_session",description:'Archive a conversation session. Archived sessions are preserved but removed from the active list. Use "all" as name to archive all sessions except the current one.',input_schema:{type:"object",properties:{name:{type:"string",description:'Session name to archive, or "all" to archive all except current.'}},required:["name"]}},{name:"unarchive_session",description:"Restore an archived session back to the active sessions list.",input_schema:{type:"object",properties:{name:{type:"string",description:"Archived session name to restore."}},required:["name"]}},{name:"list_archived_sessions",description:"List all archived conversation sessions with message count and last update.",input_schema:{type:"object",properties:{},required:[]}}],r5=[{name:"update_living_manual",description:"Silently update the living manual with a structured insight or best practice. The manual is stored at ~/.config/smolerclaw/materials/manual/ and persists across sessions. Use when you observe a pattern that could help the user work more efficiently, or when they ask to document a workflow. Categories: workflow, tool, shortcut, best_practice.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the manual entry (e.g. "Atalho para commits rapidos")'},content:{type:"string",description:"Full content in markdown format. Include steps, examples, and tips."},category:{type:"string",enum:["workflow","tool","shortcut","best_practice"],description:"Category. Default: best_practice."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization (e.g. "git", "automacao", "produtividade"). Optional.'}},required:["title","content"]}},{name:"explain_optimal_usage",description:'Generate an interactive tutorial explaining how to use smolerclaw more efficiently. Consults the living manual (via RAG or direct read) and recent insights to build a contextual guide. Use when the user asks "como usar melhor?", "dicas de uso", "tutorial", or seems to be using tools inefficiently.',input_schema:{type:"object",properties:{topic:{type:"string",description:'Optional topic to focus on (e.g. "workflows", "git", "tarefas"). If omitted, shows general tips.'}},required:[]}},{name:"trigger_self_reflection",description:"Manually trigger the self-reflection analysis. Analyzes recent actions to detect patterns, generate insights about repetitive tasks, underutilized tools, and inefficient patterns. Updates the living manual with findings. Use at end of session or when user asks for usage analysis.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_usage_insights",description:'Get recent insights generated by the meta-learning engine. Shows detected patterns, tips, and recommendations based on observed usage. Use when the user asks "o que aprendi?", "insights de uso", or wants to see optimization suggestions.',input_schema:{type:"object",properties:{count:{type:"number",description:"Number of recent insights to show. Default 5."}},required:[]}}];async function xJ($,Z,Y){switch($){case"open_application":return await Y$(Z.name,Z.argument);case"open_file_default":return await J8(Z.path);case"open_url_browser":return await Q$(Z.url);case"get_running_apps":return await X8();case"get_system_info":return await z$();case"get_calendar_events":return await l0();case"get_news":{let Q=Z.category;return await P1(Q?[Q]:void 0)}case"create_task":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.time,J=z?f$(z):void 0,X=y4(Q,J||void 0),K=J?` \u2014 lembrete: ${J.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${X.title}"${K} [${X.id}]`}case"complete_task":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=_4(Q);return z?`Concluida: "${z.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,z=Q1(Q);return n1(z)}case"schedule_job":{let{name:Q,time:z,message:J}=Z;if(!Q?.trim()||!z?.trim()||!J?.trim())return"Error: name, time, and message are required.";let X=r4(z);if(!X)return`Error: invalid time format "${z}". Use HH:MM.`;let K=Z.schedule_type||"once",G;if(Z.date_or_day){let U=Z.date_or_day;if(K==="weekly")G=a4(U)??void 0;else G=n4(U)??void 0}if(K==="once"&&!G){let U=new Date,[q,H]=X.split(":").map(Number),B=new Date(U);if(B.setHours(q,H,0,0),B<=U)B.setDate(B.getDate()+1);G=[String(B.getMonth()+1).padStart(2,"0"),String(B.getDate()).padStart(2,"0"),String(B.getFullYear())].join("/")}let V=await d4(Q,K,X,"toast",J,G);return`Agendamento criado: "${V.name}" [${V.id}] \u2014 ${V.scheduleType} \xE0s ${V.time}`}case"remove_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await c4(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,z=r2(Q);return n2(z)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=await l4(Q);return z?`Agendamento "${z.name}" ativado.`:`Agendamento nao encontrado: "${Q}"`}case"disable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=await o4(Q);return z?`Agendamento "${z.name}" desativado.`:`Agendamento nao encontrado: "${Q}"`}case"run_scheduled_job_now":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await i4(Q)}case"add_person":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let z=Z.group;if(!["equipe","familia","contato"].includes(z))return"Error: group must be equipe, familia, or contato.";let X=X5(Q,z,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${z}) [${X.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let z=z1(Q);if(!z)return`Pessoa nao encontrada: "${Q}"`;return U5(z)}case"list_people":{let Q=Z.group,z=K5(Q);return V5(z)}case"log_interaction":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let{type:z,summary:J}=Z;if(!J?.trim())return"Error: summary is required.";let X=Z.follow_up,K=X?RZ(X):void 0;if(!Hz(Q,z,J,K||void 0))return`Pessoa nao encontrada: "${Q}"`;let V=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${z} com ${Q}${V}`}case"delegate_to_person":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let z=Z.task;if(!z?.trim())return"Error: task is required.";let J=Z.due_date,X=J?RZ(J):void 0,K=G5(Q,z,X||void 0);if(!K)return`Pessoa nao encontrada: "${Q}"`;let G=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${z}"${G} [${K.id}]`}case"update_delegation_status":{let Q=Z.delegation_id;if(!Q?.trim())return"Error: delegation_id is required.";let z=Z.status,J=Wz(Q,z,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${z}`}case"get_people_dashboard":return Oz();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let z=Z.tags||[],J=x4(Q,z);return`Memo salvo${J.tags.length>0?` [${J.tags.map((K)=>"#"+K).join(" ")}]`:""} {${J.id}}`}case"search_memos":{let Q=Z.query;if(!Q?.trim())return a1(i2());let z=v4(Q);return a1(z)}case"record_transaction":{let{type:Q,amount:z,category:J,description:X}=Z;if(!Q||!z||!J||!X)return"Error: all fields required.";let K=s2(Q,z,J,X);if(!K.allowed)return`Error: ${K.blocked}`;let G=a2(Q,z,J,X);t2(Q,z,J);let V=G.type==="entrada"?"+":"-",U=e2(K);return`${V} R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description} [${G.id}]${U?`
396
+ `+U:""}`}case"financial_summary":return t4();case"log_decision":{let{title:Q,context:z,chosen:J}=Z;if(!Q||!z||!J)return"Error: title, context, and chosen are required.";let X=Zz(Q,z,J,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let Q=Z.query;if(!Q?.trim())return y$(Y5());return y$(s1(Q))}case"open_investigation":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.type;if(!["bug","feature","test","audit","incident"].includes(z))return"Error: type must be bug, feature, test, audit, or incident.";let X=h6(Q,z,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${X.title}" (${X.type}) {${X.id}}`}case"collect_evidence":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{source:z,label:J,content:X}=Z;if(!J?.trim()||!X?.trim())return"Error: label and content are required.";let K=g6(Q,z,J,X,Z.path);if(!K)return`Investigacao nao encontrada: "${Q}"`;return`Evidencia coletada: [${K.id}] ${K.source}: ${K.label}`}case"add_finding":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{severity:z,title:J,description:X}=Z;if(!J?.trim()||!X?.trim())return"Error: title and description are required.";let K=Z.evidence_ids||[],G=m6(Q,z,J,X,K);if(!G)return`Investigacao nao encontrada: "${Q}"`;return`Conclusao registrada: [${G.severity.toUpperCase()}] ${G.title} {${G.id}}`}case"close_investigation":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=Z.summary;if(!z?.trim())return"Error: summary is required.";let J=u6(Q,z,Z.recommendations);if(!J)return`Investigacao nao encontrada: "${Q}"`;return`Investigacao concluida: "${J.title}" \u2014 ${J.evidence.length} evidencias, ${J.findings.length} conclusoes`}case"investigation_status":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=p6(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return o6(z)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=l6(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return z}case"list_investigations":{let Q=Z.query;if(Q?.trim())return z5(c6(Q));let{status:z,type:J}=Z;return z5(d6(z,J))}case"draft_email":{let{to:Q,subject:z,body:J}=Z;if(!Q?.trim()||!z?.trim()||!J?.trim())return"Error: to, subject, and body are required.";let X={to:Q,subject:z,body:J,cc:Z.cc},K=g4(X),G=await h4(X);return`${K}
397
+
398
+ ${G}`}case"save_material":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.content;if(!z?.trim())return"Error: content is required.";let J=Z.category||"geral",X=Z.tags||[],K=W5(Q,z,J,X),G=K.tags.length>0?` [${K.tags.map((V)=>"#"+V).join(" ")}]`:"";return`Material salvo: "${K.title}" (${K.category})${G} {${K.id}}`}case"search_materials":{let Q=Z.query;if(!Q?.trim())return S1(v$());let z=x$(Q);return S1(z)}case"list_materials":{let Q=Z.category,z=Z.limit||30,J=v$(z,Q);return S1(J)}case"update_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z={};if(Z.title)z.title=Z.title;if(Z.content)z.content=Z.content;if(Z.category)z.category=Z.category;if(Z.tags)z.tags=Z.tags;let J=Rz(Q,z);if(!J)return`Material nao encontrado: "${Q}"`;return`Material atualizado: "${J.title}" (${J.category}) {${J.id}}`}case"delete_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";return B5(Q)?"Material removido.":`Material nao encontrado: "${Q}"`}case"execute_powershell_script":{let Q=Z.script;if(!Q?.trim())return"Error: script is required.";let z=EZ(Q);if(z.blocked)return`BLOCKED: ${z.reason}
399
+ Esse tipo de operacao nao e permitido.`;if(!z.safe&&z.reason);let J=await K8(Q),X=[];if(J.stdout.trim())X.push(`stdout:
400
+ ${J.stdout.trim()}`);if(J.stderr.trim())X.push(`stderr:
401
+ ${J.stderr.trim()}`);return X.push(`exit: ${J.exitCode} (${J.duration}ms)`),X.join(`
402
+
403
+ `)}case"analyze_screen_context":return await f5();case"read_clipboard_content":{let Q=await k5();switch(Q.type){case"text":return`Clipboard (texto):
404
+ ${Q.text}`;case"image":return Q.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${Q.text}`}}case"send_notification":{let{title:Q,message:z}=Z,J=await yJ(Q,z);if(J.success)return`Notifica\xE7\xE3o enviada: "${Q}"`;return`Erro ao enviar notifica\xE7\xE3o: ${J.error}`}case"manage_news_feeds":switch(Z.action){case"list":return f4();case"add":{let{name:z,url:J,category:X}=Z;if(!z?.trim())return"Error: name is required for add.";if(!J?.trim())return"Error: url is required for add.";if(!X?.trim())return"Error: category is required for add.";let K=I4(z,J,X);if(typeof K==="string")return K;return`Fonte adicionada: ${K.name} (${K.category}) \u2014 ${K.url}`}case"remove":{let z=Z.name;if(!z?.trim())return"Error: name or URL is required.";return S4(z)?`Fonte removida: ${z}`:`Fonte custom nao encontrada: "${z}"`}case"disable":{let z=Z.name;if(!z?.trim())return"Error: name or URL is required.";return w4(z)?`Fonte desativada: ${z}`:`Fonte built-in nao encontrada ou ja desativada: "${z}"`}case"enable":{let z=Z.name;if(!z?.trim())return"Error: name or URL is required.";return k4(z)?`Fonte reativada: ${z}`:`Fonte nao encontrada ou nao esta desativada: "${z}"`}default:return"Error: action must be add, remove, disable, enable, or list."}case"set_active_project":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";if(Q==="auto"){let J=D5(process.cwd());if(!J)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return m$(J.id),`Projeto ativo: "${J.name}" (${J.path}) \u2014 auto-detectado [${J.id}]`}let z=m$(Q);if(!z)return`Projeto nao encontrado: "${Q}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${z.name}" (${z.path}) [${z.id}]`}case"report_work_progress":{let Q=Z.project||"",z=Z.period||"today",J=Z.lang||"pt",X=Z.save_to_file,K=Q;if(!K){let V=k1();if(!V)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=V.id}let G=await F5(K,z,J);if(!G)return`Projeto nao encontrado: "${K}"`;if(X)return dH(X,G.markdown,"utf-8"),`Relatorio salvo em: ${X}
405
+
406
+ ${G.markdown}`;return G.markdown}case"manage_work_session":{let Q=Z.action,z=Z.notes||"",J=k1();if(!J)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=C5(J.id,z);if(!X)return"Erro ao iniciar sessao.";return`Sessao iniciada para "${J.name}" as ${new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}. [${X.id}]`}case"stop":{let X=f1(J.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=E5(X.id,z);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${J.name}".`}case"status":{let X=f1(J.id);if(!X)return`Nenhuma sessao aberta para "${J.name}".`;let K=new Date(X.startedAt),G=Math.round((Date.now()-K.getTime())/60000);return`Sessao aberta: "${J.name}" \u2014 ${G} minutos (desde ${K.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let z=Z.path;if(!z?.trim())return"Error: path is required.";let J=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],G=$Z(Q,z,J,K,X);return`Projeto registrado: "${G.name}" (${G.path}) [${G.id}]`}case"list_projects":{let Q=Z.active_only||!1;return L5(g$(Q))}case"fetch_opportunities":{let{status:Q,tech:z}=Z,J=R5(Q,z);return A5(J)}case"add_opportunity":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.description;if(!z?.trim())return"Error: description is required.";let J=Z.source;if(!J?.trim())return"Error: source is required.";let X=Z.tech_required||[],K=Z.priority||"media",G=Z.deadline||null,V=fz(Q,z,J,X,K,G);return`Oportunidade registrada: "${V.title}" (${V.priority}) [${V.id}]`}case"update_opportunity_status":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=Z.status,J=bz(Q,z);if(!J)return`Oportunidade nao encontrada: "${Q}"`;return`Oportunidade atualizada: "${J.title}" -> ${z}`}case"pitwall_benchmark":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let z=Z.key,J=Math.min(Math.max(Z.iterations||1,1),10),X=Z.warmup||!1,K=Z.cwd,G=await JZ(Q,{scriptKey:z,cwd:K,iterations:J,warmup:X});if(G.exitCode!==0){let V=KZ(G);return`AVISO: Comando terminou com exit code ${G.exitCode}. Metricas podem nao ser confiaveis.
407
+
408
+ ${V.markdown}`}return KZ(G).markdown}case"pitwall_save_baseline":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let z=Z.key,J=Math.min(Math.max(Z.iterations||3,1),10),X=Z.tags||[],K=Z.reset||!1,G=Z.cwd,V=await JZ(Q,{scriptKey:z,cwd:G,iterations:J,warmup:!0});if(V.exitCode!==0)return`Error: Comando falhou (exit code ${V.exitCode}). Corrija o comando antes de salvar baseline.
409
+ `+(V.stderr?`Stderr: ${V.stderr.slice(0,300)}`:"");let U=K?dz(V,X):uz(V,X),q=U.metrics.durationNs/1e6;return`Baseline salvo: "${U.scriptKey}" (${U.runs} run${U.runs>1?"s":""})
410
+ Duracao: ${q.toFixed(2)}ms
411
+ Memoria: ${(U.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
412
+ CPU (user): ${(U.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return lz(pz());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return XZ(Q)?`Baseline removido: "${Q}"`:`Baseline nao encontrado: "${Q}"`}case"analyze_blast_radius":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let z=b5(Z.project_dir||process.cwd()),J=b5(z,Q);if(!J.startsWith(z+_J))return"Error: file must be inside project_dir.";try{let X=VZ(z),K=UZ(X,J);return sz(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"plan_refactor":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let z=b5(Z.project_dir||process.cwd()),J=b5(z,Q);if(!J.startsWith(z+_J))return"Error: file must be inside project_dir.";try{let X=VZ(z),K=az(X,J);return ez(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"archive_session":{if(!Y)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";if(Q==="all"){let z=Y.archiveAll();return z.length>0?`Arquivadas ${z.length} sessoes: ${z.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return Y.archive(Q)?`Sessao arquivada: "${Q}"`:`Falha ao arquivar "${Q}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!Y)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";return Y.unarchive(Q)?`Sessao restaurada: "${Q}"`:`Sessao arquivada nao encontrada: "${Q}"`}case"list_archived_sessions":{if(!Y)return"Error: session manager not initialized.";let Q=Y.listArchived();if(Q.length===0)return"Nenhuma sessao arquivada.";let z=Q.map((J)=>{let X=Y.getArchivedInfo(J),K=X?new Date(X.updated).toLocaleDateString("pt-BR"):"",G=X?`${X.messageCount} msgs`:"";return` ${J.padEnd(20)} ${G.padEnd(10)} ${K}`});return`Sessoes arquivadas (${Q.length}):
413
+ ${z.join(`
414
+ `)}`}case"evaluate_architecture_tradeoffs":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.background;if(!z?.trim())return"Error: background is required.";let J=Z.options;if(!J||J.length<2)return"Error: at least 2 options are required.";let X={title:Q.trim(),background:z.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},K=J.map((q)=>({name:q.name.trim(),description:q.description.trim(),scores:q.scores,pros:q.pros||[],cons:q.cons||[]})),G=Z.custom_criteria,V=G&&G.length>0?G:HZ;return XJ(X,K,V).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let z=Z.stacktrace;return KJ(Q,z).summary}case"log_incident":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.description;if(!z?.trim())return"Error: description is required.";let J=Z.root_cause;if(!J?.trim())return"Error: root_cause is required.";let X=Z.solution;if(!X?.trim())return"Error: solution is required.";let K=GJ(Q,z,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
406
415
  Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
407
- Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,J=Z.query,z=J?FQ(J).slice(0,Q):OQ(Q);return EQ(z)}case"list_incidents":{let Q=Z.limit||10,J=Z.query,z=J?CQ(J).slice(0,Q):NQ(Q);return LQ(z)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let J=RQ(Q);if(!J)return`Trade-off nao encontrado: "${Q}"`;return J.adr}case"update_living_manual":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.content;if(!J?.trim())return"Error: content is required.";let z=Z.category||"best_practice",X=Z.tags||[],K=await yQ(Q,J,z,X);if(!K.success)return"Falha ao atualizar o manual. Verifique se o docs-engine foi inicializado.";return`Manual atualizado: "${Q}" (${z})
408
- Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return _Q(Q)}case"trigger_self_reflection":{let Q=await x1();return fQ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),J=bQ(Q);return hQ(J)}default:return null}}g();var x5=[{name:"vault_status",description:'Show the integrity status of all data files: checksum verification, sizes, last backup time. Use when the user asks about data health, backup status, or says "esta tudo salvo?", "meus dados estao seguros?".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_backup",description:'Perform a manual backup of all data to the shadow backup repository. Use when the user says "faz backup", "salva tudo", "sync".',input_schema:{type:"object",properties:{message:{type:"string",description:"Optional commit message for the backup."}},required:[]}},{name:"sync_cloud_context",description:'Push the backup to a configured remote repository (if set up). Use when the user says "manda pro cloud", "sync remoto", "push backup".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_init_backup",description:"Initialize the shadow backup system (creates a local git repo for data versioning). Run once to enable automatic backups.",input_schema:{type:"object",properties:{},required:[]}}];async function cQ($,Z){switch($){case"vault_status":{if(!c1())return"Vault nao inicializado.";return T4(A4())}case"vault_backup":{if(!c1())return"Vault nao inicializado.";let Y=Z.message||void 0;return await U1(Y)}case"sync_cloud_context":{if(!c1())return"Vault nao inicializado.";return await S4()}case"vault_init_backup":{if(!c1())return"Vault nao inicializado.";return await I4()}default:return null}}g();import{existsSync as X1,mkdirSync as GU,readFileSync as v1,readdirSync as qU}from"fs";import{join as z1}from"path";import{createHash as UU}from"crypto";var iQ=1,n9=400,HU=80,lQ=1.5,oQ=0.75,WU=10,BU=new Set(["a","o","e","de","do","da","em","um","uma","para","com","nao","que","por","se","na","no","os","as","ao","ou","foi","ser","tem","seu","sua","mais","como","mas","dos","das","esse","essa","este","esta","isso","isto","ele","ela","nos","ja","ate","muito","tambem","entre","quando","sobre","mesmo","depois","sem","vai","ainda","pode","aqui","so","the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","above","below","between","out","off","over","under","again","further","then","once","here","there","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","because","but","and","or","if","while","this","that","these","those","it","its"]),Y4="",v5="",Y$=[],J0={},z0=0,X0={},f5=!1,s9=()=>z1(v5,"rag-index.json");function aQ($){if(Y4=$,v5=z1($,"rag"),!X1(v5))GU(v5,{recursive:!0});EU(),f5=!0}function h5(){return f5}function g5(){return{chunks:Y$.length,sources:Object.keys(X0).length,builtAt:Y$.length>0?LU()?.builtAt??null:null}}function m5(){if(!f5)throw Error("Memory not initialized. Call initMemory() first.");let $=OU(),Z=0,Y=0,Q={},J=new Set;for(let[X,K]of Object.entries($)){let V=jU(K);if(Q[X]=V,X0[X]!==V)J.add(X)}let z=Object.keys(X0).filter((X)=>!(X in $));if(J.size===0&&z.length===0)return{indexed:0,skipped:Object.keys($).length,total:Y$.length};Y$=Y$.filter((X)=>{let K=`${X.source}:${X.sourceId}`;return!J.has(K)&&!z.includes(K)});for(let X of J){let K=$[X],V=X.indexOf(":");if(V===-1)continue;let G=X.slice(0,V),q=X.slice(V+1);if(!["memo","material","session","decision"].includes(G))continue;let W=DU(G,q,K),B=NU(K,G,q,W);Y$=[...Y$,...B],Z++}return Y=Object.keys($).length-Z,FU(),X0=Q,RU(),{indexed:Z,skipped:Y,total:Y$.length}}function u5($,Z=3){if(Y$.length===0)return[];let Y=r9($);if(Y.length===0)return[];return Y$.map((J)=>{let z=MU(Y,J),X=CU(Y,J),K=0.6*z+0.4*X;return{chunk:J,score:K}}).filter((J)=>J.score>0).sort((J,z)=>z.score-J.score).slice(0,Math.min(Z,WU))}function p5($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let J=PU(Y.chunk.source),z=(Y.score*100).toFixed(1),X=Y.chunk.content.length>300?Y.chunk.content.slice(0,300).replace(/\n/g," ")+"...":Y.chunk.content.replace(/\n/g," ");return`[${Q+1}] ${J}: ${Y.chunk.title} (relevancia: ${z}%)
416
+ Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,z=Z.query,J=z?HJ(z).slice(0,Q):qJ(Q);return BJ(J)}case"list_incidents":{let Q=Z.limit||10,z=Z.query,J=z?VJ(z).slice(0,Q):UJ(Q);return OJ(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=WJ(Q);if(!z)return`Trade-off nao encontrado: "${Q}"`;return z.adr}case"update_living_manual":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.content;if(!z?.trim())return"Error: content is required.";let J=Z.category||"best_practice",X=Z.tags||[],K=await DJ(Q,z,J,X);if(!K.success)return"Falha ao atualizar o manual. Verifique se o docs-engine foi inicializado.";return`Manual atualizado: "${Q}" (${J})
417
+ Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return TJ(Q)}case"trigger_self_reflection":{let Q=await p$();return wJ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),z=PJ(Q);return kJ(z)}default:return null}}l();var n5=[{name:"vault_status",description:'Show the integrity status of all data files: checksum verification, sizes, last backup time. Use when the user asks about data health, backup status, or says "esta tudo salvo?", "meus dados estao seguros?".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_backup",description:'Perform a manual backup of all data to the shadow backup repository. Use when the user says "faz backup", "salva tudo", "sync".',input_schema:{type:"object",properties:{message:{type:"string",description:"Optional commit message for the backup."}},required:[]}},{name:"sync_cloud_context",description:'Push the backup to a configured remote repository (if set up). Use when the user says "manda pro cloud", "sync remoto", "push backup".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_init_backup",description:"Initialize the shadow backup system (creates a local git repo for data versioning). Run once to enable automatic backups.",input_schema:{type:"object",properties:{},required:[]}}];async function vJ($,Z){switch($){case"vault_status":{if(!e$())return"Vault nao inicializado.";return d8(p8())}case"vault_backup":{if(!e$())return"Vault nao inicializado.";let Y=Z.message||void 0;return await O$(Y)}case"sync_cloud_context":{if(!e$())return"Vault nao inicializado.";return await l8()}case"vault_init_backup":{if(!e$())return"Vault nao inicializado.";return await c8()}default:return null}}l();import{existsSync as G$,mkdirSync as cH,readFileSync as d$,readdirSync as lH}from"fs";import{join as K$}from"path";import{createHash as oH}from"crypto";var mJ=1,FZ=400,iH=80,hJ=1.5,gJ=0.75,rH=10,nH=new Set(["a","o","e","de","do","da","em","um","uma","para","com","nao","que","por","se","na","no","os","as","ao","ou","foi","ser","tem","seu","sua","mais","como","mas","dos","das","esse","essa","este","esta","isso","isto","ele","ela","nos","ja","ate","muito","tambem","entre","quando","sobre","mesmo","depois","sem","vai","ainda","pode","aqui","so","the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","above","below","between","out","off","over","under","again","further","then","once","here","there","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","because","but","and","or","if","while","this","that","these","those","it","its"]),U8="",a5="",K0=[],V1={},U1=0,q1={},s5=!1,jZ=()=>K$(a5,"rag-index.json");function uJ($){if(U8=$,a5=K$($,"rag"),!G$(a5))cH(a5,{recursive:!0});YW(),s5=!0}function t5(){return s5}function e5(){return{chunks:K0.length,sources:Object.keys(q1).length,builtAt:K0.length>0?QW()?.builtAt??null:null}}function $7(){if(!s5)throw Error("Memory not initialized. Call initMemory() first.");let $=eH(),Z=0,Y=0,Q={},z=new Set;for(let[X,K]of Object.entries($)){let G=zW(K);if(Q[X]=G,q1[X]!==G)z.add(X)}let J=Object.keys(q1).filter((X)=>!(X in $));if(z.size===0&&J.length===0)return{indexed:0,skipped:Object.keys($).length,total:K0.length};K0=K0.filter((X)=>{let K=`${X.source}:${X.sourceId}`;return!z.has(K)&&!J.includes(K)});for(let X of z){let K=$[X],G=X.indexOf(":");if(G===-1)continue;let V=X.slice(0,G),U=X.slice(G+1);if(!["memo","material","session","decision"].includes(V))continue;let H=JW(V,U,K),B=tH(K,V,U,H);K0=[...K0,...B],Z++}return Y=Object.keys($).length-Z,$W(),q1=Q,ZW(),{indexed:Z,skipped:Y,total:K0.length}}function Z7($,Z=3){if(K0.length===0)return[];let Y=LZ($);if(Y.length===0)return[];return K0.map((z)=>{let J=aH(Y,z),X=sH(Y,z),K=0.6*J+0.4*X;return{chunk:z,score:K}}).filter((z)=>z.score>0).sort((z,J)=>J.score-z.score).slice(0,Math.min(Z,rH))}function Y7($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let z=XW(Y.chunk.source),J=(Y.score*100).toFixed(1),X=Y.chunk.content.length>300?Y.chunk.content.slice(0,300).replace(/\n/g," ")+"...":Y.chunk.content.replace(/\n/g," ");return`[${Q+1}] ${z}: ${Y.chunk.title} (relevancia: ${J}%)
409
418
  ${X}`});return`Resultados da memoria (${$.length}):
410
419
 
411
420
  ${Z.join(`
412
421
 
413
- `)}`}function MU($,Z){let Y=Z.tokens.length;if(Y===0||z0===0)return 0;let Q=new Map;for(let z of Z.tokens)Q.set(z,(Q.get(z)??0)+1);let J=0;for(let z of $){let X=Q.get(z)??0;if(X===0)continue;let K=J0[z]??0;if(K===0)continue;let V=X*(lQ+1),G=X+lQ*(1-oQ+oQ*(Y/z0));J+=K*(V/G)}return J}function CU($,Z){let Y=new Map;for(let G of $)Y.set(G,(Y.get(G)??0)+1);let Q=new Map;for(let G of Z.tokens)Q.set(G,(Q.get(G)??0)+1);let J=new Set([...$,...Z.tokens]),z=0,X=0,K=0;for(let G of J){let q=J0[G]??0,U=(Y.get(G)??0)*q,W=(Q.get(G)??0)*q;z+=U*W,X+=U*U,K+=W*W}let V=Math.sqrt(X)*Math.sqrt(K);return V>0?z/V:0}function r9($){return $.toLowerCase().replace(/[^\w\s\u00E1\u00E9\u00ED\u00F3\u00FA\u00E2\u00EA\u00EE\u00F4\u00FB\u00E3\u00F5\u00E0\u00E8\u00EC\u00F2\u00F9\u00E4\u00EB\u00EF\u00F6\u00FC\u00E7]/g," ").split(/\s+/).filter((Z)=>Z.length>2&&!BU.has(Z))}function NU($,Z,Y,Q){let J=$.trim();if(J.length===0)return[];if(J.length<=n9)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:J,tokens:r9(J)}];let z=[],X=0,K=0;while(X<J.length){let V=Math.min(X+n9,J.length),G=J.slice(X,V);z.push({id:`${Z}:${Y}:${K}`,source:Z,sourceId:Y,title:Q,content:G,tokens:r9(G)}),X+=n9-HU,K++}return z}function OU(){let $={},Z=z1(Y4,"memos.json");if(X1(Z))try{let z=JSON.parse(v1(Z,"utf-8"));if(!Array.isArray(z))throw Error("not an array");for(let X of z){if(!X||typeof X!=="object")continue;let K=X;if(typeof K.id!=="string"||typeof K.content!=="string")continue;let V=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`memo:${K.id}`]=`${K.content}${V}`}}catch{}let Y=z1(Y4,"materials.json");if(X1(Y))try{let z=JSON.parse(v1(Y,"utf-8"));if(!Array.isArray(z))throw Error("not an array");for(let X of z){if(!X||typeof X!=="object")continue;let K=X;if(typeof K.id!=="string"||typeof K.title!=="string"||typeof K.content!=="string")continue;let V=typeof K.category==="string"?K.category:"geral",G=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`material:${K.id}`]=`${K.title}
414
- ${V}
415
- ${K.content}${G}`}}catch{}let Q=z1(Y4,"decisions.json");if(X1(Q))try{let z=JSON.parse(v1(Q,"utf-8"));if(!Array.isArray(z))throw Error("not an array");for(let X of z){if(!X||typeof X!=="object")continue;let K=X;if(typeof K.id!=="string"||typeof K.title!=="string"||typeof K.context!=="string"||typeof K.chosen!=="string")continue;let V=[K.title,K.context,`Escolha: ${K.chosen}`];if(typeof K.alternatives==="string")V.push(`Alternativas: ${K.alternatives}`);if(Array.isArray(K.tags)&&K.tags.length>0)V.push(`[${K.tags.join(", ")}]`);$[`decision:${K.id}`]=V.join(`
416
- `)}}catch{}let J=z1(Y4,"sessions");if(X1(J))try{let z=qU(J,{withFileTypes:!0}).filter((X)=>X.isFile()&&X.name.endsWith(".json")&&!X.name.startsWith(".")).map((X)=>X.name);for(let X of z){let K=z1(J,X);try{let V=JSON.parse(v1(K,"utf-8"));if(!V||typeof V!=="object"||!Array.isArray(V.messages))continue;let G=V.messages.filter((q)=>{if(!q||typeof q!=="object")return!1;let U=q;return U.role==="assistant"&&typeof U.content==="string"&&U.content.length>50}).map((q)=>q.content).join(`
422
+ `)}`}function aH($,Z){let Y=Z.tokens.length;if(Y===0||U1===0)return 0;let Q=new Map;for(let J of Z.tokens)Q.set(J,(Q.get(J)??0)+1);let z=0;for(let J of $){let X=Q.get(J)??0;if(X===0)continue;let K=V1[J]??0;if(K===0)continue;let G=X*(hJ+1),V=X+hJ*(1-gJ+gJ*(Y/U1));z+=K*(G/V)}return z}function sH($,Z){let Y=new Map;for(let V of $)Y.set(V,(Y.get(V)??0)+1);let Q=new Map;for(let V of Z.tokens)Q.set(V,(Q.get(V)??0)+1);let z=new Set([...$,...Z.tokens]),J=0,X=0,K=0;for(let V of z){let U=V1[V]??0,q=(Y.get(V)??0)*U,H=(Q.get(V)??0)*U;J+=q*H,X+=q*q,K+=H*H}let G=Math.sqrt(X)*Math.sqrt(K);return G>0?J/G:0}function LZ($){return $.toLowerCase().replace(/[^\w\s\u00E1\u00E9\u00ED\u00F3\u00FA\u00E2\u00EA\u00EE\u00F4\u00FB\u00E3\u00F5\u00E0\u00E8\u00EC\u00F2\u00F9\u00E4\u00EB\u00EF\u00F6\u00FC\u00E7]/g," ").split(/\s+/).filter((Z)=>Z.length>2&&!nH.has(Z))}function tH($,Z,Y,Q){let z=$.trim();if(z.length===0)return[];if(z.length<=FZ)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:z,tokens:LZ(z)}];let J=[],X=0,K=0;while(X<z.length){let G=Math.min(X+FZ,z.length),V=z.slice(X,G);J.push({id:`${Z}:${Y}:${K}`,source:Z,sourceId:Y,title:Q,content:V,tokens:LZ(V)}),X+=FZ-iH,K++}return J}function eH(){let $={},Z=K$(U8,"memos.json");if(G$(Z))try{let J=JSON.parse(d$(Z,"utf-8"));if(!Array.isArray(J))throw Error("not an array");for(let X of J){if(!X||typeof X!=="object")continue;let K=X;if(typeof K.id!=="string"||typeof K.content!=="string")continue;let G=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`memo:${K.id}`]=`${K.content}${G}`}}catch{}let Y=K$(U8,"materials.json");if(G$(Y))try{let J=JSON.parse(d$(Y,"utf-8"));if(!Array.isArray(J))throw Error("not an array");for(let X of J){if(!X||typeof X!=="object")continue;let K=X;if(typeof K.id!=="string"||typeof K.title!=="string"||typeof K.content!=="string")continue;let G=typeof K.category==="string"?K.category:"geral",V=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`material:${K.id}`]=`${K.title}
423
+ ${G}
424
+ ${K.content}${V}`}}catch{}let Q=K$(U8,"decisions.json");if(G$(Q))try{let J=JSON.parse(d$(Q,"utf-8"));if(!Array.isArray(J))throw Error("not an array");for(let X of J){if(!X||typeof X!=="object")continue;let K=X;if(typeof K.id!=="string"||typeof K.title!=="string"||typeof K.context!=="string"||typeof K.chosen!=="string")continue;let G=[K.title,K.context,`Escolha: ${K.chosen}`];if(typeof K.alternatives==="string")G.push(`Alternativas: ${K.alternatives}`);if(Array.isArray(K.tags)&&K.tags.length>0)G.push(`[${K.tags.join(", ")}]`);$[`decision:${K.id}`]=G.join(`
425
+ `)}}catch{}let z=K$(U8,"sessions");if(G$(z))try{let J=lH(z,{withFileTypes:!0}).filter((X)=>X.isFile()&&X.name.endsWith(".json")&&!X.name.startsWith(".")).map((X)=>X.name);for(let X of J){let K=K$(z,X);try{let G=JSON.parse(d$(K,"utf-8"));if(!G||typeof G!=="object"||!Array.isArray(G.messages))continue;let V=G.messages.filter((U)=>{if(!U||typeof U!=="object")return!1;let q=U;return q.role==="assistant"&&typeof q.content==="string"&&q.content.length>50}).map((U)=>U.content).join(`
417
426
  ---
418
- `);if(G.length>0)$[`session:${V.id}`]=G}catch{}}}catch{}return $}function FU(){let $=Y$.length;if($===0){J0={},z0=0;return}let Z=new Map,Y=0;for(let J of Y$){let z=new Set;for(let X of J.tokens)if(!z.has(X))Z.set(X,(Z.get(X)??0)+1),z.add(X);Y+=J.tokens.length}z0=Y/$;let Q={};for(let[J,z]of Z)Q[J]=Math.log(($-z+0.5)/(z+0.5)+1);J0=Q}function RU(){if(!f5)return;let $={chunks:Y$,idf:J0,avgDocLength:z0,sourceHashes:X0,builtAt:new Date().toISOString(),version:iQ};P(s9(),JSON.stringify($))}function EU(){let $=s9();if(!X1($)){Y$=[],J0={},z0=0,X0={};return}try{let Z=JSON.parse(v1($,"utf-8"));if(Z.version!==iQ){Y$=[],J0={},z0=0,X0={};return}Y$=Z.chunks,J0=Z.idf,z0=Z.avgDocLength,X0=Z.sourceHashes}catch{Y$=[],J0={},z0=0,X0={}}}function LU(){let $=s9();if(!X1($))return null;try{return{builtAt:JSON.parse(v1($,"utf-8")).builtAt}}catch{return null}}function jU($){return UU("sha256").update($).digest("hex").slice(0,16)}function DU($,Z,Y){switch($){case"material":{let Q=Y.split(`
427
+ `);if(V.length>0)$[`session:${G.id}`]=V}catch{}}}catch{}return $}function $W(){let $=K0.length;if($===0){V1={},U1=0;return}let Z=new Map,Y=0;for(let z of K0){let J=new Set;for(let X of z.tokens)if(!J.has(X))Z.set(X,(Z.get(X)??0)+1),J.add(X);Y+=z.tokens.length}U1=Y/$;let Q={};for(let[z,J]of Z)Q[z]=Math.log(($-J+0.5)/(J+0.5)+1);V1=Q}function ZW(){if(!s5)return;let $={chunks:K0,idf:V1,avgDocLength:U1,sourceHashes:q1,builtAt:new Date().toISOString(),version:mJ};P(jZ(),JSON.stringify($))}function YW(){let $=jZ();if(!G$($)){K0=[],V1={},U1=0,q1={};return}try{let Z=JSON.parse(d$($,"utf-8"));if(Z.version!==mJ){K0=[],V1={},U1=0,q1={};return}K0=Z.chunks,V1=Z.idf,U1=Z.avgDocLength,q1=Z.sourceHashes}catch{K0=[],V1={},U1=0,q1={}}}function QW(){let $=jZ();if(!G$($))return null;try{return{builtAt:JSON.parse(d$($,"utf-8")).builtAt}}catch{return null}}function zW($){return oH("sha256").update($).digest("hex").slice(0,16)}function JW($,Z,Y){switch($){case"material":{let Q=Y.split(`
419
428
  `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"memo":return Y.slice(0,60).replace(/\n/g," ")+(Y.length>60?"...":"");case"decision":{let Q=Y.split(`
420
- `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function PU($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var d5=[{name:"recall_memory",description:'Search the local RAG memory index for relevant information from memos, materials, decisions, and past sessions. Use when the user asks "o que eu sei sobre...", "lembra de...", "busca na memoria...", or needs context from past interactions. Returns the top 3 most relevant text fragments.',input_schema:{type:"object",properties:{query:{type:"string",description:"Natural language query to search the memory index"},top_k:{type:"number",description:"Number of results to return. Default 3, max 10."}},required:["query"]}},{name:"index_memory",description:"Build or update the local RAG memory index. Indexes memos, materials, decisions, and sessions. "+'Incremental \u2014 only re-indexes changed data. Use when the user says "atualiza a memoria", "reindexa", or after adding many new items.',input_schema:{type:"object",properties:{},required:[]}},{name:"memory_status",description:"Show stats about the local RAG memory index: number of indexed chunks, sources, and last build time.",input_schema:{type:"object",properties:{},required:[]}}];function nQ($,Z){switch($){case"recall_memory":{if(!h5())return"Error: memory not initialized. Run /indexar first.";let Y=Z.query;if(!Y?.trim())return"Error: query is required.";let Q=Math.min(Math.max(Z.top_k||3,1),10),J=u5(Y,Q);return p5(J)}case"index_memory":{if(!h5())return"Error: memory not initialized.";let Y=m5();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!h5())return"Memory: nao inicializada.";let Y=g5(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
429
+ `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function XW($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var Q7=[{name:"recall_memory",description:'Search the local RAG memory index for relevant information from memos, materials, decisions, and past sessions. Use when the user asks "o que eu sei sobre...", "lembra de...", "busca na memoria...", or needs context from past interactions. Returns the top 3 most relevant text fragments.',input_schema:{type:"object",properties:{query:{type:"string",description:"Natural language query to search the memory index"},top_k:{type:"number",description:"Number of results to return. Default 3, max 10."}},required:["query"]}},{name:"index_memory",description:"Build or update the local RAG memory index. Indexes memos, materials, decisions, and sessions. "+'Incremental \u2014 only re-indexes changed data. Use when the user says "atualiza a memoria", "reindexa", or after adding many new items.',input_schema:{type:"object",properties:{},required:[]}},{name:"memory_status",description:"Show stats about the local RAG memory index: number of indexed chunks, sources, and last build time.",input_schema:{type:"object",properties:{},required:[]}}];function pJ($,Z){switch($){case"recall_memory":{if(!t5())return"Error: memory not initialized. Run /indexar first.";let Y=Z.query;if(!Y?.trim())return"Error: query is required.";let Q=Math.min(Math.max(Z.top_k||3,1),10),z=Z7(Y,Q);return Y7(z)}case"index_memory":{if(!t5())return"Error: memory not initialized.";let Y=$7();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!t5())return"Memory: nao inicializada.";let Y=e5(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
421
430
  Chunks: ${Y.chunks}
422
431
  Fontes: ${Y.sources}
423
- Ultima indexacao: ${Q}`}default:return null}}g();d$();import{join as AU}from"path";import{createHash as TU}from"crypto";var IU={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},Q4={architectural:["refactor","redesign","migrate","architecture","restructure","microservice","monolith","database schema","api design"],complex:["implement feature","add functionality","integrate","authentication","authorization","security","performance","optimize","cache"],moderate:["update","modify","change","fix bug","add endpoint","create component","add validation","error handling"],simple:["rename","move","delete unused","add comment","format","lint"],trivial:["typo","spacing","import order","semicolon"]},SU=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],wU="",D=null,t9=[],eQ={...IU},$J=!1,rQ=null,kU=()=>AU(wU,"plan-history.json");function K0(){return $J}function e9($,Z){let Y=$.toLowerCase(),Q=bU(Y),J=Z?.files||[],z=Z?.modules||[],X=[],K=[];for(let q of J)for(let U of SU)if(U.test(q))X.push(`Modifying sensitive file: ${q}`);if(J.length>3)X.push(`Affects ${J.length} files \u2014 higher coordination risk`);if(z.length>1)X.push(`Spans ${z.length} modules \u2014 may have cascading effects`);if(Y.includes("api"))K.push("API contract may need versioning consideration");if(Y.includes("database")||Y.includes("schema"))K.push("Database changes may require migration");if(Y.includes("auth")||Y.includes("security"))K.push("Security changes require thorough review");let V=eQ.requireApprovalFor.includes(Q),G=V?`Task classified as "${Q}" \u2014 requires explicit approval`:`Task classified as "${Q}" \u2014 can proceed with auto-approval`;return{complexity:Q,filesAffected:J,modulesAffected:z,risks:X,assumptions:K,requiresApproval:V,reason:G}}function bU($){for(let Z of Q4.architectural)if($.includes(Z))return"architectural";for(let Z of Q4.complex)if($.includes(Z))return"complex";for(let Z of Q4.moderate)if($.includes(Z))return"moderate";for(let Z of Q4.simple)if($.includes(Z))return"simple";for(let Z of Q4.trivial)if($.includes(Z))return"trivial";return"moderate"}function ZJ($,Z,Y){let Q=e9($),J={id:tQ(),objective:$,strategy:Z.map((z,X)=>({...z,id:tQ(),order:X+1,status:"pending"})),assumptions:[...Y?.assumptions||[],...Q.assumptions],risks:[...Y?.risks||[],...Q.risks],status:"draft",complexity:Q.complexity,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return D=J,H0().emit("planning:started",{planId:J.id,objective:$,timestamp:Date.now()}),J}async function YJ(){if(!D)return{success:!1,plan:null,message:"No active plan to submit"};if(D.status!=="draft")return{success:!1,plan:D,message:`Plan already in status: ${D.status}`};if(D={...D,status:"pending_approval",updatedAt:new Date().toISOString()},eQ.autoApproveComplexity.includes(D.complexity))return sQ("Auto-approved based on complexity classification");if(rQ)if(await rQ(D))return sQ("Approved by user");else return yU("Rejected by user");return{success:!0,plan:D,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function sQ($){if(!D)return{success:!1,plan:null,message:"No active plan to approve"};if(D.status!=="pending_approval"&&D.status!=="draft")return{success:!1,plan:D,message:`Cannot approve plan in status: ${D.status}`};return D={...D,status:"approved",approvedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),userFeedback:$},H0().emit("planning:approved",{planId:D.id,feedback:$,timestamp:Date.now()}),{success:!0,plan:D,message:"Plan approved \u2014 execution may proceed"}}function yU($){if(!D)return{success:!1,plan:null,message:"No active plan to reject"};return D={...D,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},H0().emit("planning:rejected",{planId:D.id,feedback:$,timestamp:Date.now()}),KJ(D),D=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function QJ(){if(!D)return{allowed:!0,reason:"No plan required \u2014 trivial operation"};if(D.status==="approved"||D.status==="executing")return{allowed:!0,reason:"Plan approved \u2014 execution permitted"};if(D.status==="draft"||D.status==="pending_approval")return{allowed:!1,reason:`Execution blocked \u2014 plan awaiting approval (status: ${D.status})`};return{allowed:!1,reason:`Execution blocked \u2014 plan status: ${D.status}`}}function JJ($,Z){if(!D)return{success:!1,message:"No active plan"};let Y=D.strategy.findIndex((K)=>K.id===$);if(Y===-1)return{success:!1,message:`Step not found: ${$}`};let Q=D.strategy.map((K,V)=>V===Y?{...K,status:"completed",result:Z}:K);D={...D,strategy:Q,updatedAt:new Date().toISOString()},H0().emit("planning:step_completed",{planId:D.id,stepId:$,result:Z,timestamp:Date.now()});let J=D.strategy.find((K)=>K.status==="pending"),z=D.strategy[Y].action;if(D.strategy.every((K)=>K.status==="completed"||K.status==="skipped"))_U();return{success:!0,message:`Step completed: ${z}`,nextStep:J}}function zJ($,Z,Y){if(!D)return{success:!1,message:"No active plan"};let Q=D.strategy.findIndex((z)=>z.id===$);if(Q===-1)return{success:!1,message:`Step not found: ${$}`};let J=D.strategy.map((z,X)=>X===Q?{...z,status:"blocked",blockedReason:Z}:z);return D={...D,strategy:J,status:"blocked",blockedAt:new Date().toISOString(),blockedReason:Z,updatedAt:new Date().toISOString()},H0().emit("planning:blocked",{planId:D.id,stepId:$,reason:Z,proposedAlternative:Y,timestamp:Date.now()}),{success:!0,message:Y?`Step blocked: ${Z}. Proposed alternative: ${Y}`:`Step blocked: ${Z}. Awaiting user guidance.`}}function _U(){if(!D)return;D={...D,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},H0().emit("planning:completed",{planId:D.id,stepsCompleted:D.strategy.filter(($)=>$.status==="completed").length,timestamp:Date.now()}),KJ(D),D=null}function J4(){return D?{...D}:null}function $Z($){let Z=$.strategy.map((J)=>{return`${J.status==="completed"?"\u2713":J.status==="in_progress"?"\u2192":J.status==="blocked"?"\u2717":"\u25CB"} Passo ${J.order}: ${J.action} \u2192 ${J.target}`}),Y=$.assumptions.length>0?$.assumptions.map((J)=>` - ${J}`).join(`
424
- `):" (nenhuma)",Q=$.risks.length>0?$.risks.map((J)=>` - ${J}`).join(`
432
+ Ultima indexacao: ${Q}`}default:return null}}l();u0();import{join as KW}from"path";import{createHash as GW}from"crypto";var VW={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},q8={architectural:["refactor","redesign","migrate","architecture","restructure","microservice","monolith","database schema","api design"],complex:["implement feature","add functionality","integrate","authentication","authorization","security","performance","optimize","cache"],moderate:["update","modify","change","fix bug","add endpoint","create component","add validation","error handling"],simple:["rename","move","delete unused","add comment","format","lint"],trivial:["typo","spacing","import order","semicolon"]},UW=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],qW="",A=null,AZ=[],oJ={...VW},iJ=!1,dJ=null,HW=()=>KW(qW,"plan-history.json");function H1(){return iJ}function PZ($,Z){let Y=$.toLowerCase(),Q=WW(Y),z=Z?.files||[],J=Z?.modules||[],X=[],K=[];for(let U of z)for(let q of UW)if(q.test(U))X.push(`Modifying sensitive file: ${U}`);if(z.length>3)X.push(`Affects ${z.length} files \u2014 higher coordination risk`);if(J.length>1)X.push(`Spans ${J.length} modules \u2014 may have cascading effects`);if(Y.includes("api"))K.push("API contract may need versioning consideration");if(Y.includes("database")||Y.includes("schema"))K.push("Database changes may require migration");if(Y.includes("auth")||Y.includes("security"))K.push("Security changes require thorough review");let G=oJ.requireApprovalFor.includes(Q),V=G?`Task classified as "${Q}" \u2014 requires explicit approval`:`Task classified as "${Q}" \u2014 can proceed with auto-approval`;return{complexity:Q,filesAffected:z,modulesAffected:J,risks:X,assumptions:K,requiresApproval:G,reason:V}}function WW($){for(let Z of q8.architectural)if($.includes(Z))return"architectural";for(let Z of q8.complex)if($.includes(Z))return"complex";for(let Z of q8.moderate)if($.includes(Z))return"moderate";for(let Z of q8.simple)if($.includes(Z))return"simple";for(let Z of q8.trivial)if($.includes(Z))return"trivial";return"moderate"}function rJ($,Z,Y){let Q=PZ($),z={id:lJ(),objective:$,strategy:Z.map((J,X)=>({...J,id:lJ(),order:X+1,status:"pending"})),assumptions:[...Y?.assumptions||[],...Q.assumptions],risks:[...Y?.risks||[],...Q.risks],status:"draft",complexity:Q.complexity,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return A=z,O1().emit("planning:started",{planId:z.id,objective:$,timestamp:Date.now()}),z}async function nJ(){if(!A)return{success:!1,plan:null,message:"No active plan to submit"};if(A.status!=="draft")return{success:!1,plan:A,message:`Plan already in status: ${A.status}`};if(A={...A,status:"pending_approval",updatedAt:new Date().toISOString()},oJ.autoApproveComplexity.includes(A.complexity))return cJ("Auto-approved based on complexity classification");if(dJ)if(await dJ(A))return cJ("Approved by user");else return BW("Rejected by user");return{success:!0,plan:A,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function cJ($){if(!A)return{success:!1,plan:null,message:"No active plan to approve"};if(A.status!=="pending_approval"&&A.status!=="draft")return{success:!1,plan:A,message:`Cannot approve plan in status: ${A.status}`};return A={...A,status:"approved",approvedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),userFeedback:$},O1().emit("planning:approved",{planId:A.id,feedback:$,timestamp:Date.now()}),{success:!0,plan:A,message:"Plan approved \u2014 execution may proceed"}}function BW($){if(!A)return{success:!1,plan:null,message:"No active plan to reject"};return A={...A,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},O1().emit("planning:rejected",{planId:A.id,feedback:$,timestamp:Date.now()}),$3(A),A=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function aJ(){if(!A)return{allowed:!0,reason:"No plan required \u2014 trivial operation"};if(A.status==="approved"||A.status==="executing")return{allowed:!0,reason:"Plan approved \u2014 execution permitted"};if(A.status==="draft"||A.status==="pending_approval")return{allowed:!1,reason:`Execution blocked \u2014 plan awaiting approval (status: ${A.status})`};return{allowed:!1,reason:`Execution blocked \u2014 plan status: ${A.status}`}}function sJ($,Z){if(!A)return{success:!1,message:"No active plan"};let Y=A.strategy.findIndex((K)=>K.id===$);if(Y===-1)return{success:!1,message:`Step not found: ${$}`};let Q=A.strategy.map((K,G)=>G===Y?{...K,status:"completed",result:Z}:K);A={...A,strategy:Q,updatedAt:new Date().toISOString()},O1().emit("planning:step_completed",{planId:A.id,stepId:$,result:Z,timestamp:Date.now()});let z=A.strategy.find((K)=>K.status==="pending"),J=A.strategy[Y].action;if(A.strategy.every((K)=>K.status==="completed"||K.status==="skipped"))OW();return{success:!0,message:`Step completed: ${J}`,nextStep:z}}function tJ($,Z,Y){if(!A)return{success:!1,message:"No active plan"};let Q=A.strategy.findIndex((J)=>J.id===$);if(Q===-1)return{success:!1,message:`Step not found: ${$}`};let z=A.strategy.map((J,X)=>X===Q?{...J,status:"blocked",blockedReason:Z}:J);return A={...A,strategy:z,status:"blocked",blockedAt:new Date().toISOString(),blockedReason:Z,updatedAt:new Date().toISOString()},O1().emit("planning:blocked",{planId:A.id,stepId:$,reason:Z,proposedAlternative:Y,timestamp:Date.now()}),{success:!0,message:Y?`Step blocked: ${Z}. Proposed alternative: ${Y}`:`Step blocked: ${Z}. Awaiting user guidance.`}}function OW(){if(!A)return;A={...A,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},O1().emit("planning:completed",{planId:A.id,stepsCompleted:A.strategy.filter(($)=>$.status==="completed").length,timestamp:Date.now()}),$3(A),A=null}function H8(){return A?{...A}:null}function DZ($){let Z=$.strategy.map((z)=>{return`${z.status==="completed"?"\u2713":z.status==="in_progress"?"\u2192":z.status==="blocked"?"\u2717":"\u25CB"} Passo ${z.order}: ${z.action} \u2192 ${z.target}`}),Y=$.assumptions.length>0?$.assumptions.map((z)=>` - ${z}`).join(`
433
+ `):" (nenhuma)",Q=$.risks.length>0?$.risks.map((z)=>` - ${z}`).join(`
425
434
  `):" (nenhum identificado)";return[`**Objetivo:** ${$.objective}`,"",`**Complexidade:** ${$.complexity}`,"","**Estrat\xE9gia T\xE9cnica:**",...Z,"","**Premissas/Riscos:**",Y,Q,"","**Bloqueio:** Posso prosseguir com este plano ou deseja ajustar algum detalhe?"].join(`
426
- `)}function XJ($){let Z=$.strategy.filter((J)=>J.status==="completed").length,Y=$.strategy.length,Q=$.strategy.find((J)=>J.status==="in_progress"||J.status==="pending");return[`Plano: ${$.objective}`,`Status: ${$.status}`,`Progresso: ${Z}/${Y} passos`,Q?`Pr\xF3ximo: ${Q.action}`:""].filter(Boolean).join(`
427
- `)}function KJ($){let Z={planId:$.id,objective:$.objective,status:$.status,complexity:$.complexity,stepsCompleted:$.strategy.filter((Y)=>Y.status==="completed").length,totalSteps:$.strategy.length,createdAt:$.createdAt,completedAt:$.completedAt};t9=[...t9,Z],xU()}function xU(){if(!$J)return;P(kU(),JSON.stringify(t9,null,2))}function tQ(){return TU("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function VJ(){return`
435
+ `)}function eJ($){let Z=$.strategy.filter((z)=>z.status==="completed").length,Y=$.strategy.length,Q=$.strategy.find((z)=>z.status==="in_progress"||z.status==="pending");return[`Plano: ${$.objective}`,`Status: ${$.status}`,`Progresso: ${Z}/${Y} passos`,Q?`Pr\xF3ximo: ${Q.action}`:""].filter(Boolean).join(`
436
+ `)}function $3($){let Z={planId:$.id,objective:$.objective,status:$.status,complexity:$.complexity,stepsCompleted:$.strategy.filter((Y)=>Y.status==="completed").length,totalSteps:$.strategy.length,createdAt:$.createdAt,completedAt:$.completedAt};AZ=[...AZ,Z],NW()}function NW(){if(!iJ)return;P(HW(),JSON.stringify(AZ,null,2))}function lJ(){return GW("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function Z3(){return`
428
437
  ## Protocolo de Alta Ag\xEAncia
429
438
 
430
439
  Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
@@ -466,50 +475,54 @@ Ao usar \`propose_plan\`, estruture assim:
466
475
  - **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
467
476
  - **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
468
477
  - **Bloqueio**: Sempre termine com "Posso prosseguir com este plano?"
469
- `.trim()}var c5=[{name:"propose_plan",description:"Submit a structured implementation plan for user approval. Use this BEFORE executing any non-trivial task that involves: - Multiple file modifications - Architectural decisions - Business logic changes - API integrations The plan must include objective, steps with targets, and risks/assumptions. Execution is BLOCKED until the user approves the plan.",input_schema:{type:"object",properties:{objective:{type:"string",description:'Concise description of the end goal (e.g., "Implement JWT authentication for /api/users")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",description:'What to do (e.g., "Create middleware")'},target:{type:"string",description:'Target file or module (e.g., "src/middleware/auth.ts")'},description:{type:"string",description:"Brief explanation of this step"},estimatedImpact:{type:"string",enum:["none","low","medium","high","critical"],description:"Risk level of this step. Default: low."},dependencies:{type:"array",items:{type:"string"},description:"IDs of steps that must complete first. Optional."}},required:["action","target","description"]},description:"Ordered list of implementation steps"},assumptions:{type:"array",items:{type:"string"},description:'Key assumptions being made (e.g., "JWT secret exists in .env")'},risks:{type:"array",items:{type:"string"},description:"Potential risks or breaking changes"}},required:["objective","steps"]}},{name:"check_plan_status",description:"Check if execution is allowed based on the current plan status. Returns whether you can proceed with modifications or need to wait for approval. Use this before any write operation if unsure about plan state.",input_schema:{type:"object",properties:{},required:[]}},{name:"report_plan_deviation",description:"Report that the current execution plan has encountered an obstacle. Use this when you discover something that invalidates the original plan. This STOPS execution and requires proposing an alternative approach. MANDATORY: Always explain what was found and propose a concrete alternative.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the step that encountered the obstacle. Optional if not in specific step."},obstacle:{type:"string",description:'What obstacle was encountered (e.g., "API does not support pagination")'},impact:{type:"string",description:'How this affects the plan (e.g., "Cannot proceed with step 3")'},alternative:{type:"string",description:"Proposed alternative approach"}},required:["obstacle","impact","alternative"]}},{name:"complete_plan_step",description:"Mark a plan step as completed and optionally provide the result. Use this after successfully completing each step in the approved plan. This helps track progress and enables checkpoint validation.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the completed step"},result:{type:"string",description:"Brief description of what was accomplished. Optional."}},required:["step_id"]}},{name:"get_current_plan",description:"Get the current active plan with its status and progress. Use to review the plan before continuing execution or to show status to user.",input_schema:{type:"object",properties:{},required:[]}},{name:"analyze_task_complexity",description:"Analyze a task description to determine its complexity and whether it requires planning. Returns complexity classification (trivial/simple/moderate/complex/architectural) and whether explicit approval is needed. Use this when unsure if planning is required.",input_schema:{type:"object",properties:{task:{type:"string",description:"Description of the task to analyze"},files:{type:"array",items:{type:"string"},description:"List of files that would be affected. Optional."},modules:{type:"array",items:{type:"string"},description:"List of modules/systems that would be affected. Optional."}},required:["task"]}}];async function GJ($,Z){switch($){case"propose_plan":{if(!K0())return"Error: Agency engine not initialized. Planning features unavailable.";let Y=Z.objective;if(!Y?.trim())return"Error: objective is required.";let Q=Z.steps;if(!Q?.length)return"Error: at least one step is required.";let J=Q.map((V,G)=>({action:V.action,target:V.target,description:V.description,estimatedImpact:V.estimatedImpact||"low",dependencies:V.dependencies||[],order:G+1})),z=ZJ(Y,J,{assumptions:Z.assumptions,risks:Z.risks}),X=await YJ();if(!X.success)return`Error creating plan: ${X.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
478
+ `.trim()}var z7=[{name:"propose_plan",description:"Submit a structured implementation plan for user approval. Use this BEFORE executing any non-trivial task that involves: - Multiple file modifications - Architectural decisions - Business logic changes - API integrations The plan must include objective, steps with targets, and risks/assumptions. Execution is BLOCKED until the user approves the plan.",input_schema:{type:"object",properties:{objective:{type:"string",description:'Concise description of the end goal (e.g., "Implement JWT authentication for /api/users")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",description:'What to do (e.g., "Create middleware")'},target:{type:"string",description:'Target file or module (e.g., "src/middleware/auth.ts")'},description:{type:"string",description:"Brief explanation of this step"},estimatedImpact:{type:"string",enum:["none","low","medium","high","critical"],description:"Risk level of this step. Default: low."},dependencies:{type:"array",items:{type:"string"},description:"IDs of steps that must complete first. Optional."}},required:["action","target","description"]},description:"Ordered list of implementation steps"},assumptions:{type:"array",items:{type:"string"},description:'Key assumptions being made (e.g., "JWT secret exists in .env")'},risks:{type:"array",items:{type:"string"},description:"Potential risks or breaking changes"}},required:["objective","steps"]}},{name:"check_plan_status",description:"Check if execution is allowed based on the current plan status. Returns whether you can proceed with modifications or need to wait for approval. Use this before any write operation if unsure about plan state.",input_schema:{type:"object",properties:{},required:[]}},{name:"report_plan_deviation",description:"Report that the current execution plan has encountered an obstacle. Use this when you discover something that invalidates the original plan. This STOPS execution and requires proposing an alternative approach. MANDATORY: Always explain what was found and propose a concrete alternative.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the step that encountered the obstacle. Optional if not in specific step."},obstacle:{type:"string",description:'What obstacle was encountered (e.g., "API does not support pagination")'},impact:{type:"string",description:'How this affects the plan (e.g., "Cannot proceed with step 3")'},alternative:{type:"string",description:"Proposed alternative approach"}},required:["obstacle","impact","alternative"]}},{name:"complete_plan_step",description:"Mark a plan step as completed and optionally provide the result. Use this after successfully completing each step in the approved plan. This helps track progress and enables checkpoint validation.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the completed step"},result:{type:"string",description:"Brief description of what was accomplished. Optional."}},required:["step_id"]}},{name:"get_current_plan",description:"Get the current active plan with its status and progress. Use to review the plan before continuing execution or to show status to user.",input_schema:{type:"object",properties:{},required:[]}},{name:"analyze_task_complexity",description:"Analyze a task description to determine its complexity and whether it requires planning. Returns complexity classification (trivial/simple/moderate/complex/architectural) and whether explicit approval is needed. Use this when unsure if planning is required.",input_schema:{type:"object",properties:{task:{type:"string",description:"Description of the task to analyze"},files:{type:"array",items:{type:"string"},description:"List of files that would be affected. Optional."},modules:{type:"array",items:{type:"string"},description:"List of modules/systems that would be affected. Optional."}},required:["task"]}}];async function Y3($,Z){switch($){case"propose_plan":{if(!H1())return"Error: Agency engine not initialized. Planning features unavailable.";let Y=Z.objective;if(!Y?.trim())return"Error: objective is required.";let Q=Z.steps;if(!Q?.length)return"Error: at least one step is required.";let z=Q.map((G,V)=>({action:G.action,target:G.target,description:G.description,estimatedImpact:G.estimatedImpact||"low",dependencies:G.dependencies||[],order:V+1})),J=rJ(Y,z,{assumptions:Z.assumptions,risks:Z.risks}),X=await nJ();if(!X.success)return`Error creating plan: ${X.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
470
479
 
471
- ${$Z(z)}`}case"check_plan_status":{if(!K0())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=QJ(),Q=J4();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${XJ(Q)}
480
+ ${DZ(J)}`}case"check_plan_status":{if(!H1())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=aJ(),Q=H8();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${eJ(Q)}
472
481
 
473
482
  Execu\xE7\xE3o: ${Y.allowed?"PERMITIDA":"BLOQUEADA"}
474
- Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!K0())return"Error: Agency engine not initialized.";let{obstacle:Y,impact:Q,alternative:J}=Z;if(!Y?.trim())return"Error: obstacle is required.";if(!Q?.trim())return"Error: impact is required.";if(!J?.trim())return"Error: alternative is required.";let z=J4();if(!z)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let X=Z.step_id,K=X?z.strategy.find((V)=>V.id===X):z.strategy.find((V)=>V.status==="in_progress"||V.status==="pending");if(K)zJ(K.id,Y,J);return["**Desvio Detectado**","",`**Obst\xE1culo:** ${Y}`,`**Impacto no Plano:** ${Q}`,"","**Alternativa Proposta:**",J,"","**Status:** Execu\xE7\xE3o BLOQUEADA. Aguardando aprova\xE7\xE3o da alternativa.","","**Bloqueio:** Posso prosseguir com esta alternativa?"].join(`
475
- `)}case"complete_plan_step":{if(!K0())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=JJ(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let J=J4(),z=J?`Progresso: ${J.strategy.filter((K)=>K.status==="completed").length}/${J.strategy.length}`:"",X=Q.nextStep?`
483
+ Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!H1())return"Error: Agency engine not initialized.";let{obstacle:Y,impact:Q,alternative:z}=Z;if(!Y?.trim())return"Error: obstacle is required.";if(!Q?.trim())return"Error: impact is required.";if(!z?.trim())return"Error: alternative is required.";let J=H8();if(!J)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let X=Z.step_id,K=X?J.strategy.find((G)=>G.id===X):J.strategy.find((G)=>G.status==="in_progress"||G.status==="pending");if(K)tJ(K.id,Y,z);return["**Desvio Detectado**","",`**Obst\xE1culo:** ${Y}`,`**Impacto no Plano:** ${Q}`,"","**Alternativa Proposta:**",z,"","**Status:** Execu\xE7\xE3o BLOQUEADA. Aguardando aprova\xE7\xE3o da alternativa.","","**Bloqueio:** Posso prosseguir com esta alternativa?"].join(`
484
+ `)}case"complete_plan_step":{if(!H1())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=sJ(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let z=H8(),J=z?`Progresso: ${z.strategy.filter((K)=>K.status==="completed").length}/${z.strategy.length}`:"",X=Q.nextStep?`
476
485
  Pr\xF3ximo passo: ${Q.nextStep.action} \u2192 ${Q.nextStep.target}`:`
477
486
  Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Q.message}
478
- ${z}${X}`}case"get_current_plan":{if(!K0())return"Agency engine not initialized. No planning features available.";let Y=J4();if(!Y)return"Nenhum plano ativo no momento.";return $Z(Y)}case"analyze_task_complexity":{if(!K0())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=e9(Y,{files:Z.files,modules:Z.modules}),J=["**An\xE1lise de Complexidade**","",`**Tarefa:** ${Y}`,`**Classifica\xE7\xE3o:** ${Q.complexity}`,`**Requer Aprova\xE7\xE3o:** ${Q.requiresApproval?"SIM":"N\xC3O"}`,"",`**Motivo:** ${Q.reason}`];if(Q.risks.length>0){J.push("","**Riscos Identificados:**");for(let z of Q.risks)J.push(` - ${z}`)}if(Q.assumptions.length>0){J.push("","**Premissas:**");for(let z of Q.assumptions)J.push(` - ${z}`)}if(Q.requiresApproval)J.push("","**Recomenda\xE7\xE3o:** Use `propose_plan` antes de executar esta tarefa.");return J.join(`
479
- `)}default:return null}}o();import{existsSync as qJ,readdirSync as vU,readFileSync as fU,mkdirSync as hU}from"fs";import{join as ZZ}from"path";function f1($){if(!qJ($))return[];let Z=[],Y=vU($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let J=JSON.parse(fU(ZZ($,Q),"utf-8"));if(!J.name||!J.description||!J.command)continue;if(typeof J.name!=="string"||typeof J.command!=="string")continue;if(J.command.includes("$(")||J.command.includes("`"))continue;Z.push({name:J.name,description:J.description,inputSchema:J.input_schema||{type:"object",properties:{},required:[]},command:J.command,source:ZZ($,Q)})}catch{}return Z}function h1($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function YZ($,Z){let Y=$.command;for(let[q,U]of Object.entries(Z)){let W=String(U).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${q}\\}\\}`,"g"),W)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let Q=q1(),J=Bun.spawn([...Q,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),z=setTimeout(()=>J.kill(),30000),[X,K]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),V=await J.exited;clearTimeout(z);let G=X.trim();if(K.trim())G+=(G?`
480
- `:"")+K.trim();if(V!==0)G+=(G?`
481
- `:"")+`Exit code: ${V}`;return G||"(no output)"}function UJ($){let Z=ZZ($,"plugins");if(!qJ(Z))hU(Z,{recursive:!0});return Z}g();import{existsSync as zZ,readFileSync as BJ,statSync as pU}from"fs";import{resolve as XZ}from"path";import{existsSync as gU,realpathSync as mU}from"fs";import{resolve as uU,sep as HJ}from"path";var QZ=10485760;function k0($){let Z=uU($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+HJ))return`Error: path outside working directory is not permitted: ${Z}`;try{if(gU(Z)){let Q=mU(Z);if(Q!==Y&&!Q.startsWith(Y+HJ))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function V0($,Z){let Y=$[Z];if(typeof Y!=="string"||Y.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function JZ($){try{let Z=new URL($),Y=Z.hostname.toLowerCase();if(Z.protocol!=="http:"&&Z.protocol!=="https:")return`Error: protocol ${Z.protocol} is not allowed.`;if(["localhost","127.0.0.1","::1","0.0.0.0","::ffff:127.0.0.1","::ffff:0.0.0.0"].includes(Y))return"Error: requests to localhost are blocked for security.";if(Y.endsWith(".local")||Y.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(Y==="metadata.google.internal"||Y==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let J=Y.split(".").map(Number);if(J.length===4&&J.every((z)=>!isNaN(z)&&z>=0&&z<=255)){if(J[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(J[0]===172&&J[1]>=16&&J[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(J[0]===192&&J[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(J[0]===169&&J[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(J[0]===0)return"Error: requests to 0.x IPs are blocked."}if(Y.startsWith("::ffff:")||Y.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function WJ($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi,"").replace(/<header[^>]*>[\s\S]*?<\/header>/gi,"").replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi,"").replace(/<\/(p|div|h[1-6]|li|tr|br|hr)[^>]*>/gi,`
487
+ ${J}${X}`}case"get_current_plan":{if(!H1())return"Agency engine not initialized. No planning features available.";let Y=H8();if(!Y)return"Nenhum plano ativo no momento.";return DZ(Y)}case"analyze_task_complexity":{if(!H1())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=PZ(Y,{files:Z.files,modules:Z.modules}),z=["**An\xE1lise de Complexidade**","",`**Tarefa:** ${Y}`,`**Classifica\xE7\xE3o:** ${Q.complexity}`,`**Requer Aprova\xE7\xE3o:** ${Q.requiresApproval?"SIM":"N\xC3O"}`,"",`**Motivo:** ${Q.reason}`];if(Q.risks.length>0){z.push("","**Riscos Identificados:**");for(let J of Q.risks)z.push(` - ${J}`)}if(Q.assumptions.length>0){z.push("","**Premissas:**");for(let J of Q.assumptions)z.push(` - ${J}`)}if(Q.requiresApproval)z.push("","**Recomenda\xE7\xE3o:** Use `propose_plan` antes de executar esta tarefa.");return z.join(`
488
+ `)}default:return null}}s();import{existsSync as G3,readdirSync as CW,readFileSync as EW,mkdirSync as RW}from"fs";import{join as SZ}from"path";var W8={"desktop.about":"About smolerclaw","desktop.settings":"Settings...","desktop.quit":"Quit","desktop.chat":"Chat","desktop.new_chat":"New Chat","desktop.clear_chat":"Clear Chat","desktop.edit":"Edit","desktop.undo":"Undo","desktop.redo":"Redo","desktop.cut":"Cut","desktop.copy":"Copy","desktop.paste":"Paste","desktop.select_all":"Select All","desktop.view":"View","desktop.toggle_theme":"Toggle Theme","desktop.actual_size":"Actual Size","desktop.zoom_in":"Zoom In","desktop.zoom_out":"Zoom Out","desktop.dev_tools":"Toggle Developer Tools","desktop.window":"Window","desktop.minimize":"Minimize","desktop.zoom":"Zoom","desktop.close":"Close","desktop.help":"Help","desktop.documentation":"Documentation","desktop.report_issue":"Report Issue","desktop.not_available":"Electrobun not available.","desktop.opening_browser":"Opening in default browser: {{url}}","web.title":"smolerclaw","web.welcome_title":"Welcome to smolerclaw","web.welcome_desc":"Your micro AI assistant for Windows. Ask me anything, and I'll help you with code, files, system tasks, and more.","web.new_chat":"+ New Chat","web.no_sessions":"No sessions yet","web.total_cost":"Total cost:","web.toggle_theme":"Toggle theme","web.clear_chat":"Clear chat","web.placeholder":"Message smolerclaw...","web.input_hint":"Press Enter to send, Shift+Enter for new line","web.confirm_new_chat":"Start a new chat?","web.messages_count":"{{count}} messages","web.you":"You","web.assistant":"smolerclaw","web.running":"running","web.complete":"complete","web.connected":"Connected to smolerclaw","web.disconnected":"Disconnected, reconnecting...","web.suggestion_start_title":"Get started","web.suggestion_start_desc":"Learn what I can do","web.suggestion_tasks_title":"View tasks","web.suggestion_tasks_desc":"See your task list","web.suggestion_system_title":"System info","web.suggestion_system_desc":"Get Windows status","web.suggestion_briefing_title":"Daily briefing","web.suggestion_briefing_desc":"Start your day","web.suggestion_start_prompt":"What can you help me with?","web.suggestion_tasks_prompt":"Show me my recent tasks","web.suggestion_system_prompt":"Check system status","web.suggestion_briefing_prompt":"Give me a daily briefing","ui.starting_web":"Starting smolerclaw web UI...","ui.starting_desktop":"Starting smolerclaw desktop app...","ui.running_at":"App running at: {{url}}","session.no_sessions":"No sessions found.","session.sessions_title":"Sessions","session.messages":"{{count}} messages","session.filter":"filter:","label.you":"You","label.assistant":"Claude","approval.prompt":"[y]es / [n]o / [a]ll","approval.approved":"approved","approval.rejected":"rejected","approval.approved_all":"approved all for this session","approval.timeout":"timeout \u2014 auto-rejected","tool.more_lines":"... ({{count}} more lines)","plugin.none_loaded":"No plugins loaded. Add files to {{dir}}","plugin.list_title":"Plugins:"};var Q3={"desktop.about":"Sobre o smolerclaw","desktop.settings":"Configura\xE7\xF5es...","desktop.quit":"Sair","desktop.chat":"Conversa","desktop.new_chat":"Nova Conversa","desktop.clear_chat":"Limpar Conversa","desktop.edit":"Editar","desktop.undo":"Desfazer","desktop.redo":"Refazer","desktop.cut":"Recortar","desktop.copy":"Copiar","desktop.paste":"Colar","desktop.select_all":"Selecionar Tudo","desktop.view":"Visualizar","desktop.toggle_theme":"Alternar Tema","desktop.actual_size":"Tamanho Real","desktop.zoom_in":"Aumentar Zoom","desktop.zoom_out":"Diminuir Zoom","desktop.dev_tools":"Ferramentas do Desenvolvedor","desktop.window":"Janela","desktop.minimize":"Minimizar","desktop.zoom":"Zoom","desktop.close":"Fechar","desktop.help":"Ajuda","desktop.documentation":"Documenta\xE7\xE3o","desktop.report_issue":"Reportar Problema","desktop.not_available":"Electrobun n\xE3o dispon\xEDvel.","desktop.opening_browser":"Abrindo no navegador padr\xE3o: {{url}}","web.title":"smolerclaw","web.welcome_title":"Bem-vindo ao smolerclaw","web.welcome_desc":"Seu micro assistente de IA para Windows. Pergunte qualquer coisa \u2014 ajudo com c\xF3digo, arquivos, tarefas do sistema e muito mais.","web.new_chat":"+ Nova Conversa","web.no_sessions":"Nenhuma sess\xE3o ainda","web.total_cost":"Custo total:","web.toggle_theme":"Alternar tema","web.clear_chat":"Limpar conversa","web.placeholder":"Mensagem para o smolerclaw...","web.input_hint":"Enter para enviar, Shift+Enter para nova linha","web.confirm_new_chat":"Iniciar nova conversa?","web.messages_count":"{{count}} mensagens","web.you":"Voc\xEA","web.assistant":"smolerclaw","web.running":"executando","web.complete":"conclu\xEDdo","web.connected":"Conectado ao smolerclaw","web.disconnected":"Desconectado, reconectando...","web.suggestion_start_title":"Come\xE7ar","web.suggestion_start_desc":"Saiba o que eu posso fazer","web.suggestion_tasks_title":"Ver tarefas","web.suggestion_tasks_desc":"Veja sua lista de tarefas","web.suggestion_system_title":"Info do sistema","web.suggestion_system_desc":"Status do Windows","web.suggestion_briefing_title":"Briefing di\xE1rio","web.suggestion_briefing_desc":"Comece seu dia","web.suggestion_start_prompt":"O que voc\xEA pode fazer por mim?","web.suggestion_tasks_prompt":"Mostre minhas tarefas recentes","web.suggestion_system_prompt":"Verifique o status do sistema","web.suggestion_briefing_prompt":"Me d\xEA um briefing di\xE1rio","ui.starting_web":"Iniciando interface web do smolerclaw...","ui.starting_desktop":"Iniciando app desktop do smolerclaw...","ui.running_at":"App rodando em: {{url}}","session.no_sessions":"Nenhuma sess\xE3o encontrada.","session.sessions_title":"Sess\xF5es","session.messages":"{{count}} mensagens","session.filter":"filtro:","label.you":"Voc\xEA","label.assistant":"Claude","approval.prompt":"[s]im / [n]\xE3o / [t]odos","approval.approved":"aprovado","approval.rejected":"rejeitado","approval.approved_all":"aprovado tudo para esta sess\xE3o","approval.timeout":"tempo esgotado \u2014 rejeitado automaticamente","tool.more_lines":"... ({{count}} linhas a mais)","plugin.none_loaded":"Nenhum plugin carregado. Adicione arquivos em {{dir}}","plugin.list_title":"Plugins:"};function z3($){if($!=="auto")return TZ($);try{let Y=Intl.DateTimeFormat().resolvedOptions().locale;if(Y){let Q=TZ(Y);if(Q!=="en")return Q}}catch{}let Z=process.env.LANG||process.env.LC_ALL||process.env.LANGUAGE||"";if(Z)return TZ(Z);return"en"}function TZ($){if($.toLowerCase().replace(/_/g,"-").startsWith("pt"))return"pt";return"en"}var MW={en:W8,pt:Q3},J3="en",IZ=W8;function X3($){J3=z3($),IZ=MW[J3]||W8}function S($,Z){let Y=IZ[$]||W8[$]||$;if(Z)for(let[Q,z]of Object.entries(Z))Y=Y.replace(new RegExp(`\\{\\{${Q}\\}\\}`,"g"),String(z));return Y}function K3(){return{...IZ}}function c$($){if(!G3($))return[];let Z=[],Y=CW($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let z=JSON.parse(EW(SZ($,Q),"utf-8"));if(!z.name||!z.description||!z.command)continue;if(typeof z.name!=="string"||typeof z.command!=="string")continue;if(z.command.includes("$(")||z.command.includes("`"))continue;Z.push({name:z.name,description:z.description,inputSchema:z.input_schema||{type:"object",properties:{},required:[]},command:z.command,source:SZ($,Q)})}catch{}return Z}function l$($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function J7($,Z){let Y=$.command;for(let[U,q]of Object.entries(Z)){let H=String(q).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${U}\\}\\}`,"g"),H)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let Q=B$(),z=Bun.spawn([...Q,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),J=setTimeout(()=>z.kill(),30000),[X,K]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),G=await z.exited;clearTimeout(J);let V=X.trim();if(K.trim())V+=(V?`
489
+ `:"")+K.trim();if(G!==0)V+=(V?`
490
+ `:"")+`Exit code: ${G}`;return V||"(no output)"}function V3($){let Z=SZ($,"plugins");if(!G3(Z))RW(Z,{recursive:!0});return Z}import{existsSync as H0,readdirSync as G7,readFileSync as O8,mkdirSync as kZ,renameSync as wZ,rmSync as B8}from"fs";import{join as p,basename as X7,extname as K7}from"path";u0();u0();var w=[],F0="",U3="";async function q3($,Z){if(F0=$,U3=Z,w=[],!H0($))return kZ($,{recursive:!0}),[];let Y=c$($);for(let z of Y)w=[...w,{name:z.name,description:z.description,version:"1.0.0",type:"json",source:z.source,enabled:!0,tools:l$([z]),jsonPlugin:z,eventUnsubs:[]}];let Q=G7($).filter((z)=>{let J=K7(z);return J===".ts"||J===".js"});for(let z of Q){let J=p($,z);try{let X=await import(J),K=X.default||X;if(!K.name||!K.description){m.debug(`Skipping invalid script plugin: ${z}`);continue}let G=await fZ(K,J);if(G)w=[...w,G]}catch(X){m.debug(`Failed to load script plugin: ${z}`,{error:X instanceof Error?X.message:String(X)})}}return Q0("status:update",{source:"plugin-system",message:`${w.length} plugin(s) carregado(s)`,level:"info",timestamp:Date.now()}),w}async function fZ($,Z){let Y=p(U3,"plugins",$.name);if(!H0(Y))kZ(Y,{recursive:!0});let Q={notify:(J,X="info")=>{Q0("status:update",{source:`plugin:${$.name}`,message:J,level:X,timestamp:Date.now()})},dataDir:Y};try{await $.onLoad?.(Q)}catch(J){return m.debug(`Plugin ${$.name} onLoad failed`,{error:J instanceof Error?J.message:String(J)}),null}let z=[];if($.events){for(let[J,X]of Object.entries($.events))if(X){let K=t.on(J,X,{async:!0});z.push(K)}}return{name:$.name,description:$.description,version:$.version||"1.0.0",type:"script",source:Z,enabled:!0,tools:$.tools||[],scriptDef:$,eventUnsubs:z}}function H3(){return w.filter(($)=>$.enabled).flatMap(($)=>[...$.tools])}async function W3($,Z){for(let Y of w){if(!Y.enabled)continue;if(!Y.tools.some((z)=>z.name===$))continue;if(Y.type==="script"&&Y.scriptDef?.onToolCall)return await Y.scriptDef.onToolCall($,Z);if(Y.type==="json"&&Y.jsonPlugin)return await J7(Y.jsonPlugin,Z)}return null}function B3($){let Z=w.findIndex((J)=>J.name===$);if(Z===-1)return!1;let Y=w[Z];if(!Y.enabled)return!1;for(let J of Y.eventUnsubs)J();if(Y.type==="script"&&Y.scriptDef?.onUnload)try{Y.scriptDef.onUnload()}catch{}let Q=p(F0,"disabled");if(!H0(Q))kZ(Q,{recursive:!0});let z=p(Q,X7(Y.source));try{wZ(Y.source,z)}catch{}return w=w.map((J,X)=>X===Z?{...J,enabled:!1,eventUnsubs:[]}:J),Q0("status:update",{source:"plugin-system",message:`Plugin "${$}" desabilitado`,level:"info",timestamp:Date.now()}),!0}async function O3($){let Z=w.findIndex((G)=>G.name===$&&!G.enabled);if(Z!==-1){let G=w[Z],V=p(F0,"disabled"),U=p(V,X7(G.source)),q=p(F0,X7(G.source));if(H0(U))try{wZ(U,q)}catch{}return w=w.map((H,B)=>B===Z?{...H,enabled:!0,source:q}:H),Q0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}let Y=p(F0,"disabled");if(!H0(Y))return!1;let z=G7(Y).find((G)=>{return X7(G,K7(G))===$});if(!z)return!1;let J=p(Y,z),X=p(F0,z);try{wZ(J,X)}catch{return!1}let K=K7(z);if(K===".json"){let G=c$(F0).filter((V)=>V.source===X);for(let V of G)w=[...w,{name:V.name,description:V.description,version:"1.0.0",type:"json",source:V.source,enabled:!0,tools:l$([V]),jsonPlugin:V,eventUnsubs:[]}]}else if(K===".ts"||K===".js")try{let G=await import(X),V=G.default||G;if(V.name&&V.description){let U=await fZ(V,X);if(U)w=[...w,U]}}catch{}return Q0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}async function N3($){if(!F0)return{success:!1,name:"",message:"Plugin system nao inicializado."};let Z=FW($);if(!Z)return{success:!1,name:"",message:`Fonte invalida: "${$}". Use owner/repo ou URL do GitHub.`};let{owner:Y,repo:Q,branch:z}=Z,J=p(F0,"installed",`${Y}--${Q}`);if(H0(J))return{success:!1,name:`${Y}/${Q}`,message:`Plugin ${Y}/${Q} ja instalado. Use /plugin uninstall para remover.`};let X=`https://github.com/${Y}/${Q}.git`,K=["git","clone","--depth","1"];if(z)K.push("--branch",z);K.push(X,J);try{let M=Bun.spawn(K,{stdout:"pipe",stderr:"pipe"}),C=setTimeout(()=>M.kill(),30000),[,F]=await Promise.all([new Response(M.stdout).text(),new Response(M.stderr).text()]),k=await M.exited;if(clearTimeout(C),k!==0){try{B8(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`git clone falhou: ${F.trim().split(`
491
+ `)[0]||`exit code ${k}`}`}}}catch(M){try{B8(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`Erro ao clonar: ${M instanceof Error?M.message:String(M)}`}}let G=LW(J);if(!G){try{B8(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:'Nenhum entry point encontrado. O repo deve conter plugin.json, plugin.ts, index.ts, ou package.json com campo "smolerclaw".'}}let V=K7(G.path),U=`${Y}--${Q}${V}`,q=p(F0,U);if(V===".ts"||V===".js"){let M=G.path.replace(/\\/g,"/"),C=`// Auto-installed from github.com/${Y}/${Q}
492
+ export { default } from '${M}'
493
+ `;Bun.write(q,C)}else{let M=O8(G.path,"utf-8");Bun.write(q,M)}if(V===".json"){let M=c$(F0).filter((C)=>C.source===q);for(let C of M)w=[...w,{name:C.name,description:C.description,version:"1.0.0",type:"json",source:q,enabled:!0,tools:l$([C]),jsonPlugin:C,eventUnsubs:[]}]}else try{let M=await import(G.path),C=M.default||M;if(C.name&&C.description){let F=await fZ(C,q);if(F)w=[...w,F]}}catch{}let B=w.find((M)=>M.source===q)?.name||`${Y}/${Q}`;Q0("status:update",{source:"plugin-system",message:`Plugin "${B}" instalado de github.com/${Y}/${Q}`,level:"success",timestamp:Date.now()});let O=p(J,".smolerclaw-install.json");return Bun.write(O,JSON.stringify({source:`${Y}/${Q}`,branch:z||"default",installedAt:new Date().toISOString(),entryPoint:q,pluginName:B},null,2)),{success:!0,name:B,message:`Plugin "${B}" instalado com sucesso de github.com/${Y}/${Q}.`}}function M3($){if(!F0)return{success:!1,message:"Plugin system nao inicializado."};let Z=p(F0,"installed");if(!H0(Z))return{success:!1,message:`Plugin "${$}" nao encontrado.`};let Y=w.find((J)=>J.name===$),Q=null,z=null;if(Y){z=Y.source;let J=G7(Z).filter((X)=>H0(p(Z,X,".smolerclaw-install.json")));for(let X of J)try{let K=JSON.parse(O8(p(Z,X,".smolerclaw-install.json"),"utf-8"));if(K.pluginName===$||K.entryPoint===z){Q=p(Z,X);break}}catch{}}else{let J=$.replace("/","--"),X=p(Z,J);if(H0(X)){Q=X;try{z=JSON.parse(O8(p(X,".smolerclaw-install.json"),"utf-8")).entryPoint||null}catch{}}}if(!Q&&!z)return{success:!1,message:`Plugin "${$}" nao encontrado entre os instalados.`};if(Y){for(let J of Y.eventUnsubs)J();if(Y.scriptDef?.onUnload)try{Y.scriptDef.onUnload()}catch{}w=w.filter((J)=>J.name!==$)}if(z&&H0(z))try{B8(z,{force:!0})}catch{}if(Q)try{B8(Q,{recursive:!0,force:!0})}catch{}return Q0("status:update",{source:"plugin-system",message:`Plugin "${$}" desinstalado`,level:"info",timestamp:Date.now()}),{success:!0,message:`Plugin "${$}" desinstalado com sucesso.`}}function C3(){let $=p(F0,"installed");if(!H0($))return[];let Z=[],Y=G7($);for(let Q of Y){let z=p($,Q,".smolerclaw-install.json");if(!H0(z))continue;try{let J=JSON.parse(O8(z,"utf-8"));Z.push({name:J.pluginName||Q,source:J.source||Q.replace("--","/"),installedAt:J.installedAt||"desconhecido"})}catch{}}return Z}function FW($){let Z=$.match(/github\.com\/([^/]+)\/([^/\s#]+)/);if(Z){let Q=Z[2].replace(/\.git$/,""),z=$.match(/#(.+)$/);return{owner:Z[1],repo:Q,branch:z?.[1]||null}}let Y=$.match(/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+?)(?:#(.+))?$/);if(Y)return{owner:Y[1],repo:Y[2],branch:Y[3]||null};return null}function LW($){let Z=p($,"package.json");if(H0(Z))try{let z=JSON.parse(O8(Z,"utf-8"));if(z.smolerclaw){let J=p($,z.smolerclaw);if(H0(J))return{path:J}}}catch{}let Y=["plugin.json","plugin.ts","plugin.js","index.ts","index.js"];for(let z of Y){let J=p($,z);if(H0(J))return{path:J}}let Q=["src/plugin.ts","src/plugin.js","src/index.ts","src/index.js"];for(let z of Q){let J=p($,z);if(H0(J))return{path:J}}return null}function E3($){return w.find((Z)=>Z.name===$)}function R3(){if(w.length===0)return"Nenhum plugin carregado. Adicione arquivos em ~/.config/smolerclaw/plugins/";let $=["Plugins:"];for(let Z of w){let Y=Z.enabled?"":" [desabilitado]",Q=Z.type==="script"?"script":"json",z=Z.tools.length;$.push(` ${Z.name} v${Z.version} (${Q}) \u2014 ${Z.description} [${z} tool${z!==1?"s":""}]${Y}`)}return $.join(`
494
+ `)}async function F3(){for(let $ of w){for(let Z of $.eventUnsubs)Z();if($.type==="script"&&$.scriptDef?.onUnload)try{await $.scriptDef.onUnload()}catch{}}w=[]}l();import{existsSync as _Z,readFileSync as A3,statSync as DW}from"fs";import{resolve as xZ}from"path";import{existsSync as jW,realpathSync as AW}from"fs";import{resolve as PW,sep as L3}from"path";var bZ=10485760;function y1($){let Z=PW($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+L3))return`Error: path outside working directory is not permitted: ${Z}`;try{if(jW(Z)){let Q=AW(Z);if(Q!==Y&&!Q.startsWith(Y+L3))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function W1($,Z){let Y=$[Z];if(typeof Y!=="string"||Y.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function yZ($){try{let Z=new URL($),Y=Z.hostname.toLowerCase();if(Z.protocol!=="http:"&&Z.protocol!=="https:")return`Error: protocol ${Z.protocol} is not allowed.`;if(["localhost","127.0.0.1","::1","0.0.0.0","::ffff:127.0.0.1","::ffff:0.0.0.0"].includes(Y))return"Error: requests to localhost are blocked for security.";if(Y.endsWith(".local")||Y.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(Y==="metadata.google.internal"||Y==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let z=Y.split(".").map(Number);if(z.length===4&&z.every((J)=>!isNaN(J)&&J>=0&&J<=255)){if(z[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(z[0]===172&&z[1]>=16&&z[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(z[0]===192&&z[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(z[0]===169&&z[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(z[0]===0)return"Error: requests to 0.x IPs are blocked."}if(Y.startsWith("::ffff:")||Y.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function j3($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi,"").replace(/<header[^>]*>[\s\S]*?<\/header>/gi,"").replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi,"").replace(/<\/(p|div|h[1-6]|li|tr|br|hr)[^>]*>/gi,`
482
495
  `).replace(/<(br|hr)[^>]*\/?>/gi,`
483
496
  `).replace(/<[^>]+>/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
484
497
 
485
- `).trim()}function MJ($){let Z=V0($,"path");if(Z)return Z;let Y=XZ($.path),Q=k0(Y);if(Q)return Q;if(!zZ(Y))return`Error: file not found: ${Y}`;let J=pU(Y).size;if(J>QZ)return`Error: file too large (${Z4(J)}). Max is ${Z4(QZ)}.`;let X=BJ(Y,"utf-8").split(`
486
- `),K=Math.max(1,$.offset||1),V=Math.min(2000,$.limit||500),U=X.slice(K-1,K-1+V).map((B,M)=>`${String(K+M).padStart(4)} ${B}`).join(`
487
- `),W=X.length-(K-1+V);if(W>0)U+=`
488
- ... (${W} more lines, total ${X.length})`;return h$(U)}function CJ($,Z){let Y=V0($,"path");if(Y)return Y;let Q=XZ($.path),J=k0(Q);if(J)return J;let z=$.content,X=zZ(Q);Z.saveState(Q),P(Q,z);let K=z.split(`
489
- `).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function NJ($,Z){let Y=V0($,"path");if(Y)return Y;let Q=XZ($.path),J=k0(Q);if(J)return J;if(!zZ(Q))return`Error: file not found: ${Q}`;let z=BJ(Q,"utf-8"),X=$.old_text,K=$.new_text,V=z.split(X).length-1;if(V===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(V>1)return`Error: old_text found ${V} times. It must be unique. Include more surrounding context.`;Z.saveState(Q);let G=z.split(X).join(K);P(Q,G);let q=X.split(`
490
- `).length,U=K.split(`
491
- `).length;return`Edited: ${Q} (replaced ${q} lines with ${U} lines)`}o();import{existsSync as dU,readdirSync as cU,readFileSync as lU,statSync as oU}from"fs";import{resolve as KZ,join as FJ,sep as OJ}from"path";async function RJ($){let Z=V0($,"pattern");if(Z)return Z;let Y=$.pattern,Q=KZ($.path||"."),J=k0(Q);if(J)return J;let z=$.include;if(await K6())return iU(Y,Q,z);return aU(Y,Q,z)}async function iU($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let K of p1)Q.push("--glob",`!${K}`);Q.push("-e",$,Z);let J=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe"}),z=await new Response(J.stdout).text(),X=await new Response(J.stderr).text();if(await J.exited,!z.trim()&&!X.trim())return"No matches found.";if(X.trim()&&!z.trim())return`Error: ${X.trim()}`;return nU(z,Z)}async function aU($,Z,Y){let Q;try{Q=new RegExp($)}catch(q){return`Error: invalid regex pattern: ${q instanceof Error?q.message:$}`}let J=Y||"**/*",z=new Bun.Glob(J),X=[],K=0,V=5000;for await(let q of z.scan({cwd:Z,onlyFiles:!0})){if(B2(q))continue;if(++K>V){X.push(`... (stopped after scanning ${V} files)`);break}let U=FJ(Z,q);try{let B=lU(U,"utf-8").split(`
492
- `);for(let M=0;M<B.length;M++)if(Q.test(B[M])){if(X.push(`${q}:${M+1}:${B[M]}`),X.length>=100)break}}catch{}if(X.length>=100)break}if(X.length===0)return"No matches found.";let G=X.slice(0,100).join(`
493
- `);if(X.length>100)G+=`
494
- ... (showing first 100 matches)`;return h$(G)}async function EJ($){let Z=V0($,"pattern");if(Z)return Z;let Y=$.pattern,Q=KZ($.path||"."),J=k0(Q);if(J)return J;let z=new Bun.Glob(Y),X=[];for await(let V of z.scan({cwd:Q,onlyFiles:!0})){if(B2(V))continue;if(X.push(V),X.length>=200)break}if(X.length===0)return"No files found.";let K=X.join(`
498
+ `).trim()}function P3($){let Z=W1($,"path");if(Z)return Z;let Y=xZ($.path),Q=y1(Y);if(Q)return Q;if(!_Z(Y))return`Error: file not found: ${Y}`;let z=DW(Y).size;if(z>bZ)return`Error: file too large (${V8(z)}). Max is ${V8(bZ)}.`;let X=A3(Y,"utf-8").split(`
499
+ `),K=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),q=X.slice(K-1,K-1+G).map((B,O)=>`${String(K+O).padStart(4)} ${B}`).join(`
500
+ `),H=X.length-(K-1+G);if(H>0)q+=`
501
+ ... (${H} more lines, total ${X.length})`;return o0(q)}function D3($,Z){let Y=W1($,"path");if(Y)return Y;let Q=xZ($.path),z=y1(Q);if(z)return z;let J=$.content,X=_Z(Q);Z.saveState(Q),P(Q,J);let K=J.split(`
502
+ `).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function T3($,Z){let Y=W1($,"path");if(Y)return Y;let Q=xZ($.path),z=y1(Q);if(z)return z;if(!_Z(Q))return`Error: file not found: ${Q}`;let J=A3(Q,"utf-8"),X=$.old_text,K=$.new_text,G=J.split(X).length-1;if(G===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(G>1)return`Error: old_text found ${G} times. It must be unique. Include more surrounding context.`;Z.saveState(Q);let V=J.split(X).join(K);P(Q,V);let U=X.split(`
503
+ `).length,q=K.split(`
504
+ `).length;return`Edited: ${Q} (replaced ${U} lines with ${q} lines)`}s();import{existsSync as TW,readdirSync as IW,readFileSync as SW,statSync as wW}from"fs";import{resolve as vZ,join as S3,sep as I3}from"path";async function w3($){let Z=W1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=vZ($.path||"."),z=y1(Q);if(z)return z;let J=$.include;if(await e9())return kW(Y,Q,J);return fW(Y,Q,J)}async function kW($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let K of s$)Q.push("--glob",`!${K}`);Q.push("-e",$,Z);let z=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe"}),J=await new Response(z.stdout).text(),X=await new Response(z.stderr).text();if(await z.exited,!J.trim()&&!X.trim())return"No matches found.";if(X.trim()&&!J.trim())return`Error: ${X.trim()}`;return bW(J,Z)}async function fW($,Z,Y){let Q;try{Q=new RegExp($)}catch(U){return`Error: invalid regex pattern: ${U instanceof Error?U.message:$}`}let z=Y||"**/*",J=new Bun.Glob(z),X=[],K=0,G=5000;for await(let U of J.scan({cwd:Z,onlyFiles:!0})){if(h7(U))continue;if(++K>G){X.push(`... (stopped after scanning ${G} files)`);break}let q=S3(Z,U);try{let B=SW(q,"utf-8").split(`
505
+ `);for(let O=0;O<B.length;O++)if(Q.test(B[O])){if(X.push(`${U}:${O+1}:${B[O]}`),X.length>=100)break}}catch{}if(X.length>=100)break}if(X.length===0)return"No matches found.";let V=X.slice(0,100).join(`
506
+ `);if(X.length>100)V+=`
507
+ ... (showing first 100 matches)`;return o0(V)}async function k3($){let Z=W1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=vZ($.path||"."),z=y1(Q);if(z)return z;let J=new Bun.Glob(Y),X=[];for await(let G of J.scan({cwd:Q,onlyFiles:!0})){if(h7(G))continue;if(X.push(G),X.length>=200)break}if(X.length===0)return"No files found.";let K=X.join(`
495
508
  `);if(X.length>=200)K+=`
496
- ... (showing first 200 files)`;return K}function LJ($){let Z=KZ($.path||"."),Y=k0(Z);if(Y)return Y;if(!dU(Z))return`Error: not found: ${Z}`;return cU(Z,{withFileTypes:!0}).sort((z,X)=>{if(z.isDirectory()!==X.isDirectory())return z.isDirectory()?-1:1;return z.name.localeCompare(X.name)}).map((z)=>{if(z.isDirectory())return`d ${z.name}/`;try{let X=oU(FJ(Z,z.name)),K=Z4(X.size);return`f ${z.name} ${K}`}catch{return`f ${z.name}`}}).join(`
497
- `)}function nU($,Z){let Y=process.cwd(),Q=Y+OJ,J=Z+OJ,X=$.trim().split(`
498
- `).map((G)=>{if(G.startsWith(Q))return"."+G.slice(Y.length).replace(/\\/g,"/");if(G.startsWith(J))return"."+G.slice(Z.length).replace(/\\/g,"/");return G}),K=X.length,V=X.slice(0,100).join(`
499
- `);if(K>100)V+=`
500
- ... (${K-100} more matches)`;return h$(V)}o();async function jJ($){let Z=V0($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),J=q1(),z=Bun.spawn([...J,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>z.kill(),Q*1000),[K,V]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),G=await z.exited;clearTimeout(X);let q="";if(K.trim())q+=K.trim();if(V.trim())q+=(q?`
509
+ ... (showing first 200 files)`;return K}function f3($){let Z=vZ($.path||"."),Y=y1(Z);if(Y)return Y;if(!TW(Z))return`Error: not found: ${Z}`;return IW(Z,{withFileTypes:!0}).sort((J,X)=>{if(J.isDirectory()!==X.isDirectory())return J.isDirectory()?-1:1;return J.name.localeCompare(X.name)}).map((J)=>{if(J.isDirectory())return`d ${J.name}/`;try{let X=wW(S3(Z,J.name)),K=V8(X.size);return`f ${J.name} ${K}`}catch{return`f ${J.name}`}}).join(`
510
+ `)}function bW($,Z){let Y=process.cwd(),Q=Y+I3,z=Z+I3,X=$.trim().split(`
511
+ `).map((V)=>{if(V.startsWith(Q))return"."+V.slice(Y.length).replace(/\\/g,"/");if(V.startsWith(z))return"."+V.slice(Z.length).replace(/\\/g,"/");return V}),K=X.length,G=X.slice(0,100).join(`
512
+ `);if(K>100)G+=`
513
+ ... (${K-100} more matches)`;return o0(G)}s();async function b3($){let Z=W1($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),z=B$(),J=Bun.spawn([...z,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>J.kill(),Q*1000),[K,G]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),V=await J.exited;clearTimeout(X);let U="";if(K.trim())U+=K.trim();if(G.trim())U+=(U?`
501
514
  `:"")+`STDERR:
502
- `+V.trim();if(G!==0)q+=(q?`
503
- `:"")+`Exit code: ${G}`;return h$(q||"(no output)")}async function DJ($){let Z=$.url,Y=$.method||"GET",Q=$.headers||{},J=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let z=JZ(Z);if(z)return z;try{let X=new AbortController,K=setTimeout(()=>X.abort(),30000),V=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Q},body:J&&Y!=="GET"&&Y!=="HEAD"?J:void 0,signal:X.signal});if(clearTimeout(K),V.status>=300&&V.status<400){let B=V.headers.get("location");if(!B)return`Status: ${V.status} (redirect with no location header)`;let M=JZ(B);if(M)return`Redirect blocked: ${M}`;return`Status: ${V.status} -> Redirect to: ${B}
504
- (Use fetch_url on the redirect target if needed)`}let G=`${V.status} ${V.statusText}`,q=V.headers.get("content-type")||"";if(Y==="HEAD"){let B=[...V.headers.entries()].map(([M,N])=>`${M}: ${N}`).join(`
505
- `);return`Status: ${G}
506
- ${B}`}let U=V.headers.get("content-length");if(U&&Number(U)>$4*2)return`Status: ${G}
515
+ `+G.trim();if(V!==0)U+=(U?`
516
+ `:"")+`Exit code: ${V}`;return o0(U||"(no output)")}async function y3($){let Z=$.url,Y=$.method||"GET",Q=$.headers||{},z=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let J=yZ(Z);if(J)return J;try{let X=new AbortController,K=setTimeout(()=>X.abort(),30000),G=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Q},body:z&&Y!=="GET"&&Y!=="HEAD"?z:void 0,signal:X.signal});if(clearTimeout(K),G.status>=300&&G.status<400){let B=G.headers.get("location");if(!B)return`Status: ${G.status} (redirect with no location header)`;let O=yZ(B);if(O)return`Redirect blocked: ${O}`;return`Status: ${G.status} -> Redirect to: ${B}
517
+ (Use fetch_url on the redirect target if needed)`}let V=`${G.status} ${G.statusText}`,U=G.headers.get("content-type")||"";if(Y==="HEAD"){let B=[...G.headers.entries()].map(([O,M])=>`${O}: ${M}`).join(`
518
+ `);return`Status: ${V}
519
+ ${B}`}let q=G.headers.get("content-length");if(q&&Number(q)>G8*2)return`Status: ${V}
507
520
 
508
- Error: response body too large (${U} bytes). Max is ${$4*2} bytes.`;let W=await V.text();if(q.includes("text/html")){let B=WJ(W);return h$(`Status: ${G}
521
+ Error: response body too large (${q} bytes). Max is ${G8*2} bytes.`;let H=await G.text();if(U.includes("text/html")){let B=j3(H);return o0(`Status: ${V}
509
522
 
510
- ${B}`)}return h$(`Status: ${G}
523
+ ${B}`)}return o0(`Status: ${V}
511
524
 
512
- ${W}`)}catch(X){if(X instanceof Error&&X.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${X instanceof Error?X.message:String(X)}`}}async function PJ($,Z,Y,Q,J){let z=performance.now();try{let X=await rU($,Z,Y,Q,J);return setImmediate(()=>{d9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-z),success:!X.startsWith("Error:")})}),X}catch(X){return setImmediate(()=>{d9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-z),success:!1})}),`Error: ${X instanceof Error?X.message:String(X)}`}}async function rU($,Z,Y,Q,J){switch($){case"read_file":return MJ(Z);case"write_file":return CJ(Z,Y);case"edit_file":return NJ(Z,Y);case"search_files":return await RJ(Z);case"find_files":return await EJ(Z);case"list_directory":return LJ(Z);case"run_command":return await jJ(Z);case"fetch_url":return await DJ(Z)}let z=await cQ($,Z);if(z!==null)return z;let X=nQ($,Z);if(X!==null)return X;let K=await GJ($,Z);if(K!==null)return K;let V=await dQ($,Z,J);if(V!==null)return V;let G=Q.find((q)=>q.name===$);if(G)return await YZ(G,Z);return`Error: unknown tool "${$}"`}var g1=new e2,TJ=[];function VZ($){TJ=$}var IJ=null;function GZ($){IJ=$}var AJ=!1;function qZ(){if(AJ)return;if(AJ=!0,L)k.push(...x8),k.push(...G7),k.push(...q7);else k.push(U7);k.push(...R5),k.push(...E5),k.push(...L5),k.push(...j5),k.push(D5),k.push(...P5),k.push(...A5),k.push(...T5),k.push(...d5),k.push(...b5),k.push(...x5),k.push(...I5),k.push(...S5),k.push(...w5),k.push(...y5),k.push(...k5),k.push(..._5),k.push(...c5)}async function l5($,Z){return PJ($,Z,g1,TJ,IJ)}var sU=new Set([429,500,502,503,529]);async function wJ($,Z={}){let Y=Z.maxRetries??3,Q=Z.baseDelayMs??1000,J;for(let z=0;z<=Y;z++)try{return await $()}catch(X){if(J=X,Z.signal?.aborted)throw X;if(z>=Y)throw X;if(tU(X)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(z+1,500,"Auth refreshed, retrying..."),await SJ(500,Z.signal);continue}}if(!eU(X))throw X;let V=$H(X)??Q*Math.pow(2,z),G=X instanceof Error?X.message:String(X);Z.onRetry?.(z+1,V,G),await SJ(V,Z.signal)}throw J}function tU($){if(!($ instanceof Error))return!1;return $.status===401}function eU($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&sU.has(Z))return!0;let Y=$.message.toLowerCase();if(Y.includes("econnreset")||Y.includes("econnrefused"))return!0;if(Y.includes("etimedout")||Y.includes("socket hang up"))return!0;if(Y.includes("overloaded"))return!0;return!1}function $H($){let Z=$.headers;if(!Z)return null;let Y=Z["retry-after"];if(!Y)return null;let Q=Number(Y);if(!isNaN(Q)&&Q>0)return Math.min(Q,60)*1000;return null}function SJ($,Z){return new Promise((Y,Q)=>{let J=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(J),Q(Error("Aborted"))},{once:!0})})}var ZH={haiku:200000,sonnet:200000,opus:200000};function b0($){return Math.ceil($.length/3.5)}function UZ($){let Z=0;for(let Y of $){if(Z+=b0(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=b0(JSON.stringify(Q.input)),Z+=b0(Q.result);Z+=10}return Z}function HZ($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(ZH))if(Z.includes(Y))return Q;return 200000}function kJ($,Z,Y){let Q=HZ(Z)-20000-Y;if(UZ($)<=Q)return $;let z=[],X=Q,K=[...$].reverse(),V=[];for(let q of K){let U=b0(q.content)+(q.toolCalls?.reduce((W,B)=>W+b0(JSON.stringify(B.input))+b0(B.result),0)??0)+10;if(X-U<0)break;X-=U,V.unshift(q)}let G=$.length-V.length;if(G>0)z.push({role:"user",content:`[Note: ${G} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return z.push(...V),z}function bJ($,Z,Y){let Q=HZ(Z)-20000-Y;return UZ($)>Q*0.7}function yJ($,Z,Y){let Q=HZ(Z)-20000-Y;if(UZ($)<=Q*0.7)return null;let z=Math.max(4,Math.floor($.length*0.3)),X=$.slice(0,$.length-z),K=$.slice($.length-z);if(X.length<2)return null;return{toSummarize:X,toKeep:K}}function _J($){return`Summarize this conversation concisely. Focus on:
525
+ ${H}`)}catch(X){if(X instanceof Error&&X.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${X instanceof Error?X.message:String(X)}`}}async function _3($,Z,Y,Q,z){let J=performance.now();try{let X=await yW($,Z,Y,Q,z);return setImmediate(()=>{OZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!X.startsWith("Error:")})}),X}catch(X){return setImmediate(()=>{OZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${X instanceof Error?X.message:String(X)}`}}async function yW($,Z,Y,Q,z){switch($){case"read_file":return P3(Z);case"write_file":return D3(Z,Y);case"edit_file":return T3(Z,Y);case"search_files":return await w3(Z);case"find_files":return await k3(Z);case"list_directory":return f3(Z);case"run_command":return await b3(Z);case"fetch_url":return await y3(Z)}let J=await vJ($,Z);if(J!==null)return J;let X=pJ($,Z);if(X!==null)return X;let K=await Y3($,Z);if(K!==null)return K;let G=await xJ($,Z,z);if(G!==null)return G;let V=await W3($,Z);if(V!==null)return V;let U=Q.find((q)=>q.name===$);if(U)return await J7(U,Z);return`Error: unknown tool "${$}"`}var o$=new A6,v3=[];function hZ($){v3=$}var h3=null;function gZ($){h3=$}var x3=!1;function mZ(){if(x3)return;if(x3=!0,j)y.push(...d2),y.push(...j4),y.push(...A4);else y.push(P4);y.push(...y5),y.push(..._5),y.push(...x5),y.push(...v5),y.push(h5),y.push(...g5),y.push(...m5),y.push(...u5),y.push(...Q7),y.push(...o5),y.push(...n5),y.push(...p5),y.push(...d5),y.push(...c5),y.push(...i5),y.push(...l5),y.push(...r5),y.push(...z7)}async function V7($,Z){return _3($,Z,o$,v3,h3)}var _W=new Set([429,500,502,503,529]);async function m3($,Z={}){let Y=Z.maxRetries??3,Q=Z.baseDelayMs??1000,z;for(let J=0;J<=Y;J++)try{return await $()}catch(X){if(z=X,Z.signal?.aborted)throw X;if(J>=Y)throw X;if(xW(X)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(J+1,500,"Auth refreshed, retrying..."),await g3(500,Z.signal);continue}}if(!vW(X))throw X;let G=hW(X)??Q*Math.pow(2,J),V=X instanceof Error?X.message:String(X);Z.onRetry?.(J+1,G,V),await g3(G,Z.signal)}throw z}function xW($){if(!($ instanceof Error))return!1;return $.status===401}function vW($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&_W.has(Z))return!0;let Y=$.message.toLowerCase();if(Y.includes("econnreset")||Y.includes("econnrefused"))return!0;if(Y.includes("etimedout")||Y.includes("socket hang up"))return!0;if(Y.includes("overloaded"))return!0;return!1}function hW($){let Z=$.headers;if(!Z)return null;let Y=Z["retry-after"];if(!Y)return null;let Q=Number(Y);if(!isNaN(Q)&&Q>0)return Math.min(Q,60)*1000;return null}function g3($,Z){return new Promise((Y,Q)=>{let z=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(z),Q(Error("Aborted"))},{once:!0})})}var gW={haiku:200000,sonnet:200000,opus:200000};function _1($){return Math.ceil($.length/3.5)}function uZ($){let Z=0;for(let Y of $){if(Z+=_1(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=_1(JSON.stringify(Q.input)),Z+=_1(Q.result);Z+=10}return Z}function pZ($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(gW))if(Z.includes(Y))return Q;return 200000}function u3($,Z,Y){let Q=pZ(Z)-20000-Y;if(uZ($)<=Q)return $;let J=[],X=Q,K=[...$].reverse(),G=[];for(let U of K){let q=_1(U.content)+(U.toolCalls?.reduce((H,B)=>H+_1(JSON.stringify(B.input))+_1(B.result),0)??0)+10;if(X-q<0)break;X-=q,G.unshift(U)}let V=$.length-G.length;if(V>0)J.push({role:"user",content:`[Note: ${V} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return J.push(...G),J}function p3($,Z,Y){let Q=pZ(Z)-20000-Y;return uZ($)>Q*0.7}function d3($,Z,Y){let Q=pZ(Z)-20000-Y;if(uZ($)<=Q*0.7)return null;let J=Math.max(4,Math.floor($.length*0.3)),X=$.slice(0,$.length-J),K=$.slice($.length-J);if(X.length<2)return null;return{toSummarize:X,toKeep:K}}function c3($){return`Summarize this conversation concisely. Focus on:
513
526
  1. Key decisions made
514
527
  2. Files created or modified
515
528
  3. Important context the user shared
@@ -519,34 +532,34 @@ Be brief but preserve actionable information. Output ONLY the summary.
519
532
 
520
533
  ---
521
534
  ${$.map((Y)=>{let Q=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)Q+=`
522
- Tools used: ${Y.toolCalls.map((J)=>J.name).join(", ")}`;return Q}).join(`
535
+ Tools used: ${Y.toolCalls.map((z)=>z.name).join(", ")}`;return Q}).join(`
523
536
 
524
- `)}`}function xJ($,Z=2000){return $.map((Y)=>{if(!Y.toolCalls?.length)return Y;let Q=Y.toolCalls.map((J)=>{if(J.result.length<=Z)return J;let z=J.result.split(`
525
- `),X=Math.min(10,z.length),K=Math.min(5,Math.max(0,z.length-X)),V=z.length-X-K,G=[...z.slice(0,X)];if(V>0)G.push(`... (${V} lines omitted)`);if(K>0)G.push(...z.slice(-K));let q=G.join(`
526
- `);return{...J,result:q}});return{...Y,toolCalls:Q}})}var YH=[/OPENAI_API_KEY\s*=/i,/AWS_SECRET_ACCESS_KEY\s*=/i,/AWS_SESSION_TOKEN\s*=/i,/GITHUB_TOKEN\s*=/i,/GH_TOKEN\s*=/i,/SLACK_TOKEN\s*=/i,/SLACK_BOT_TOKEN\s*=/i,/DATABASE_URL\s*=.*:\/\/.+:.+@/i,/REDIS_URL\s*=.*:\/\/.+:.+@/i,/password\s*=\s*["'][^"']{4,}["']/i,/secret\s*=\s*["'][^"']{4,}["']/i,/Bearer\s+[A-Za-z0-9\-._~+\/]{20,}/i,/sk-[A-Za-z0-9]{20,}/,/ghp_[A-Za-z0-9]{36,}/,/xoxb-[0-9]{10,}/];function WZ($){for(let Z of YH)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var QH=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],JH=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function vJ($){return(process.platform==="win32"?QH:JH).some((Y)=>Y.test($))}var zH=[/\brm\s+(-rf?|--recursive)/i,/\brmdir\s/i,/\bdel\s+\/[sS]/i,/\bRemove-Item\s.*-Recurse/i,/\bformat\s+[a-z]:/i,/\bgit\s+(push\s+--force|reset\s+--hard|clean\s+-fd)/i,/\bdrop\s+(table|database)/i,/\btruncate\s+table/i,/\bchmod\s+777/i,/\bchown\s+-R/i,/\bcurl\s.*\|\s*(bash|sh)/i,/\bwget\s.*\|\s*(bash|sh)/i,/\bnpm\s+publish/i,/\bsudo\s/i,/\bkill\s+-9/i,/\bshutdown/i,/\breboot/i],XH=[/\bgit\s+push/i,/\bgit\s+commit/i,/\bnpm\s+install/i,/\bbun\s+(install|add)/i,/\bpip\s+install/i,/\bcargo\s+install/i,/\bmkdir\s+-p/i];function fJ($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":case"read_clipboard_content":case"analyze_screen_context":case"memory_status":case"recall_memory":return{level:"safe"};case"write_file":{let Y=String(Z.path||"");if(vJ(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),J=WZ(Q);if(J)return{level:"dangerous",reason:`content contains potential secret: ${J}`};return{level:"moderate",reason:`write ${Y}`}}case"edit_file":{let Y=String(Z.path||"");if(vJ(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),J=WZ(Q);if(J)return{level:"dangerous",reason:`new_text contains potential secret: ${J}`};return{level:"moderate",reason:`edit ${Y}`}}case"run_command":{let Y=String(Z.command||""),Q=WZ(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let J of zH)if(J.test(Y))return{level:"dangerous",reason:Y};for(let J of XH)if(J.test(Y))return{level:"moderate",reason:Y};return{level:"moderate",reason:Y}}case"execute_powershell_script":return{level:"dangerous",reason:"PowerShell script execution"};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function BZ($){if(!($ instanceof Error))return String($);let{status:Z,message:Y}=$;if(Z)switch(Z){case 400:if(Y.includes("context_length")||Y.includes("too many tokens"))return"Message too long for the model's context window. Try /clear to start fresh or use a shorter prompt.";return`Bad request: ${KH(Y)}`;case 401:return"Authentication failed. Your subscription token may be expired.\nTry: Run `claude` to refresh subscription credentials.";case 403:return`Access denied. Your subscription may not have permission for this model.
527
- Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${VH(Y)}" may not exist or be unavailable.
537
+ `)}`}function l3($,Z=2000){return $.map((Y)=>{if(!Y.toolCalls?.length)return Y;let Q=Y.toolCalls.map((z)=>{if(z.result.length<=Z)return z;let J=z.result.split(`
538
+ `),X=Math.min(10,J.length),K=Math.min(5,Math.max(0,J.length-X)),G=J.length-X-K,V=[...J.slice(0,X)];if(G>0)V.push(`... (${G} lines omitted)`);if(K>0)V.push(...J.slice(-K));let U=V.join(`
539
+ `);return{...z,result:U}});return{...Y,toolCalls:Q}})}var mW=[/OPENAI_API_KEY\s*=/i,/AWS_SECRET_ACCESS_KEY\s*=/i,/AWS_SESSION_TOKEN\s*=/i,/GITHUB_TOKEN\s*=/i,/GH_TOKEN\s*=/i,/SLACK_TOKEN\s*=/i,/SLACK_BOT_TOKEN\s*=/i,/DATABASE_URL\s*=.*:\/\/.+:.+@/i,/REDIS_URL\s*=.*:\/\/.+:.+@/i,/password\s*=\s*["'][^"']{4,}["']/i,/secret\s*=\s*["'][^"']{4,}["']/i,/Bearer\s+[A-Za-z0-9\-._~+\/]{20,}/i,/sk-[A-Za-z0-9]{20,}/,/ghp_[A-Za-z0-9]{36,}/,/xoxb-[0-9]{10,}/];function dZ($){for(let Z of mW)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var uW=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],pW=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function o3($){return(process.platform==="win32"?uW:pW).some((Y)=>Y.test($))}var dW=[/\brm\s+(-rf?|--recursive)/i,/\brmdir\s/i,/\bdel\s+\/[sS]/i,/\bRemove-Item\s.*-Recurse/i,/\bformat\s+[a-z]:/i,/\bgit\s+(push\s+--force|reset\s+--hard|clean\s+-fd)/i,/\bdrop\s+(table|database)/i,/\btruncate\s+table/i,/\bchmod\s+777/i,/\bchown\s+-R/i,/\bcurl\s.*\|\s*(bash|sh)/i,/\bwget\s.*\|\s*(bash|sh)/i,/\bnpm\s+publish/i,/\bsudo\s/i,/\bkill\s+-9/i,/\bshutdown/i,/\breboot/i],cW=[/\bgit\s+push/i,/\bgit\s+commit/i,/\bnpm\s+install/i,/\bbun\s+(install|add)/i,/\bpip\s+install/i,/\bcargo\s+install/i,/\bmkdir\s+-p/i];function i3($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":case"read_clipboard_content":case"analyze_screen_context":case"memory_status":case"recall_memory":return{level:"safe"};case"write_file":{let Y=String(Z.path||"");if(o3(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),z=dZ(Q);if(z)return{level:"dangerous",reason:`content contains potential secret: ${z}`};return{level:"moderate",reason:`write ${Y}`}}case"edit_file":{let Y=String(Z.path||"");if(o3(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),z=dZ(Q);if(z)return{level:"dangerous",reason:`new_text contains potential secret: ${z}`};return{level:"moderate",reason:`edit ${Y}`}}case"run_command":{let Y=String(Z.command||""),Q=dZ(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let z of dW)if(z.test(Y))return{level:"dangerous",reason:Y};for(let z of cW)if(z.test(Y))return{level:"moderate",reason:Y};return{level:"moderate",reason:Y}}case"execute_powershell_script":return{level:"dangerous",reason:"PowerShell script execution"};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function cZ($){if(!($ instanceof Error))return String($);let{status:Z,message:Y}=$;if(Z)switch(Z){case 400:if(Y.includes("context_length")||Y.includes("too many tokens"))return"Message too long for the model's context window. Try /clear to start fresh or use a shorter prompt.";return`Bad request: ${lW(Y)}`;case 401:return"Authentication failed. Your subscription token may be expired.\nTry: Run `claude` to refresh subscription credentials.";case 403:return`Access denied. Your subscription may not have permission for this model.
540
+ Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${oW(Y)}" may not exist or be unavailable.
528
541
  Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
529
- The request will be retried automatically. If this persists, wait a minute.`;case 500:case 502:case 503:return"Anthropic API is temporarily unavailable. Retrying automatically...";case 529:return"Anthropic API is overloaded. Retrying with backoff..."}let Q=Y.toLowerCase();if(Q.includes("econnrefused")||Q.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(Q.includes("etimedout")||Q.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(Q.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(Q.includes("expired")||Q.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return Y}function KH($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function VH($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function hJ($,Z,Y){if($==="auto")return!1;if(Y==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command","execute_powershell_script"].includes(Z);if($==="confirm-all")return Y!=="safe";return!1}function gJ($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let Y=String(Z.command||"");return`Run: ${Y.length>60?Y.slice(0,57)+"...":Y}`}case"execute_powershell_script":{let Y=String(Z.script||""),Q=Y.split(`
530
- `)[0]||"",J=Y.split(`
531
- `).length;return`PowerShell (${J} line${J>1?"s":""}): ${Q.length>50?Q.slice(0,47)+"...":Q}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function mJ($,Z,Y=20){let Q=$.split(`
532
- `),J=Z.split(`
533
- `),z=[],X=Q.slice(0,Y);for(let V of X)z.push(` \x1B[31m- ${V}\x1B[0m`);if(Q.length>Y)z.push(` \x1B[2m ... (${Q.length-Y} more removed)\x1B[0m`);let K=J.slice(0,Y);for(let V of K)z.push(` \x1B[32m+ ${V}\x1B[0m`);if(J.length>Y)z.push(` \x1B[2m ... (${J.length-Y} more added)\x1B[0m`);return z}class MZ{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new x$({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new x$({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=xJ($),J=b0(Z);if(bJ(Q,this.model,J)){let V=yJ(Q,this.model,J);if(V)try{let q={role:"assistant",content:`[Conversation summary]
534
- ${await this.generateSummary(V.toSummarize)}`,timestamp:Date.now()};Q=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},q,...V.toKeep]}catch{}}let z=kJ(Q,this.model,J),X=GH(z),K=Y?k:void 0;try{yield*this.streamLoop(X,Z,K)}catch(V){yield{type:"error",error:BZ(V)}}}async generateSummary($){let Z=_J($),Q=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((J)=>J.type==="text");return Q?.type==="text"?Q.text:"Summary unavailable."}async*streamLoop($,Z,Y){let J=[...$],z=0;while(z++<25){let X;try{X=await wJ(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:J,...Y?.length?{tools:Y}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(q){yield{type:"error",error:BZ(q)};return}for await(let q of X)if(q.type==="content_block_delta"&&q.delta.type==="text_delta")yield{type:"text",text:q.delta.text};let K=await X.finalMessage();if(K.usage)yield{type:"usage",inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens};if(K.stop_reason!=="tool_use"){yield{type:"done"};return}let V=K.content.filter((q)=>q.type==="tool_use");J.push({role:"assistant",content:K.content});let G=[];for(let q of V){let U=q.input,W=fJ(q.name,U);if(W.level==="dangerous"){yield{type:"tool_blocked",id:q.id,name:q.name,reason:`Blocked dangerous operation: ${W.reason}`},G.push({type:"tool_result",tool_use_id:q.id,content:`Error: Operation blocked for safety. Reason: ${W.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&hJ(this.approvalMode,q.name,W.level)&&this.approvalCallback){if(yield{type:"tool_call",id:q.id,name:q.name,input:q.input},!await this.approvalCallback(q.name,U,W.level)){yield{type:"tool_blocked",id:q.id,name:q.name,reason:"Rejected by user"},G.push({type:"tool_result",tool_use_id:q.id,content:"Error: User rejected this operation."});continue}let N=await l5(q.name,U);yield{type:"tool_result",id:q.id,name:q.name,result:N},G.push({type:"tool_result",tool_use_id:q.id,content:N});continue}yield{type:"tool_call",id:q.id,name:q.name,input:q.input};let B=await l5(q.name,U);yield{type:"tool_result",id:q.id,name:q.name,result:B},G.push({type:"tool_result",tool_use_id:q.id,content:B})}J.push({role:"user",content:G})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function GH($){let Z=[];for(let Y of $)if(Y.role==="user")if(Y.images?.length){let Q=Y.images.map((J)=>({type:"image",source:{type:"base64",media_type:J.mediaType,data:J.base64}}));Q.push({type:"text",text:Y.content}),Z.push({role:"user",content:Q})}else Z.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.toolCalls?.length){let Q=[];if(Y.content)Q.push({type:"text",text:Y.content});for(let J of Y.toolCalls)Q.push({type:"tool_use",id:J.id,name:J.name,input:J.input});Z.push({role:"assistant",content:Q}),Z.push({role:"user",content:Y.toolCalls.map((J)=>({type:"tool_result",tool_use_id:J.id,content:J.result}))})}else Z.push({role:"assistant",content:Y.content});return Z}class CZ{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,Y){if(this.name=$,this.model=Z,this.maxTokens=Y,$==="ollama")this.apiKey="ollama",this.baseUrl=process.env.OLLAMA_BASE_URL||"http://localhost:11434/v1";else this.apiKey=process.env.OPENAI_API_KEY||"",this.baseUrl=process.env.OPENAI_BASE_URL||"https://api.openai.com/v1"}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){if(!this.apiKey&&this.name!=="ollama"){yield{type:"error",error:"No API key found. Set OPENAI_API_KEY env var."};return}let Q=[{role:"system",content:Z},...$.map((J)=>({role:J.role,content:J.content}))];try{let J=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:Q,max_tokens:this.maxTokens,stream:!0})});if(!J.ok){let q=await J.text();yield{type:"error",error:`${this.name} API error ${J.status}: ${q.slice(0,200)}`};return}if(!J.body){yield{type:"error",error:"No response body"};return}let z=J.body.getReader(),X=new TextDecoder,K="",V=Z.length+$.reduce((q,U)=>q+U.content.length,0),G=0;while(!0){let{done:q,value:U}=await z.read();if(q)break;K+=X.decode(U,{stream:!0});let W=K.split(`
535
- `);K=W.pop()||"";for(let B of W){if(!B.startsWith("data: "))continue;let M=B.slice(6).trim();if(M==="[DONE]")continue;try{let F=JSON.parse(M).choices?.[0]?.delta;if(F?.content)yield{type:"text",text:F.content},G+=F.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(V/3.5),outputTokens:Math.ceil(G/3.5)},yield{type:"done"}}catch(J){yield{type:"error",error:J instanceof Error?J.message:String(J)}}}}function o5($){if($.includes(":")){let[Y,...Q]=$.split(":");return{provider:Y.toLowerCase(),model:Q.join(":")}}let Z=$.toLowerCase();if(Z.startsWith("gpt-")||Z.startsWith("o1")||Z.startsWith("o3"))return{provider:"openai",model:$};if(Z.startsWith("llama")||Z.startsWith("mistral")||Z.startsWith("codellama")||Z.startsWith("deepseek"))return{provider:"ollama",model:$};return{provider:"anthropic",model:$}}var qH={anthropic:{name:"Anthropic",envKey:"",description:"Claude models (default, via subscription)"},openai:{name:"OpenAI",envKey:"OPENAI_API_KEY",description:"GPT and o-series models"},ollama:{name:"Ollama",envKey:"",description:"Local models via Ollama (no API key needed)"}};function uJ(){let $=["Providers:"];for(let[Z,Y]of Object.entries(qH)){let Q=Y.envKey?` (${Y.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${Y.description}${Q}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
536
- `)}function pJ($,Z,Y,Q){let{provider:J,model:z}=o5(Z);if(J==="openai"||J==="ollama")return new CZ(J,z,Y);let X=new MZ($.auth.token,Z,Y,Q);return X.setAuthRefresh(()=>{let K=g0();if(K&&K.token!==$.auth.token)return $.auth=K,X.updateToken(K.token),!0;return!1}),X}g();import{existsSync as D$,mkdirSync as dJ,readdirSync as cJ,readFileSync as i5,unlinkSync as lJ,renameSync as NZ}from"fs";import{join as Q$}from"path";class OZ{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=Q$($,"sessions"),this.archiveDir=Q$($,"sessions","archive"),!D$(this.sessionsDir))dJ(this.sessionsDir,{recursive:!0});if(!D$(this.archiveDir))dJ(this.archiveDir,{recursive:!0});this.current=this.loadOrCreate("default")}get session(){return this.current}get messages(){return this.current.messages}addMessage($){this.current.messages.push($),this.current.updated=Date.now(),this.save()}trimHistory($){if(this.current.messages.length>$)this.current.messages=this.current.messages.slice(-$),this.save()}clear(){this.current.messages=[],this.current.updated=Date.now(),this.save()}popMessages($){let Z=this.current.messages.splice(-$,$);return this.current.updated=Date.now(),this.save(),Z}switchTo($){return this.current=this.loadOrCreate($),this.saveLastSession(),this.current}list(){if(!D$(this.sessionsDir))return[];return cJ(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=Q$(this.sessionsDir,`${$}.json`);if(!D$(Z))return null;try{let Y=JSON.parse(i5(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=Q$(this.sessionsDir,`${$}.json`);if(D$(Z))return lJ(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=Q$(this.sessionsDir,`${$}.json`);return P(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=Q$(this.sessionsDir,`${$}.json`);if(!D$(Z))return!1;let Y=Q$(this.archiveDir,`${$}.json`);return NZ(Z,Y),!0}archiveAll(){let $=[],Z=this.list().filter((Y)=>Y!==this.current.name);for(let Y of Z)if(this.archive(Y))$.push(Y);return $}unarchive($){let Z=Q$(this.archiveDir,`${$}.json`);if(!D$(Z))return!1;let Y=Q$(this.sessionsDir,`${$}.json`);return NZ(Z,Y),!0}listArchived(){if(!D$(this.archiveDir))return[];return cJ(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=Q$(this.archiveDir,`${$}.json`);if(!D$(Z))return null;try{let Y=JSON.parse(i5(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=Q$(this.archiveDir,`${$}.json`);if(D$(Z))return lJ(Z),!0;return!1}loadOrCreate($){let Z=Q$(this.sessionsDir,`${$}.json`);if(D$(Z))try{return JSON.parse(i5(Z,"utf-8"))}catch{let Q=Q$(this.sessionsDir,`${$}.corrupt.json`);try{NZ(Z,Q)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return P(Z,JSON.stringify(Y,null,2)),Y}saveLastSession(){let $=Q$(this.sessionsDir,"..","last-session.txt");P($,this.current.name)}getLastSession(){let $=Q$(this.sessionsDir,"..","last-session.txt");if(!D$($))return null;try{let Z=i5($,"utf-8").trim();if(!Z||!D$(Q$(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}save(){let $=Q$(this.sessionsDir,`${this.current.name}.json`);P($,JSON.stringify(this.current,null,2))}}import{existsSync as aJ,readdirSync as BH,readFileSync as nJ}from"fs";import{join as RZ}from"path";o();import{existsSync as FZ,readFileSync as oJ}from"fs";import{basename as UH,join as a5}from"path";function iJ(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${X6()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),L)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=HH($);if(Y)Z.push(`Project: ${Y}`);let Q=WH($);if(Q)Z.push(Q);return Z.join(`
537
- `)}function HH($){let Z=[["package.json","Node.js/JavaScript"],["Cargo.toml","Rust"],["go.mod","Go"],["pyproject.toml","Python"],["requirements.txt","Python"],["pom.xml","Java (Maven)"],["build.gradle","Java (Gradle)"],["Gemfile","Ruby"],["composer.json","PHP"],["Makefile","Make"],["CMakeLists.txt","C/C++ (CMake)"],["Dockerfile","Docker"]],Y=[];for(let[J,z]of Z)if(FZ(a5($,J)))Y.push(z);if(Y.length===0)return null;let Q=UH($);try{let J=a5($,"package.json");if(FZ(J)){let z=JSON.parse(oJ(J,"utf-8"));if(z.name)Q=z.name}}catch(J){x.debug("Failed to parse package.json for project name",{error:J})}return`Project: ${Q} (${Y.join(", ")})`}function WH($){if(!FZ(a5($,".git")))return null;let Z=[];try{let Y=oJ(a5($,".git","HEAD"),"utf-8").trim(),Q=Y.startsWith("ref: refs/heads/")?Y.slice(16):Y.slice(0,8);Z.push(`Git branch: ${Q}`)}catch{return Z.push("Git: initialized"),Z.join(`
538
- `)}try{let Y=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q)Z.push(`Last commit: ${Q}`)}}catch(Y){x.debug("git log failed",{error:Y})}try{let Y=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q){let J=Q.split(`
539
- `),z=J.slice(0,15);if(J.length>15)z.push(`... and ${J.length-15} more files`);Z.push(`Uncommitted changes:
540
- `+z.join(`
541
- `))}}}catch(Y){x.debug("git diff --stat failed",{error:Y})}try{let Y=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q){let J=Q.split(`
542
- `).slice(0,10);Z.push(`Staged:
542
+ The request will be retried automatically. If this persists, wait a minute.`;case 500:case 502:case 503:return"Anthropic API is temporarily unavailable. Retrying automatically...";case 529:return"Anthropic API is overloaded. Retrying with backoff..."}let Q=Y.toLowerCase();if(Q.includes("econnrefused")||Q.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(Q.includes("etimedout")||Q.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(Q.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(Q.includes("expired")||Q.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return Y}function lW($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function oW($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function r3($,Z,Y){if($==="auto")return!1;if(Y==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command","execute_powershell_script"].includes(Z);if($==="confirm-all")return Y!=="safe";return!1}function n3($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let Y=String(Z.command||"");return`Run: ${Y.length>60?Y.slice(0,57)+"...":Y}`}case"execute_powershell_script":{let Y=String(Z.script||""),Q=Y.split(`
543
+ `)[0]||"",z=Y.split(`
544
+ `).length;return`PowerShell (${z} line${z>1?"s":""}): ${Q.length>50?Q.slice(0,47)+"...":Q}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function a3($,Z,Y=20){let Q=$.split(`
545
+ `),z=Z.split(`
546
+ `),J=[],X=Q.slice(0,Y);for(let G of X)J.push(` \x1B[31m- ${G}\x1B[0m`);if(Q.length>Y)J.push(` \x1B[2m ... (${Q.length-Y} more removed)\x1B[0m`);let K=z.slice(0,Y);for(let G of K)J.push(` \x1B[32m+ ${G}\x1B[0m`);if(z.length>Y)J.push(` \x1B[2m ... (${z.length-Y} more added)\x1B[0m`);return J}class lZ{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new d0({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new d0({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=l3($),z=_1(Z);if(p3(Q,this.model,z)){let G=d3(Q,this.model,z);if(G)try{let U={role:"assistant",content:`[Conversation summary]
547
+ ${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};Q=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},U,...G.toKeep]}catch{}}let J=u3(Q,this.model,z),X=iW(J),K=Y?y:void 0;try{yield*this.streamLoop(X,Z,K)}catch(G){yield{type:"error",error:cZ(G)}}}async generateSummary($){let Z=c3($),Q=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((z)=>z.type==="text");return Q?.type==="text"?Q.text:"Summary unavailable."}async*streamLoop($,Z,Y){let z=[...$],J=0;while(J++<25){let X;try{X=await m3(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:z,...Y?.length?{tools:Y}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(U){yield{type:"error",error:cZ(U)};return}for await(let U of X)if(U.type==="content_block_delta"&&U.delta.type==="text_delta")yield{type:"text",text:U.delta.text};let K=await X.finalMessage();if(K.usage)yield{type:"usage",inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens};if(K.stop_reason!=="tool_use"){yield{type:"done"};return}let G=K.content.filter((U)=>U.type==="tool_use");z.push({role:"assistant",content:K.content});let V=[];for(let U of G){let q=U.input,H=i3(U.name,q);if(H.level==="dangerous"){yield{type:"tool_blocked",id:U.id,name:U.name,reason:`Blocked dangerous operation: ${H.reason}`},V.push({type:"tool_result",tool_use_id:U.id,content:`Error: Operation blocked for safety. Reason: ${H.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&r3(this.approvalMode,U.name,H.level)&&this.approvalCallback){if(yield{type:"tool_call",id:U.id,name:U.name,input:U.input},!await this.approvalCallback(U.name,q,H.level)){yield{type:"tool_blocked",id:U.id,name:U.name,reason:"Rejected by user"},V.push({type:"tool_result",tool_use_id:U.id,content:"Error: User rejected this operation."});continue}let M=await V7(U.name,q);yield{type:"tool_result",id:U.id,name:U.name,result:M},V.push({type:"tool_result",tool_use_id:U.id,content:M});continue}yield{type:"tool_call",id:U.id,name:U.name,input:U.input};let B=await V7(U.name,q);yield{type:"tool_result",id:U.id,name:U.name,result:B},V.push({type:"tool_result",tool_use_id:U.id,content:B})}z.push({role:"user",content:V})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function iW($){let Z=[];for(let Y of $)if(Y.role==="user")if(Y.images?.length){let Q=Y.images.map((z)=>({type:"image",source:{type:"base64",media_type:z.mediaType,data:z.base64}}));Q.push({type:"text",text:Y.content}),Z.push({role:"user",content:Q})}else Z.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.toolCalls?.length){let Q=[];if(Y.content)Q.push({type:"text",text:Y.content});for(let z of Y.toolCalls)Q.push({type:"tool_use",id:z.id,name:z.name,input:z.input});Z.push({role:"assistant",content:Q}),Z.push({role:"user",content:Y.toolCalls.map((z)=>({type:"tool_result",tool_use_id:z.id,content:z.result}))})}else Z.push({role:"assistant",content:Y.content});return Z}class oZ{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,Y){if(this.name=$,this.model=Z,this.maxTokens=Y,$==="ollama")this.apiKey="ollama",this.baseUrl=process.env.OLLAMA_BASE_URL||"http://localhost:11434/v1";else this.apiKey=process.env.OPENAI_API_KEY||"",this.baseUrl=process.env.OPENAI_BASE_URL||"https://api.openai.com/v1"}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){if(!this.apiKey&&this.name!=="ollama"){yield{type:"error",error:"No API key found. Set OPENAI_API_KEY env var."};return}let Q=[{role:"system",content:Z},...$.map((z)=>({role:z.role,content:z.content}))];try{let z=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:Q,max_tokens:this.maxTokens,stream:!0})});if(!z.ok){let U=await z.text();yield{type:"error",error:`${this.name} API error ${z.status}: ${U.slice(0,200)}`};return}if(!z.body){yield{type:"error",error:"No response body"};return}let J=z.body.getReader(),X=new TextDecoder,K="",G=Z.length+$.reduce((U,q)=>U+q.content.length,0),V=0;while(!0){let{done:U,value:q}=await J.read();if(U)break;K+=X.decode(q,{stream:!0});let H=K.split(`
548
+ `);K=H.pop()||"";for(let B of H){if(!B.startsWith("data: "))continue;let O=B.slice(6).trim();if(O==="[DONE]")continue;try{let C=JSON.parse(O).choices?.[0]?.delta;if(C?.content)yield{type:"text",text:C.content},V+=C.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(G/3.5),outputTokens:Math.ceil(V/3.5)},yield{type:"done"}}catch(z){yield{type:"error",error:z instanceof Error?z.message:String(z)}}}}function U7($){if($.includes(":")){let[Y,...Q]=$.split(":");return{provider:Y.toLowerCase(),model:Q.join(":")}}let Z=$.toLowerCase();if(Z.startsWith("gpt-")||Z.startsWith("o1")||Z.startsWith("o3"))return{provider:"openai",model:$};if(Z.startsWith("llama")||Z.startsWith("mistral")||Z.startsWith("codellama")||Z.startsWith("deepseek"))return{provider:"ollama",model:$};return{provider:"anthropic",model:$}}var rW={anthropic:{name:"Anthropic",envKey:"",description:"Claude models (default, via subscription)"},openai:{name:"OpenAI",envKey:"OPENAI_API_KEY",description:"GPT and o-series models"},ollama:{name:"Ollama",envKey:"",description:"Local models via Ollama (no API key needed)"}};function s3(){let $=["Providers:"];for(let[Z,Y]of Object.entries(rW)){let Q=Y.envKey?` (${Y.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${Y.description}${Q}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
549
+ `)}function t3($,Z,Y,Q){let{provider:z,model:J}=U7(Z);if(z==="openai"||z==="ollama")return new oZ(z,J,Y);let X=new lZ($.auth.token,Z,Y,Q);return X.setAuthRefresh(()=>{let K=u1();if(K&&K.token!==$.auth.token)return $.auth=K,X.updateToken(K.token),!0;return!1}),X}l();import{existsSync as L0,mkdirSync as e3,readdirSync as $X,readFileSync as N8,unlinkSync as ZX,renameSync as iZ}from"fs";import{join as e}from"path";class rZ{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=e($,"sessions"),this.archiveDir=e($,"sessions","archive"),!L0(this.sessionsDir))e3(this.sessionsDir,{recursive:!0});if(!L0(this.archiveDir))e3(this.archiveDir,{recursive:!0});this.current=this.loadOrCreate("default")}get session(){return this.current}get messages(){return this.current.messages}addMessage($){this.current.messages.push($),this.current.updated=Date.now(),this.save()}trimHistory($){if(this.current.messages.length>$)this.current.messages=this.current.messages.slice(-$),this.save()}clear(){this.current.messages=[],this.current.updated=Date.now(),this.save()}popMessages($){let Z=this.current.messages.splice(-$,$);return this.current.updated=Date.now(),this.save(),Z}switchTo($){return this.current=this.loadOrCreate($),this.saveLastSession(),this.current}list(){if(!L0(this.sessionsDir))return[];return $X(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=e(this.sessionsDir,`${$}.json`);if(!L0(Z))return null;try{let Y=JSON.parse(N8(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=e(this.sessionsDir,`${$}.json`);if(L0(Z))return ZX(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=e(this.sessionsDir,`${$}.json`);return P(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=e(this.sessionsDir,`${$}.json`);if(!L0(Z))return!1;let Y=e(this.archiveDir,`${$}.json`);return iZ(Z,Y),!0}archiveAll(){let $=[],Z=this.list().filter((Y)=>Y!==this.current.name);for(let Y of Z)if(this.archive(Y))$.push(Y);return $}unarchive($){let Z=e(this.archiveDir,`${$}.json`);if(!L0(Z))return!1;let Y=e(this.sessionsDir,`${$}.json`);return iZ(Z,Y),!0}listArchived(){if(!L0(this.archiveDir))return[];return $X(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=e(this.archiveDir,`${$}.json`);if(!L0(Z))return null;try{let Y=JSON.parse(N8(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=e(this.archiveDir,`${$}.json`);if(L0(Z))return ZX(Z),!0;return!1}loadOrCreate($){let Z=e(this.sessionsDir,`${$}.json`);if(L0(Z))try{return JSON.parse(N8(Z,"utf-8"))}catch{let Q=e(this.sessionsDir,`${$}.corrupt.json`);try{iZ(Z,Q)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return P(Z,JSON.stringify(Y,null,2)),Y}saveLastSession(){let $=e(this.sessionsDir,"..","last-session.txt");P($,this.current.name)}getLastSession(){let $=e(this.sessionsDir,"..","last-session.txt");if(!L0($))return null;try{let Z=N8($,"utf-8").trim();if(!Z||!L0(e(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}getSession($){let Z=e(this.sessionsDir,`${$}.json`);if(!L0(Z))return null;try{return JSON.parse(N8(Z,"utf-8"))}catch{return null}}addMessageTo($,Z){let Y=this.getSession($)||{id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};Y.messages.push(Z),Y.updated=Date.now();let Q=e(this.sessionsDir,`${$}.json`);if(P(Q,JSON.stringify(Y,null,2)),this.current.name===$)this.current=Y}listAll(){return this.list().map(($)=>{let Z=this.getInfo($),Y=this.getSession($);return{name:$,messageCount:Z?.messageCount||0,created:Y?.created||0,updated:Z?.updated||0}})}getCurrentName(){return this.current.name}createSession($){let Z=this.getSession($);if(Z)return Z;let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()},Q=e(this.sessionsDir,`${$}.json`);return P(Q,JSON.stringify(Y,null,2)),Y}save(){let $=e(this.sessionsDir,`${this.current.name}.json`);P($,JSON.stringify(this.current,null,2))}}import{existsSync as zX,readdirSync as tW,readFileSync as JX}from"fs";import{join as aZ}from"path";s();import{existsSync as nZ,readFileSync as YX}from"fs";import{basename as nW,join as q7}from"path";function QX(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${t9()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),j)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=aW($);if(Y)Z.push(`Project: ${Y}`);let Q=sW($);if(Q)Z.push(Q);return Z.join(`
550
+ `)}function aW($){let Z=[["package.json","Node.js/JavaScript"],["Cargo.toml","Rust"],["go.mod","Go"],["pyproject.toml","Python"],["requirements.txt","Python"],["pom.xml","Java (Maven)"],["build.gradle","Java (Gradle)"],["Gemfile","Ruby"],["composer.json","PHP"],["Makefile","Make"],["CMakeLists.txt","C/C++ (CMake)"],["Dockerfile","Docker"]],Y=[];for(let[z,J]of Z)if(nZ(q7($,z)))Y.push(J);if(Y.length===0)return null;let Q=nW($);try{let z=q7($,"package.json");if(nZ(z)){let J=JSON.parse(YX(z,"utf-8"));if(J.name)Q=J.name}}catch(z){m.debug("Failed to parse package.json for project name",{error:z})}return`Project: ${Q} (${Y.join(", ")})`}function sW($){if(!nZ(q7($,".git")))return null;let Z=[];try{let Y=YX(q7($,".git","HEAD"),"utf-8").trim(),Q=Y.startsWith("ref: refs/heads/")?Y.slice(16):Y.slice(0,8);Z.push(`Git branch: ${Q}`)}catch{return Z.push("Git: initialized"),Z.join(`
551
+ `)}try{let Y=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q)Z.push(`Last commit: ${Q}`)}}catch(Y){m.debug("git log failed",{error:Y})}try{let Y=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q){let z=Q.split(`
552
+ `),J=z.slice(0,15);if(z.length>15)J.push(`... and ${z.length-15} more files`);Z.push(`Uncommitted changes:
543
553
  `+J.join(`
544
- `))}}}catch(Y){x.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
545
- `):null}function rJ($,Z){if(!aJ($))return[];let Y=[],Q=BH($,{withFileTypes:!0});for(let J of Q)if(J.isFile()&&J.name.endsWith(".md")){let z=nJ(RZ($,J.name),"utf-8");Y.push({name:J.name.replace(".md",""),content:z.trim(),source:Z})}else if(J.isDirectory()){let z=RZ($,J.name,"SKILL.md");if(aJ(z)){let X=nJ(z,"utf-8");Y.push({name:J.name,content:X.trim(),source:Z})}}return Y}function sJ($){let Z=rJ($,"global"),Y=RZ(process.cwd(),".smolerclaw","skills"),Q=rJ(Y,"local"),J=new Map;for(let z of Z)J.set(z.name,z);for(let z of Q)J.set(z.name,z);return[...J.values()]}function tJ($){if($.length===0)return"No skills loaded.";return`Skills:
554
+ `))}}}catch(Y){m.debug("git diff --stat failed",{error:Y})}try{let Y=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q){let z=Q.split(`
555
+ `).slice(0,10);Z.push(`Staged:
556
+ `+z.join(`
557
+ `))}}}catch(Y){m.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
558
+ `):null}function XX($,Z){if(!zX($))return[];let Y=[],Q=tW($,{withFileTypes:!0});for(let z of Q)if(z.isFile()&&z.name.endsWith(".md")){let J=JX(aZ($,z.name),"utf-8");Y.push({name:z.name.replace(".md",""),content:J.trim(),source:Z})}else if(z.isDirectory()){let J=aZ($,z.name,"SKILL.md");if(zX(J)){let X=JX(J,"utf-8");Y.push({name:z.name,content:X.trim(),source:Z})}}return Y}function KX($){let Z=XX($,"global"),Y=aZ(process.cwd(),".smolerclaw","skills"),Q=XX(Y,"local"),z=new Map;for(let J of Z)z.set(J.name,J);for(let J of Q)z.set(J.name,J);return[...z.values()]}function GX($){if($.length===0)return"No skills loaded.";return`Skills:
546
559
  `+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
547
- `)}function n5($,Z,Y="auto"){let Q=[];for(let J of Z)Q.push(J.content);if(Y&&Y!=="auto"){let z={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[Y]||Y;Q.push(`## Language Override
548
- ALWAYS respond in ${z}. This is a hard requirement.`)}if(K0())Q.push(`---
549
- `+VJ());if(Q.push(`---
560
+ `)}function H7($,Z,Y="auto"){let Q=[];for(let z of Z)Q.push(z.content);if(Y&&Y!=="auto"){let J={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[Y]||Y;Q.push(`## Language Override
561
+ ALWAYS respond in ${J}. This is a hard requirement.`)}if(H1())Q.push(`---
562
+ `+Z3());if(Q.push(`---
550
563
  ## Meta-Learning & Self-Awareness
551
564
  You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
552
565
 
@@ -566,101 +579,97 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
566
579
  ## Environment
567
580
  The user's current working directory and project info. Use this context when they ask about code or files.
568
581
 
569
- `+iJ()),$)Q.push(`## User Instructions
582
+ `+QX()),$)Q.push(`## User Instructions
570
583
  `+$);return Q.join(`
571
584
 
572
- `)}import{existsSync as K$,readdirSync as t5,readFileSync as X4,mkdirSync as LZ,renameSync as EZ,rmSync as z4}from"fs";import{join as h,basename as r5,extname as s5}from"path";d$();d$();var S=[],M$="",eJ="";async function $z($,Z){if(M$=$,eJ=Z,S=[],!K$($))return LZ($,{recursive:!0}),[];let Y=f1($);for(let J of Y)S=[...S,{name:J.name,description:J.description,version:"1.0.0",type:"json",source:J.source,enabled:!0,tools:h1([J]),jsonPlugin:J,eventUnsubs:[]}];let Q=t5($).filter((J)=>{let z=s5(J);return z===".ts"||z===".js"});for(let J of Q){let z=h($,J);try{let X=await import(z),K=X.default||X;if(!K.name||!K.description){x.debug(`Skipping invalid script plugin: ${J}`);continue}let V=await jZ(K,z);if(V)S=[...S,V]}catch(X){x.debug(`Failed to load script plugin: ${J}`,{error:X instanceof Error?X.message:String(X)})}}return s("status:update",{source:"plugin-system",message:`${S.length} plugin(s) carregado(s)`,level:"info",timestamp:Date.now()}),S}async function jZ($,Z){let Y=h(eJ,"plugins",$.name);if(!K$(Y))LZ(Y,{recursive:!0});let Q={notify:(z,X="info")=>{s("status:update",{source:`plugin:${$.name}`,message:z,level:X,timestamp:Date.now()})},dataDir:Y};try{await $.onLoad?.(Q)}catch(z){return x.debug(`Plugin ${$.name} onLoad failed`,{error:z instanceof Error?z.message:String(z)}),null}let J=[];if($.events){for(let[z,X]of Object.entries($.events))if(X){let K=r.on(z,X,{async:!0});J.push(K)}}return{name:$.name,description:$.description,version:$.version||"1.0.0",type:"script",source:Z,enabled:!0,tools:$.tools||[],scriptDef:$,eventUnsubs:J}}function Zz(){return S.filter(($)=>$.enabled).flatMap(($)=>[...$.tools])}function Yz($){let Z=S.findIndex((z)=>z.name===$);if(Z===-1)return!1;let Y=S[Z];if(!Y.enabled)return!1;for(let z of Y.eventUnsubs)z();if(Y.type==="script"&&Y.scriptDef?.onUnload)try{Y.scriptDef.onUnload()}catch{}let Q=h(M$,"disabled");if(!K$(Q))LZ(Q,{recursive:!0});let J=h(Q,r5(Y.source));try{EZ(Y.source,J)}catch{}return S=S.map((z,X)=>X===Z?{...z,enabled:!1,eventUnsubs:[]}:z),s("status:update",{source:"plugin-system",message:`Plugin "${$}" desabilitado`,level:"info",timestamp:Date.now()}),!0}async function Qz($){let Z=S.findIndex((V)=>V.name===$&&!V.enabled);if(Z!==-1){let V=S[Z],G=h(M$,"disabled"),q=h(G,r5(V.source)),U=h(M$,r5(V.source));if(K$(q))try{EZ(q,U)}catch{}return S=S.map((W,B)=>B===Z?{...W,enabled:!0,source:U}:W),s("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}let Y=h(M$,"disabled");if(!K$(Y))return!1;let J=t5(Y).find((V)=>{return r5(V,s5(V))===$});if(!J)return!1;let z=h(Y,J),X=h(M$,J);try{EZ(z,X)}catch{return!1}let K=s5(J);if(K===".json"){let V=f1(M$).filter((G)=>G.source===X);for(let G of V)S=[...S,{name:G.name,description:G.description,version:"1.0.0",type:"json",source:G.source,enabled:!0,tools:h1([G]),jsonPlugin:G,eventUnsubs:[]}]}else if(K===".ts"||K===".js")try{let V=await import(X),G=V.default||V;if(G.name&&G.description){let q=await jZ(G,X);if(q)S=[...S,q]}}catch{}return s("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}async function Jz($){if(!M$)return{success:!1,name:"",message:"Plugin system nao inicializado."};let Z=MH($);if(!Z)return{success:!1,name:"",message:`Fonte invalida: "${$}". Use owner/repo ou URL do GitHub.`};let{owner:Y,repo:Q,branch:J}=Z,z=h(M$,"installed",`${Y}--${Q}`);if(K$(z))return{success:!1,name:`${Y}/${Q}`,message:`Plugin ${Y}/${Q} ja instalado. Use /plugin uninstall para remover.`};let X=`https://github.com/${Y}/${Q}.git`,K=["git","clone","--depth","1"];if(J)K.push("--branch",J);K.push(X,z);try{let N=Bun.spawn(K,{stdout:"pipe",stderr:"pipe"}),F=setTimeout(()=>N.kill(),30000),[,j]=await Promise.all([new Response(N.stdout).text(),new Response(N.stderr).text()]),p=await N.exited;if(clearTimeout(F),p!==0){try{z4(z,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`git clone falhou: ${j.trim().split(`
573
- `)[0]||`exit code ${p}`}`}}}catch(N){try{z4(z,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`Erro ao clonar: ${N instanceof Error?N.message:String(N)}`}}let V=CH(z);if(!V){try{z4(z,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:'Nenhum entry point encontrado. O repo deve conter plugin.json, plugin.ts, index.ts, ou package.json com campo "smolerclaw".'}}let G=s5(V.path),q=`${Y}--${Q}${G}`,U=h(M$,q);if(G===".ts"||G===".js"){let N=V.path.replace(/\\/g,"/"),F=`// Auto-installed from github.com/${Y}/${Q}
574
- export { default } from '${N}'
575
- `;Bun.write(U,F)}else{let N=X4(V.path,"utf-8");Bun.write(U,N)}if(G===".json"){let N=f1(M$).filter((F)=>F.source===U);for(let F of N)S=[...S,{name:F.name,description:F.description,version:"1.0.0",type:"json",source:U,enabled:!0,tools:h1([F]),jsonPlugin:F,eventUnsubs:[]}]}else try{let N=await import(V.path),F=N.default||N;if(F.name&&F.description){let j=await jZ(F,U);if(j)S=[...S,j]}}catch{}let B=S.find((N)=>N.source===U)?.name||`${Y}/${Q}`;s("status:update",{source:"plugin-system",message:`Plugin "${B}" instalado de github.com/${Y}/${Q}`,level:"success",timestamp:Date.now()});let M=h(z,".smolerclaw-install.json");return Bun.write(M,JSON.stringify({source:`${Y}/${Q}`,branch:J||"default",installedAt:new Date().toISOString(),entryPoint:U,pluginName:B},null,2)),{success:!0,name:B,message:`Plugin "${B}" instalado com sucesso de github.com/${Y}/${Q}.`}}function zz($){if(!M$)return{success:!1,message:"Plugin system nao inicializado."};let Z=h(M$,"installed");if(!K$(Z))return{success:!1,message:`Plugin "${$}" nao encontrado.`};let Y=S.find((z)=>z.name===$),Q=null,J=null;if(Y){J=Y.source;let z=t5(Z).filter((X)=>K$(h(Z,X,".smolerclaw-install.json")));for(let X of z)try{let K=JSON.parse(X4(h(Z,X,".smolerclaw-install.json"),"utf-8"));if(K.pluginName===$||K.entryPoint===J){Q=h(Z,X);break}}catch{}}else{let z=$.replace("/","--"),X=h(Z,z);if(K$(X)){Q=X;try{J=JSON.parse(X4(h(X,".smolerclaw-install.json"),"utf-8")).entryPoint||null}catch{}}}if(!Q&&!J)return{success:!1,message:`Plugin "${$}" nao encontrado entre os instalados.`};if(Y){for(let z of Y.eventUnsubs)z();if(Y.scriptDef?.onUnload)try{Y.scriptDef.onUnload()}catch{}S=S.filter((z)=>z.name!==$)}if(J&&K$(J))try{z4(J,{force:!0})}catch{}if(Q)try{z4(Q,{recursive:!0,force:!0})}catch{}return s("status:update",{source:"plugin-system",message:`Plugin "${$}" desinstalado`,level:"info",timestamp:Date.now()}),{success:!0,message:`Plugin "${$}" desinstalado com sucesso.`}}function Xz(){let $=h(M$,"installed");if(!K$($))return[];let Z=[],Y=t5($);for(let Q of Y){let J=h($,Q,".smolerclaw-install.json");if(!K$(J))continue;try{let z=JSON.parse(X4(J,"utf-8"));Z.push({name:z.pluginName||Q,source:z.source||Q.replace("--","/"),installedAt:z.installedAt||"desconhecido"})}catch{}}return Z}function MH($){let Z=$.match(/github\.com\/([^/]+)\/([^/\s#]+)/);if(Z){let Q=Z[2].replace(/\.git$/,""),J=$.match(/#(.+)$/);return{owner:Z[1],repo:Q,branch:J?.[1]||null}}let Y=$.match(/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+?)(?:#(.+))?$/);if(Y)return{owner:Y[1],repo:Y[2],branch:Y[3]||null};return null}function CH($){let Z=h($,"package.json");if(K$(Z))try{let J=JSON.parse(X4(Z,"utf-8"));if(J.smolerclaw){let z=h($,J.smolerclaw);if(K$(z))return{path:z}}}catch{}let Y=["plugin.json","plugin.ts","plugin.js","index.ts","index.js"];for(let J of Y){let z=h($,J);if(K$(z))return{path:z}}let Q=["src/plugin.ts","src/plugin.js","src/index.ts","src/index.js"];for(let J of Q){let z=h($,J);if(K$(z))return{path:z}}return null}function Kz($){return S.find((Z)=>Z.name===$)}function Vz(){if(S.length===0)return"Nenhum plugin carregado. Adicione arquivos em ~/.config/smolerclaw/plugins/";let $=["Plugins:"];for(let Z of S){let Y=Z.enabled?"":" [desabilitado]",Q=Z.type==="script"?"script":"json",J=Z.tools.length;$.push(` ${Z.name} v${Z.version} (${Q}) \u2014 ${Z.description} [${J} tool${J!==1?"s":""}]${Y}`)}return $.join(`
576
- `)}async function Gz(){for(let $ of S){for(let Z of $.eventUnsubs)Z();if($.type==="script"&&$.scriptDef?.onUnload)try{await $.scriptDef.onUnload()}catch{}}S=[]}import{join as NH}from"path";async function qz($,Z,Y){let Q=new OZ($.dataDir),J=Z||Q.getLastSession()||"default";if(J!=="default")Q.switchTo(J);let z=sJ($.skillsDir),X=n5($.systemPrompt,z,$.language),K=!Y;qZ();let V=UJ(NH($.dataDir,"..")),G=f1(V);if(G.length>0)VZ(G),k.push(...h1(G));await $z(V,$.dataDir);let q=Zz(),U=new Set(k.map((M)=>M.name));for(let M of q)if(!U.has(M.name))k.push(M);let W=wY(),B=W?`${X}
585
+ `)}async function VX($,Z,Y){let Q=new rZ($.dataDir),z=Z||Q.getLastSession()||"default";if(z!=="default")Q.switchTo(z);let J=KX($.skillsDir),X=H7($.systemPrompt,J,$.language),K=!Y;mZ();let G=V3(l7()),V=c$(G);if(V.length>0)hZ(V),y.push(...l$(V));await q3(G,$.dataDir);let U=H3(),q=new Set(y.map((O)=>O.name));for(let O of U)if(!q.has(O.name))y.push(O);let H=jz(),B=H?`${X}
577
586
 
578
- ${W}`:X;return{sessions:Q,sessionName:J,skills:z,systemPrompt:X,activeSystemPrompt:B,enableTools:K,plugins:G}}async function Uz($,Z,Y,Q,J,z){let X=J||"";if(z){let q=await OH();X=X?`${X}
587
+ ${H}`:X;return{sessions:Q,sessionName:z,skills:J,systemPrompt:X,activeSystemPrompt:B,enableTools:K,plugins:V}}async function UX($,Z,Y,Q,z,J){let X=z||"";if(J){let U=await eW();X=X?`${X}
579
588
 
580
- ${q}`:q}if(!X.trim())console.error("smolerclaw: no input provided"),process.exit(1);let K={role:"user",content:X.trim(),timestamp:Date.now()};Z.addMessage(K);let V="";for await(let q of $.chat(Z.messages,Y,Q))if(q.type==="text")process.stdout.write(q.text),V+=q.text;else if(q.type==="error")console.error(`
581
- smolerclaw error: ${q.error}`);if(V&&!V.endsWith(`
589
+ ${U}`:U}if(!X.trim())console.error("smolerclaw: no input provided"),process.exit(1);let K={role:"user",content:X.trim(),timestamp:Date.now()};Z.addMessage(K);let G="";for await(let U of $.chat(Z.messages,Y,Q))if(U.type==="text")process.stdout.write(U.text),G+=U.text;else if(U.type==="error")console.error(`
590
+ smolerclaw error: ${U.error}`);if(G&&!G.endsWith(`
582
591
  `))process.stdout.write(`
583
- `);let G={role:"assistant",content:V,timestamp:Date.now()};Z.addMessage(G)}async function OH(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var FH=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function g$($){return FH?"":$}var H={altOn:g$("\x1B[?1049h"),altOff:g$("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:g$("\x1B[1m"),dim:g$("\x1B[2m"),italic:g$("\x1B[3m"),underline:g$("\x1B[4m"),reset:g$("\x1B[0m"),inv:g$("\x1B[7m"),fg:($)=>g$(`\x1B[38;5;${$}m`),bg:($)=>g$(`\x1B[48;5;${$}m`)};var I={user:H.fg(75),ai:H.fg(114),tool:H.fg(215),err:H.fg(196),sys:H.fg(245),prompt:H.fg(220),code:H.fg(180),heading:H.fg(75),link:H.fg(39),quote:H.fg(245)},RH={primary:H.fg(75),secondary:H.fg(39),accent:H.fg(220),muted:H.fg(245),header:H.fg(81)},EH={primary:H.fg(215),secondary:H.fg(220),accent:H.fg(196),muted:H.fg(245),header:H.fg(214)},LH={primary:H.fg(183),secondary:H.fg(157),accent:H.fg(147),muted:H.fg(242),header:H.fg(183)};function DZ($){switch($){case"productivity":return RH;case"spillover_alert":return EH;case"sharpen_or_relax":return LH}}function O($){process.stdout.write($)}var jH=/\x1b\[[0-9;]*[a-zA-Z]/g;function y0($){return $.replace(jH,"")}function DH($){let Z=$.codePointAt(0)||0;if(Z>=4352&&Z<=4447||Z>=11904&&Z<=42191&&Z!==12351||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65135||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510||Z>=127744&&Z<=130047||Z>=131072&&Z<=196607)return 2;return 1}function V$($){let Z=y0($),Y=0;for(let Q of Z)Y+=DH(Q);return Y}function _0($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
584
- `)){if(V$(Q)<=Z){Y.push(Q);continue}let X=y0(Q).split(" "),K=[],V="";for(let q of X)if(V.length+(V?1:0)+q.length>Z&&V)K.push(V),V=" "+q;else V+=(V?" ":"")+q;if(V)K.push(V);let G=PH(Q);for(let q=0;q<K.length;q++)if(G&&q===0)K[q]=G+K[q]+H.reset;else if(G)K[q]=G+K[q]+H.reset;Y.push(...K)}return Y}function PH($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function e5($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
585
- `),J=[],z=!1,X="";for(let K=0;K<Q.length;K++){let V=Q[K];if(V.trimStart().startsWith("```")){if(!z){z=!0,X=V.trimStart().slice(3).trim();let B=X?` ${X}`:"";J.push(` ${H.dim}\u250C\u2500\u2500${B}${"\u2500".repeat(Math.max(1,40-B.length))}${H.reset}`)}else z=!1,X="",J.push(` ${H.dim}\u2514${"\u2500".repeat(42)}${H.reset}`);continue}if(z){J.push(` ${H.dim}\u2502${H.reset} ${I.code}${V}${H.reset}`);continue}if(!V.trim()){J.push("");continue}let G=V.match(/^(#{1,3})\s+(.+)/);if(G){let B=G[1].length,M=G[2],N=B===1?"\u2501":B===2?"\u2500":"\xB7";J.push(` ${I.heading}${H.bold}${N} ${K4(M)}${H.reset}`);continue}if(V.trimStart().startsWith(">")){let B=V.replace(/^\s*>\s?/,"");PZ(J,` ${I.quote}\u2502 ${K4(B)}${H.reset}`,Y);continue}let q=V.match(/^(\s*)([-*+])\s+(.+)/);if(q){let B=Math.floor(q[1].length/2),M=q[3],N=" ".repeat(B);PZ(J,` ${N}${H.dim}\u2022${H.reset} ${K4(M)}`,Y);continue}let U=V.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(U){let B=Math.floor(U[1].length/2),M=U[2],N=U[3],F=" ".repeat(B);PZ(J,` ${F}${H.dim}${M}.${H.reset} ${K4(N)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(V.trim())){J.push(` ${H.dim}${"\u2500".repeat(40)}${H.reset}`);continue}let W=` ${K4(V)}`;if(V$(W)>Y)for(let B of _0(W,Y))J.push(B);else J.push(W)}if(z)J.push(` ${H.dim}\u2514${"\u2500".repeat(42)}${H.reset}`);return J}function PZ($,Z,Y){if(V$(Z)>Y)for(let Q of _0(Z,Y))$.push(Q);else $.push(Z)}function K4($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${H.inv} $1 ${H.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${H.bold}${H.italic}$1${H.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${H.bold}$1${H.reset}`),Z=Z.replace(/__(.+?)__/g,`${H.bold}$1${H.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${H.italic}$1${H.reset}`),Z=Z.replace(/_(.+?)_/g,`${H.italic}$1${H.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${H.underline}$1${H.reset} ${I.link}($2)${H.reset}`),Z}import{existsSync as AH,readFileSync as TH,writeFileSync as IH}from"fs";var AZ=500;class TZ{filePath;entries=[];cursor=-1;pending="";constructor($){this.filePath=$;this.load()}add($){let Z=$.trim();if(!Z)return;if(this.entries.length>0&&this.entries[this.entries.length-1]===Z)return;if(this.entries.push(Z),this.entries.length>AZ)this.entries=this.entries.slice(-AZ);this.cursor=-1,this.pending="",this.save()}prev($){if(this.entries.length===0)return null;if(this.cursor===-1)this.pending=$,this.cursor=this.entries.length-1;else if(this.cursor>0)this.cursor--;else return this.entries[0];return this.entries[this.cursor]}next(){if(this.cursor===-1)return this.pending;if(this.cursor<this.entries.length-1)return this.cursor++,this.entries[this.cursor];return this.cursor=-1,this.pending}reset(){this.cursor=-1,this.pending=""}load(){try{if(AH(this.filePath)){let $=TH(this.filePath,"utf-8");this.entries=$.split(`
586
- `).filter(Boolean).slice(-AZ)}}catch{}}save(){try{IH(this.filePath,this.entries.join(`
592
+ `);let V={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(V)}async function eW(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var $B=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function i0($){return $B?"":$}var W={altOn:i0("\x1B[?1049h"),altOff:i0("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:i0("\x1B[1m"),dim:i0("\x1B[2m"),italic:i0("\x1B[3m"),underline:i0("\x1B[4m"),reset:i0("\x1B[0m"),inv:i0("\x1B[7m"),fg:($)=>i0(`\x1B[38;5;${$}m`),bg:($)=>i0(`\x1B[48;5;${$}m`)};var I={user:W.fg(75),ai:W.fg(114),tool:W.fg(215),err:W.fg(196),sys:W.fg(245),prompt:W.fg(220),code:W.fg(180),heading:W.fg(75),link:W.fg(39),quote:W.fg(245)},ZB={primary:W.fg(75),secondary:W.fg(39),accent:W.fg(220),muted:W.fg(245),header:W.fg(81)},YB={primary:W.fg(215),secondary:W.fg(220),accent:W.fg(196),muted:W.fg(245),header:W.fg(214)},QB={primary:W.fg(183),secondary:W.fg(157),accent:W.fg(147),muted:W.fg(242),header:W.fg(183)};function sZ($){switch($){case"productivity":return ZB;case"spillover_alert":return YB;case"sharpen_or_relax":return QB}}function E($){process.stdout.write($)}var zB=/\x1b\[[0-9;]*[a-zA-Z]/g;function x1($){return $.replace(zB,"")}function JB($){let Z=$.codePointAt(0)||0;if(Z>=4352&&Z<=4447||Z>=11904&&Z<=42191&&Z!==12351||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65135||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510||Z>=127744&&Z<=130047||Z>=131072&&Z<=196607)return 2;return 1}function W0($){let Z=x1($),Y=0;for(let Q of Z)Y+=JB(Q);return Y}function v1($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
593
+ `)){if(W0(Q)<=Z){Y.push(Q);continue}let X=x1(Q).split(" "),K=[],G="";for(let U of X)if(G.length+(G?1:0)+U.length>Z&&G)K.push(G),G=" "+U;else G+=(G?" ":"")+U;if(G)K.push(G);let V=XB(Q);for(let U=0;U<K.length;U++)if(V&&U===0)K[U]=V+K[U]+W.reset;else if(V)K[U]=V+K[U]+W.reset;Y.push(...K)}return Y}function XB($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function W7($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
594
+ `),z=[],J=!1,X="";for(let K=0;K<Q.length;K++){let G=Q[K];if(G.trimStart().startsWith("```")){if(!J){J=!0,X=G.trimStart().slice(3).trim();let B=X?` ${X}`:"";z.push(` ${W.dim}\u250C\u2500\u2500${B}${"\u2500".repeat(Math.max(1,40-B.length))}${W.reset}`)}else J=!1,X="",z.push(` ${W.dim}\u2514${"\u2500".repeat(42)}${W.reset}`);continue}if(J){z.push(` ${W.dim}\u2502${W.reset} ${I.code}${G}${W.reset}`);continue}if(!G.trim()){z.push("");continue}let V=G.match(/^(#{1,3})\s+(.+)/);if(V){let B=V[1].length,O=V[2],M=B===1?"\u2501":B===2?"\u2500":"\xB7";z.push(` ${I.heading}${W.bold}${M} ${M8(O)}${W.reset}`);continue}if(G.trimStart().startsWith(">")){let B=G.replace(/^\s*>\s?/,"");tZ(z,` ${I.quote}\u2502 ${M8(B)}${W.reset}`,Y);continue}let U=G.match(/^(\s*)([-*+])\s+(.+)/);if(U){let B=Math.floor(U[1].length/2),O=U[3],M=" ".repeat(B);tZ(z,` ${M}${W.dim}\u2022${W.reset} ${M8(O)}`,Y);continue}let q=G.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(q){let B=Math.floor(q[1].length/2),O=q[2],M=q[3],C=" ".repeat(B);tZ(z,` ${C}${W.dim}${O}.${W.reset} ${M8(M)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(G.trim())){z.push(` ${W.dim}${"\u2500".repeat(40)}${W.reset}`);continue}let H=` ${M8(G)}`;if(W0(H)>Y)for(let B of v1(H,Y))z.push(B);else z.push(H)}if(J)z.push(` ${W.dim}\u2514${"\u2500".repeat(42)}${W.reset}`);return z}function tZ($,Z,Y){if(W0(Z)>Y)for(let Q of v1(Z,Y))$.push(Q);else $.push(Z)}function M8($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${W.inv} $1 ${W.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${W.bold}${W.italic}$1${W.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${W.bold}$1${W.reset}`),Z=Z.replace(/__(.+?)__/g,`${W.bold}$1${W.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${W.italic}$1${W.reset}`),Z=Z.replace(/_(.+?)_/g,`${W.italic}$1${W.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${W.underline}$1${W.reset} ${I.link}($2)${W.reset}`),Z}import{existsSync as KB,readFileSync as GB,writeFileSync as VB}from"fs";var eZ=500;class $9{filePath;entries=[];cursor=-1;pending="";constructor($){this.filePath=$;this.load()}add($){let Z=$.trim();if(!Z)return;if(this.entries.length>0&&this.entries[this.entries.length-1]===Z)return;if(this.entries.push(Z),this.entries.length>eZ)this.entries=this.entries.slice(-eZ);this.cursor=-1,this.pending="",this.save()}prev($){if(this.entries.length===0)return null;if(this.cursor===-1)this.pending=$,this.cursor=this.entries.length-1;else if(this.cursor>0)this.cursor--;else return this.entries[0];return this.entries[this.cursor]}next(){if(this.cursor===-1)return this.pending;if(this.cursor<this.entries.length-1)return this.cursor++,this.entries[this.cursor];return this.cursor=-1,this.pending}reset(){this.cursor=-1,this.pending=""}load(){try{if(KB(this.filePath)){let $=GB(this.filePath,"utf-8");this.entries=$.split(`
595
+ `).filter(Boolean).slice(-eZ)}}catch{}}save(){try{VB(this.filePath,this.entries.join(`
587
596
  `)+`
588
- `)}catch{}}}import{join as cH}from"path";var SH=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],wH=" ";function IZ($,Z={}){let{width:Y=$.length,min:Q=Math.min(...$),max:J=Math.max(...$),color:z="",showBounds:X=!1}=Z;if($.length===0)return"";let K=uH($,Y),V=J-Q||1,q=K.map((W)=>{if(W===0&&Q===0)return wH;let B=(W-Q)/V,M=Math.min(7,Math.floor(B*8));return SH[M]}).join(""),U=z?`${z}${q}${H.reset}`:q;if(X)return`${H.dim}${Q.toFixed(0)}${H.reset}${U}${H.dim}${J.toFixed(0)}${H.reset}`;return U}var kH="\u2588",bH="\u2589",yH="\u258A",_H="\u258B",xH="\u258C",vH="\u258D",fH="\u258E",hH="\u258F",gH="\u2591",mH=[" ",hH,fH,vH,xH,_H,yH,bH];function SZ($,Z={}){let{width:Y=20,maxValue:Q=100,showValue:J=!0,color:z=H.fg(75),label:X=""}=Z,K=Math.min(1,Math.max(0,$/Q)),V=Math.floor(K*Y),G=K*Y-V,q=Math.floor(G*8),U=kH.repeat(V);if(q>0&&V<Y)U+=mH[q];let W=Y-V$(U);U+=gH.repeat(Math.max(0,W));let B=z?`${z}${U}${H.reset}`:U,M=[];if(X)M.push(`${H.dim}${X.padEnd(12)}${H.reset}`);if(M.push(B),J)M.push(` ${H.dim}${$.toFixed(1)}%${H.reset}`);return M.join("")}function V4($,Z){let Y=[];if(Y.push(`${I.ai}${$.model}${H.reset}`),$.project)Y.push(`${I.heading}${$.project}${H.reset}`);if($.tokens){let{input:X,output:K}=$.tokens;Y.push(`${H.dim}${Hz(X)}/${Hz(K)} tok${H.reset}`)}if($.sessionCost)Y.push(`${H.dim}${$.sessionCost}${H.reset}`);if($.vaultStatus){let X=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",K=$.vaultStatus==="ok"?H.fg(114):$.vaultStatus==="warn"?H.fg(220):H.fg(196);Y.push(`${K}${X}${H.reset}`)}if($.customItems)for(let X of $.customItems){let K=X.color||"";Y.push(`${H.dim}${X.label}:${H.reset}${K}${X.value}${H.reset}`)}let Q=Y.join(` ${H.dim}\u2502${H.reset} `),J=V$(Q),z=Math.max(0,Z-J-2);return`${H.inv} ${Q}${" ".repeat(z)} ${H.reset}`}function wZ($,Z=40){let Y=[];Y.push(`${H.dim}${"\u2500".repeat(Z)}${H.reset}`),Y.push(`${I.heading}${H.bold} System${H.reset}`);let Q=IZ($.cpu,{width:15,color:H.fg(75)}),J=SZ($.currentCpu,{width:10,showValue:!1,color:H.fg(75)});Y.push(` ${H.dim}CPU:${H.reset} ${Q} ${J} ${$.currentCpu.toFixed(0)}%`);let z=IZ($.memory,{width:15,color:H.fg(114)}),X=SZ($.currentMem,{width:10,showValue:!1,color:H.fg(114)});return Y.push(` ${H.dim}MEM:${H.reset} ${z} ${X} ${$.currentMem.toFixed(0)}%`),Y.push(`${H.dim}${"\u2500".repeat(Z)}${H.reset}`),Y}function uH($,Z){if($.length<=Z){let J=[...$];while(J.length<Z)J.unshift(0);return J}let Y=$.length/Z,Q=[];for(let J=0;J<Z;J++){let z=Math.floor(J*Y),X=Math.floor((J+1)*Y),K=$.slice(z,X),V=K.reduce((G,q)=>G+q,0)/K.length;Q.push(V)}return Q}function Hz($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function G4($,Z,Y={}){let{title:Q="",padding:J=1,borderColor:z=H.dim,titleColor:X=I.heading}=Y,K=Z-2-J*2,V=[];if(Q){let q=V$(Q),U=2,W=Math.max(1,Z-q-2-4);V.push(`${z}\u250C${"\u2500".repeat(2)}${H.reset}${X}${H.bold} ${Q} ${H.reset}${z}${"\u2500".repeat(W)}\u2510${H.reset}`)}else V.push(`${z}\u250C${"\u2500".repeat(Z-2)}\u2510${H.reset}`);let G=" ".repeat(J);for(let q of $){let U=V$(q)>K?_0(q,K):[q];for(let W of U){let B=V$(W),M=Math.max(0,K-B);V.push(`${z}\u2502${H.reset}${G}${W}${" ".repeat(M)}${G}${z}\u2502${H.reset}`)}}return V.push(`${z}\u2514${"\u2500".repeat(Z-2)}\u2518${H.reset}`),V}function kZ($,Z,Y,Q,J={}){let z=G4($,Q,J);for(let X=0;X<z.length;X++)O(H.to(Z+X,Y)),O(z[X])}var $2={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},pH={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function bZ($,Z={}){let{width:Y=60,showActions:Q=!0,compact:J=!1}=Z,z=[],X=pH[$.category]||"\uD83D\uDCA1",K=$2.dimYellow+$2.italic;if(J){let q=$.title.length>Y-10?$.title.slice(0,Y-13)+"...":$.title;return z.push(` ${K}${X} ${q}${H.reset}`),z}z.push(` ${K}${X} ${$.title}${H.reset}`);let V=Y-6,G=_0($.explanation,V);for(let q of G)z.push(` ${K} ${y0(q)}${H.reset}`);if($.suggestedAction)z.push(` ${$2.dimCyan} \u2192 ${$.suggestedAction.label}${H.reset}`);if(Q)z.push(` ${H.dim} [Y] Aceitar [N] Ignorar${H.reset}`);return z}function Wz($,Z=40){let Y=[],Q=[...$].sort((J,z)=>z.frequency-J.frequency).slice(0,3);if(Q.length===0)return Y.push(`${H.dim} Nenhuma dica disponivel ainda.${H.reset}`),Y.push(`${H.dim} Continue usando para gerar insights.${H.reset}`),Y;for(let J=0;J<Q.length;J++){let z=Q[J],X=J+1,K=X===1?"\uD83E\uDD47":X===2?"\uD83E\uDD48":"\uD83E\uDD49",V=Z-8,G=z.title.length>V?z.title.slice(0,V-3)+"...":z.title;Y.push(`${K} ${$2.dimYellow}${G}${H.reset}`);let q=Z-4,U=z.description.length>q?z.description.slice(0,q-3)+"...":z.description;Y.push(` ${H.dim}${U}${H.reset}`);let W=z.frequency===1?"vez":"vezes";if(Y.push(` ${H.dim}Detectado ${z.frequency}x${H.reset}`),J<Q.length-1)Y.push("")}return Y}function Z2($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:Wz($,Z)}}class q4{mode="chat";width;height;statusBarEnabled=!0;statusConfig=null;dashboardLayout=null;savedChatLines=[];resizeCallbacks=[];constructor(){this.width=process.stdout.columns||80,this.height=process.stdout.rows||24}getMode(){return this.mode}getViewState(){let Z=this.statusBarEnabled&&this.statusConfig?this.height:0;return{mode:this.mode,width:this.width,height:this.height,statusBarRow:Z,contentStartRow:3,contentEndRow:this.height-2,inputRow:this.height}}enterChatMode(){if(this.mode==="chat")return;this.mode="chat",this.clearScreen()}enterDashboardMode($){this.mode="dashboard",this.dashboardLayout=$,this.clearScreen(),this.renderDashboard()}toggleMode(){if(this.mode==="chat")return;this.enterChatMode()}setStatusBar($){this.statusConfig=$}enableStatusBar($){this.statusBarEnabled=$}renderStatusBar(){if(!this.statusBarEnabled||!this.statusConfig)return;let $=this.height-1;O(H.to($,1)),O(V4(this.statusConfig,this.width))}clearScreen(){O(H.clear),O(H.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)O(H.to(Z,1)),O(H.clearLine)}updateDimensions($,Z){this.width=$,this.height=Z;for(let Y of this.resizeCallbacks)Y()}onResize($){this.resizeCallbacks.push($)}removeResizeCallback($){this.resizeCallbacks=this.resizeCallbacks.filter((Z)=>Z!==$)}renderDashboard(){if(this.mode!=="dashboard"||!this.dashboardLayout)return;this.clearContentArea();let{panels:$,columns:Z=2,gap:Y=1}=this.dashboardLayout,Q=this.getViewState(),J=Q.contentEndRow-Q.contentStartRow,z=Math.floor((this.width-Y*(Z+1))/Z),X=Q.contentStartRow,K=1+Y;for(let V=0;V<$.length;V++){let G=$[V],q=G.row??X,U=G.col??K,W=G.width??z,B=G.height??Math.floor(J/Math.ceil($.length/Z));if(this.drawDashboardPanel(G,q,U,W,B),(V+1)%Z===0)X+=B+Y,K=1+Y;else K+=W+Y}this.renderStatusBar()}drawDashboardPanel($,Z,Y,Q,J){let z=J-2,X=$.content.slice(0,z);kZ(X,Z,Y,Q,{title:$.title})}createMorningBriefingLayout($){let Z=[{id:"tasks",title:"Tarefas do Dia",content:$.tasks.length>0?$.tasks:["Nenhuma tarefa para hoje"]},{id:"followups",title:"Follow-ups",content:$.followUps.length>0?$.followUps:["Nenhum follow-up pendente"]},{id:"calendar",title:"Agenda",content:$.calendar.length>0?$.calendar:["Sem eventos hoje"]},{id:"news",title:"Noticias",content:$.news.length>0?$.news:["Sem noticias recentes"]}];if($.projectSummary)Z.push({id:"project",title:"Projetos",content:$.projectSummary});return{panels:Z,columns:2,gap:1}}createMonitoringLayout($){return{panels:[{id:"telemetry",title:"Sistema",content:wZ($,35)}],columns:1,gap:1}}}function Y2($,Z){O(`\x1B[${$};${Z}r`)}function Q2(){O("\x1B[r")}var dH=new q4;d$();class yZ{model;sessionName;authInfo;dataDir;width=80;height=24;lines=[];streamBuf="";streamLines=[];inputBuf="";inputPos=0;isStreaming=!1;scrollOffset=0;history=null;renderTimer=null;spinnerFrame=0;spinnerTimer=null;streamStartTime=0;sessionCost="";viewMode="chat";viewManager;dashboardContent=[];statusBarEnabled=!0;inputTokens=0;outputTokens=0;activeProject="";vaultStatus="ok";stickyStatusRow=0;personaMode="productivity";palette=DZ("productivity");timeContext=null;commands=["/help","/clear","/commit","/persona","/copy","/fork","/new","/load","/sessions","/delete","/model","/export","/cost","/retry","/undo","/search","/lang","/config","/exit","/briefing","/news","/open","/openfile","/openurl","/apps","/sysinfo","/calendar","/ask","/budget","/plugins","/task","/tasks","/done","/rmtask","/people","/team","/family","/person","/addperson","/delegate","/delegations","/followups","/dashboard","/contacts","/investigar","/investigate","/investigacoes","/monitor","/vigiar","/workflow","/fluxo","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/index","/indexar","/reindex","/memory","/memoria","/clipboard","/area","/tela","/screen","/ps1","/refresh","/renovar","/vault","/backup","/feeds","/fontes","/addfeed","/novafonte","/rmfeed","/rmfonte","/disablefeed","/desativarfonte","/enablefeed","/ativarfonte","/projeto","/project","/projetos","/projects","/sessao","/session","/relatorio","/report","/oportunidades","/opportunities","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];subcommands={"/model":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/modelo":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/news":["business","tech","finance","brazil","world","security"],"/noticias":["business","tech","finance","brazil","world","security"],"/open":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/abrir":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/sessao":["start","stop","status"],"/session":["start","stop","status"],"/relatorio":["today","week","month"],"/report":["today","week","month"],"/projeto":["auto"],"/project":["auto"],"/oportunidades":["nova","em_analise","aceita","recusada","concluida"],"/opportunities":["nova","em_analise","aceita","recusada","concluida"],"/persona":["default","business"],"/modo":["default","business"],"/people":["equipe","familia","contato"],"/pessoas":["equipe","familia","contato"],"/investigar":["bug","feature","test","audit","incident"],"/investigate":["bug","feature","test","audit","incident"],"/entrada":[],"/saida":[],"/lang":["pt","en","auto"],"/idioma":["pt","en","auto"],"/pomodoro":["start","stop","status"],"/foco":["start","stop","status"],"/monitor":["start","stop","list"],"/vigiar":["start","stop","list"],"/vault":["status","backup","sync","init"],"/workflow":["list","run","info","create","delete","enable","disable"],"/fluxo":["list","run","info","create","delete","ativar","desativar"]};onSubmit=null;onCancel=null;onExit=null;pickerActive=!1;lastCtrlCTime=0;eventUnsubscribers=[];statusBarContext="";activeInsight=null;insightSnippetLines=0;insightDisplayed=!1;metaLearningEntries=[];constructor($,Z,Y="",Q){this.model=$;this.sessionName=Z;this.authInfo=Y;this.dataDir=Q;this.viewManager=new q4}start($){if(this.onSubmit=$.onSubmit,this.onCancel=$.onCancel,this.onExit=$.onExit,this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.dataDir)this.history=new TZ(cH(this.dataDir,"history"));this.setupEventListeners(),O(H.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}setupEventListeners(){this.eventUnsubscribers.push(r.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(r.on("status:update",($)=>{let Z=$.level==="error"?I.err:$.level==="warning"?I.prompt:$.level==="success"?I.sys:H.dim;if(this.lines.push({text:` ${Z}[${$.source}]${H.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(r.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${I.prompt}\u26A0 ${$.message}${H.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${I.err}\u26A0 Rate limit: ${$.message}${H.reset}`});else this.lines.push({text:` ${H.dim}[telemetry] ${$.message}${H.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(r.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${H.dim}[backup] ${$.message||"Backup concluido"}${H.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${I.sys}[pomodoro] ${$.message}${H.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${I.err}[${$.taskType}] ${$.message}${H.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(r.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(r.on("insight:available",($)=>{if(this.isStreaming||this.pickerActive)return;this.showInsight($.insight)}))}cleanupEventListeners(){for(let $ of this.eventUnsubscribers)$();this.eventUnsubscribers=[]}stop(){if(this.stopSpinner(),this.cleanupEventListeners(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),O(H.show),O(H.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=e5(this.streamBuf,this.width).map((Z)=>({text:Z})),this.renderMessages(),this.renderInput()},50)}flushStream(){if(this.streamLines.length>0)this.lines.push(...this.streamLines),this.streamLines=[],this.streamBuf=""}resetStreamBuffer(){this.streamBuf="",this.streamLines=[]}endStream(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer),this.renderTimer=null,this.streamLines=e5(this.streamBuf,this.width).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Y=Z,Q;switch($){case"read_file":if(Q=String(Y.path||""),Y.offset)Q+=`:${Y.offset}`;break;case"write_file":case"edit_file":Q=String(Y.path||"");break;case"search_files":if(Q=`/${Y.pattern||""}/`,Y.include)Q+=` (${Y.include})`;break;case"find_files":Q=String(Y.pattern||"");break;case"list_directory":Q=String(Y.path||".");break;case"run_command":if(Q=String(Y.command||""),Q.length>80)Q=Q.slice(0,77)+"...";break;default:{let J=JSON.stringify(Y);Q=J.length>80?J.slice(0,77)+"...":J}}this.lines.push({text:` ${I.tool}\u2699 ${$}${H.reset} ${H.dim}${Q}${H.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
589
- `),Q=8,J=Y.slice(0,8);for(let z of J){let X=z.length>this.width-6?z.slice(0,this.width-9)+"...":z;this.lines.push({text:` ${H.dim}${X}${H.reset}`})}if(Y.length>8)this.lines.push({text:` ${H.dim}... (${Y.length-8} more lines)${H.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${I.prompt}? ${$}${H.reset} ${H.dim}[y]es / [n]o / [a]ll${H.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(Q)=>{let J=Q.toString().toLowerCase();if(J==="y"||J==="\r"||J===`
590
- `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.sys}approved${H.reset}`}),this.renderAll(),Z(!0);else if(J==="n"||J==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.err}rejected${H.reset}`}),this.renderAll(),Z(!1);else if(J==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.sys}approved all for this session${H.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${H.dim}timeout \u2014 auto-rejected${H.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=$.findIndex((G)=>G.isCurrent);if(Y<0)Y=0;let Q="",J=!1,z=()=>{if(!Q)return $;let G=Q.toLowerCase();return $.filter((q)=>q.name.toLowerCase().includes(G))},X=()=>{let U=this.height-2-2,W=z();if(Y>=W.length)Y=Math.max(0,W.length-1);let B=2,M=2,N=U-B-M,F=Math.max(1,N),j=0;if(W.length>F)j=Math.max(0,Y-Math.floor(F/2)),j=Math.min(j,W.length-F);let p=W.slice(j,j+F);if(O(H.hide),O(H.to(3,1)),O(H.clearLine),J)O(` ${I.heading}${H.bold}Sessions${H.reset} ${H.dim}filter: ${Q}\u2588${H.reset}`);else O(` ${I.heading}${H.bold}Sessions${H.reset} ${H.dim}(${W.length})${H.reset}`);O(H.to(4,1)),O(H.clearLine);for(let b=0;b<F;b++){let $$=2+B+b+1;if(O(H.to($$,1)),O(H.clearLine),b>=p.length)continue;let J$=p[b],y$=j+b===Y,H$=J$.isCurrent?"*":" ",m$=J$.isArchived?`${H.dim}[arch] ${H.reset}`:" ",v0=`${J$.messageCount} msgs`.padEnd(10),G0=oH(J$.updated);if(y$)O(` ${I.prompt}${H.bold}\u203A ${H$} ${m$}${I.prompt}${H.bold}${J$.name.padEnd(20)}${H.reset} ${H.dim}${v0} ${G0}${H.reset}`);else{let q0=J$.isArchived?H.dim:I.sys;O(` ${H$} ${m$}${q0}${J$.name.padEnd(20)}${H.reset} ${H.dim}${v0} ${G0}${H.reset}`)}}for(let b=p.length;b<F;b++){let $$=2+B+b+1;O(H.to($$,1)),O(H.clearLine)}let n=2+B+F+1;if(O(H.to(n,1)),O(H.clearLine),W.length>F){let b=Math.round((Y+1)/W.length*100);O(` ${H.dim}${j>0?"\u2191":" "} ${b}% ${j+F<W.length?"\u2193":" "}${H.reset}`)}let T=this.height-2;O(H.to(T,1)),O(H.clearLine),O(` ${H.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${H.reset}`)},K=(G)=>{this.pickerActive=!1,process.stdin.removeListener("data",V),this.renderAll(),Z(G)},V=(G)=>{let q=G.toString("utf-8"),U=z();if(q==="\x1B"&&G.length===1){if(J)J=!1,Q="",X();else K(null);return}if(q==="\x03"){K(null);return}if(q==="\r"||q===`
591
- `){if(U.length>0&&Y<U.length)K({action:"load",name:U[Y].name});return}if(q==="\x1B[A"||q==="w"&&!J){if(Y>0)Y--,X();return}if(q==="\x1B[B"||q==="s"&&!J){if(Y<U.length-1)Y++,X();return}if(q==="d"&&J===!1){if(U.length>0&&Y<U.length){let W=U[Y];if(!W.isCurrent)K({action:"delete",name:W.name,isArchived:W.isArchived})}return}if(q==="a"&&J===!1){if(U.length>0&&Y<U.length){let W=U[Y];if(!W.isCurrent){let B=W.isArchived?"unarchive":"archive";K({action:B,name:W.name})}}return}if(q==="/"&&J===!1){J=!0,Q="",X();return}if(J){if(q==="\x7F"||q==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,X();else J=!1,X();return}if(q.length===1&&q>=" "){Q+=q,Y=0,X();return}}};process.stdin.on("data",V),X()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=0,Q="",J=!1,z="",X=[...new Set($.map((W)=>W.category))].sort(),K=()=>{let W=z?$.filter((B)=>B.category===z):$;if(Q){let B=Q.toLowerCase();W=W.filter((M)=>M.title.toLowerCase().includes(B)||M.source.toLowerCase().includes(B))}return W},V=(W)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[W]||W},G=()=>{let M=this.height-2-2,N=K();if(Y>=N.length)Y=Math.max(0,N.length-1);let F=2,j=2,p=M-F-j,n=Math.max(1,p),T=0;if(N.length>n)T=Math.max(0,Y-Math.floor(n/2)),T=Math.min(T,N.length-n);let b=N.slice(T,T+n);if(O(H.hide),O(H.to(3,1)),O(H.clearLine),J)O(` ${I.heading}${H.bold}Noticias${H.reset} ${H.dim}filtro: ${Q}\u2588${H.reset}`);else{let v=z?V(z):"Todas";O(` ${I.heading}${H.bold}Noticias${H.reset} ${H.dim}(${N.length}) ${v}${H.reset}`)}O(H.to(4,1)),O(H.clearLine);for(let v=0;v<n;v++){let y$=2+F+v+1;if(O(H.to(y$,1)),O(H.clearLine),v>=b.length)continue;let H$=b[v],m$=T+v===Y,v0=H$.time?`[${H$.time}]`:" ",G0=this.width-30,q0=H$.title.length>G0?H$.title.slice(0,G0-1)+"\u2026":H$.title;if(m$)O(` ${I.prompt}${H.bold}\u203A ${v0} ${q0}${H.reset} ${H.dim}(${H$.source})${H.reset}`);else O(` ${H.dim}${v0}${H.reset} ${I.sys}${q0}${H.reset} ${H.dim}(${H$.source})${H.reset}`)}for(let v=b.length;v<n;v++){let y$=2+F+v+1;O(H.to(y$,1)),O(H.clearLine)}let $$=2+F+n+1;if(O(H.to($$,1)),O(H.clearLine),N.length>n){let v=Math.round((Y+1)/N.length*100);O(` ${H.dim}${T>0?"\u2191":" "} ${v}% ${T+n<N.length?"\u2193":" "}${H.reset}`)}let J$=this.height-2;O(H.to(J$,1)),O(H.clearLine),O(` ${H.dim}\u2191\u2193 navegar Enter abrir Ctrl+Enter ler aqui Esc cancelar / filtrar Tab categoria${H.reset}`)},q=(W)=>{this.pickerActive=!1,process.stdin.removeListener("data",U),this.renderAll(),Z(W)},U=(W)=>{let B=W.toString("utf-8"),M=K();if(B==="\x1B"&&W.length===1){if(J)J=!1,Q="",G();else q(null);return}if(B==="\x03"){q(null);return}if(B===`
592
- `||B==="\x1B\r"||B==="\x1BOM"){if(M.length>0&&Y<M.length)q({action:"read",link:M[Y].link});return}if(B==="\r"||B===`
593
- `){if(M.length>0&&Y<M.length)q({action:"open",link:M[Y].link});return}if(B==="\x1B[A"||B==="w"&&!J){if(Y>0)Y--,G();return}if(B==="\x1B[B"||B==="s"&&!J){if(Y<M.length-1)Y++,G();return}if(B==="\t"){if(!z)z=X[0]||"";else{let N=X.indexOf(z);z=N<X.length-1?X[N+1]:""}Y=0,G();return}if(B==="/"&&!J){J=!0,Q="",G();return}if(J){if(B==="\x7F"||B==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,G();else J=!1,G();return}if(B.length===1&&B>=" "){Q+=B,Y=0,G();return}}};process.stdin.on("data",U),G()})}showUsage($){this.lines.push({text:` ${H.dim}tokens: ${$}${H.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${I.err}\u2717 ${$}${H.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
594
- `))this.lines.push({text:` ${I.sys}${Z}${H.reset}`});this.lines.push({text:""}),this.renderAll()}clearMessages(){this.lines=[],this.renderAll()}updateModel($){this.model=$,this.renderHeader()}updateSession($){this.sessionName=$,this.renderHeader()}enableInput(){this.inputBuf="",this.inputPos=0,this.isStreaming=!1,this.history?.reset(),this.renderInput()}disableInput(){O(H.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),Q2(),this.render()}enterDashboardMode($){this.viewMode="dashboard";let Z=[...$.panels];if(!Z.some((Q)=>Q.id==="meta-learning")&&this.metaLearningEntries.length>0){let Q=Math.floor(this.width/2)-4,J=Z2(this.metaLearningEntries,Q);Z=[...Z,J]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),Y2(3,this.height-2),this.renderDashboard()}updateDashboardPanel($,Z){let Y=this.dashboardContent.find((Q)=>Q.id===$);if(Y){if(Y.content=Z,this.viewMode==="dashboard")this.renderDashboard()}}updateStatusBar($){if($.project!==void 0)this.activeProject=$.project;if($.inputTokens!==void 0)this.inputTokens=$.inputTokens;if($.outputTokens!==void 0)this.outputTokens=$.outputTokens;if($.vaultStatus!==void 0)this.vaultStatus=$.vaultStatus;this.renderStickyStatusBar()}setStatusBarEnabled($){this.statusBarEnabled=$,this.render()}showInsight($){if(this.activeInsight)this.dismissInsight();this.activeInsight=$;let Z=bZ($,{width:this.width-4,showActions:!0});this.insightSnippetLines=Z.length,this.renderInsightDisplay(Z),this.insightDisplayed=!0}renderInsightDisplay($){let Z=this.height-1-this.insightSnippetLines-1;O(H.hide);for(let Y=0;Y<$.length;Y++)O(H.to(Z+Y,1)),O(H.clearLine),O($[Y]);O(H.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;O(H.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)O(H.to($+Z,1)),O(H.clearLine);O(H.show),this.activeInsight=null,this.insightSnippetLines=0,this.insightDisplayed=!1,this.renderMessages()}acceptInsight(){if(!this.activeInsight)return;let $=this.activeInsight,Z={insightId:$.id,insight:$,timestamp:Date.now()};if(r.emit("insight:accepted",Z),this.lines.push({text:` ${I.sys}\u2713 Dica aceita: ${$.title}${H.reset}`}),$.suggestedAction)this.lines.push({text:` ${H.dim}Executando: ${$.suggestedAction.command}${H.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=Z2($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=DZ($),this.renderHeader(),this.statusBarEnabled)this.renderStickyStatusBar()}setTimeContext($){this.timeContext=$,this.setPersonaMode($.persona)}getPersonaMode(){return this.personaMode}getPalette(){return this.palette}getPersonaLabel(){switch(this.personaMode){case"productivity":return"PROD";case"spillover_alert":return"SPILL";case"sharpen_or_relax":return"RELAX"}}addMetaLearningEntry($){if(this.metaLearningEntries.find((Y)=>Y.title===$.title))this.metaLearningEntries=this.metaLearningEntries.map((Y)=>Y.title===$.title?{...Y,frequency:Y.frequency+1,lastSeen:Date.now()}:Y);else this.metaLearningEntries=[...this.metaLearningEntries,{...$,frequency:1,lastSeen:Date.now()}]}renderDashboard(){O(H.hide),O(H.clear),this.renderHeader();let $=2,Z=2+(this.statusBarEnabled?1:0),Y=this.height-$-Z,Q=this.dashboardContent,J=Math.min(2,Q.length),z=Math.ceil(Q.length/J),X=1,K=Math.floor((this.width-X*(J+1))/J),V=Math.floor((Y-X*(z+1))/z),G=0;for(let q=0;q<z;q++)for(let U=0;U<J&&G<Q.length;U++){let W=Q[G],B=$+X+q*(V+X)+1,M=X+U*(K+X)+1;this.drawDashboardPanel(W,B,M,K,V),G++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),O(H.show)}drawDashboardPanel($,Z,Y,Q,J){let z=this.personaMode==="sharpen_or_relax"?this.palette.muted:H.dim,X=this.palette.primary,K=G4($.content.slice(0,J-2),Q,{title:$.title,borderColor:z,titleColor:X});for(let V=0;V<K.length&&V<J;V++)O(H.to(Z+V,Y)),O(K[V])}renderStickyStatusBar(){if(!this.statusBarEnabled)return;let $=this.height-2;this.stickyStatusRow=$;let Z=[];if(this.personaMode!=="productivity"){let Q=this.personaMode==="spillover_alert"?this.palette.accent:this.palette.primary;Z.push({label:"MODE",value:this.getPersonaLabel(),color:Q})}if(this.timeContext&&this.personaMode==="spillover_alert"){let Q=this.timeContext.urgentTasks.length+this.timeContext.overdueTasks.length+this.timeContext.pendingCommits.length;if(Q>0)Z.push({label:"PEND",value:String(Q),color:this.palette.accent})}let Y={model:this.model,project:this.activeProject||void 0,tokens:{input:this.inputTokens,output:this.outputTokens},sessionCost:this.sessionCost||void 0,vaultStatus:this.vaultStatus,customItems:Z.length>0?Z:void 0};O(H.to($,1)),O(this.renderPersonaAwareStatusBar(Y))}renderPersonaAwareStatusBar($){let Z=V4($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${y0(Z)}${H.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(O(H.hide),O(H.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),O(H.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){O(H.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();O(Z),O(H.inv);let Q=` smolerclaw${this.personaMode!=="productivity"?` [${this.getPersonaLabel()}]`:""}`,J=[this.model,this.sessionName];if(this.sessionCost)J.push(this.sessionCost);if(this.authInfo)J.push(this.authInfo);let z=J.join(" | ")+" ",X=Math.max(1,this.width-V$(Q)-z.length);O(Q+" ".repeat(X)+z),O(H.reset),O(H.to(2,1));let K=this.personaMode==="sharpen_or_relax"?this.palette.muted:H.dim;O(`${K}${"\u2500".repeat(this.width)}${H.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return H.bg(52);case"sharpen_or_relax":return H.bg(53)}}renderMessages(){let Y=2+(this.statusBarEnabled?1:0),Q=this.height-2-Y,J=[...this.lines,...this.streamLines],z=J.length,X=Math.max(0,z-Q-this.scrollOffset),K=Math.min(z,X+Q),V=J.slice(X,K);O(H.hide);for(let G=0;G<Q;G++)if(O(H.to(2+G+1,1)),O(H.clearLine),G<V.length)O(V[G].text)}completeInput($){let Z=$.split(" "),Y=Z[0];if(Z.length===1){let X=this.commands.filter((K)=>K.startsWith(Y));if(X.length===1){let K=this.subcommands[X[0]];if(K&&K.length>0)return{value:X[0]+" ",options:`Opcoes: ${K.join(" ")}`};return{value:X[0]+" "}}if(X.length>1){let K=X[0];for(let V of X)while(!V.startsWith(K))K=K.slice(0,-1);return{value:K.length>$.length?K:$,options:X.join(" ")}}return null}let Q=this.subcommands[Y];if(!Q||Q.length===0)return null;let J=Z[Z.length-1].toLowerCase(),z=Q.filter((X)=>X.toLowerCase().startsWith(J));if(z.length===1)return Z[Z.length-1]=z[0],{value:Z.join(" ")+" "};if(z.length>1){let X=z[0];for(let K of z)while(!K.toLowerCase().startsWith(X.toLowerCase()))X=X.slice(0,-1);if(X.length>J.length)return Z[Z.length-1]=X,{value:Z.join(" "),options:z.join(" ")};return{value:$,options:z.join(" ")}}if(!J&&Q.length>0)return{value:$,options:Q.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(O(H.to($,1)),O(H.clearLine),O(`${H.dim}${"\u2500".repeat(this.width)}${H.reset}`),O(H.to(Z,1)),O(H.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);O(` ${I.ai}${this.getSpinnerChar()}${H.reset} ${H.dim}streaming... ${Y}s${H.reset}`),O(H.hide)}else{let Y=V$(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;O(`${I.prompt}\u276F${H.reset} ${Y}`);let Q=this.inputBuf.slice(0,this.inputPos),J=V$(Q)+3;O(H.to(Z,Math.min(J,this.width))),O(H.show)}}onKey($){if(this.pickerActive)return;let Z=$.toString("utf-8");if(this.hasActiveInsight()){let Y=Z.toLowerCase();if(Y==="y"){this.acceptInsight();return}if(Y==="n"||Z==="\x1B"){this.dismissInsight();return}this.dismissInsight()}if(Z==="\x03"){if(this.isStreaming){this.onCancel?.();return}let Y=Date.now(),Q=1500;if(this.inputBuf.length>0){this.inputBuf="",this.inputPos=0,this.lastCtrlCTime=Y,this.renderInput();return}if(Y-this.lastCtrlCTime<Q){this.onExit?.();return}this.lastCtrlCTime=Y,this.showSystem("Pressione Ctrl+C novamente para sair.");return}if(Z==="\x04"){this.onExit?.();return}if(Z==="\f"){this.render();return}if(this.isStreaming)return;if(Z==="\t"){if(this.inputBuf.startsWith("/")){let Y=this.completeInput(this.inputBuf);if(Y){if(this.inputBuf=Y.value,this.inputPos=this.inputBuf.length,this.renderInput(),Y.options)this.showSystem(Y.options)}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!Cz(Z)){let Y=Z.replace(/\r?\n/g," ").trim();if(Y.length>0)this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Y+this.inputBuf.slice(this.inputPos),this.inputPos+=Y.length,this.renderInput();return}if(Z==="\r"||Z===`
597
+ `)}catch{}}}import{join as PB}from"path";var UB=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],qB=" ";function Z9($,Z={}){let{width:Y=$.length,min:Q=Math.min(...$),max:z=Math.max(...$),color:J="",showBounds:X=!1}=Z;if($.length===0)return"";let K=LB($,Y),G=z-Q||1,U=K.map((H)=>{if(H===0&&Q===0)return qB;let B=(H-Q)/G,O=Math.min(7,Math.floor(B*8));return UB[O]}).join(""),q=J?`${J}${U}${W.reset}`:U;if(X)return`${W.dim}${Q.toFixed(0)}${W.reset}${q}${W.dim}${z.toFixed(0)}${W.reset}`;return q}var HB="\u2588",WB="\u2589",BB="\u258A",OB="\u258B",NB="\u258C",MB="\u258D",CB="\u258E",EB="\u258F",RB="\u2591",FB=[" ",EB,CB,MB,NB,OB,BB,WB];function Y9($,Z={}){let{width:Y=20,maxValue:Q=100,showValue:z=!0,color:J=W.fg(75),label:X=""}=Z,K=Math.min(1,Math.max(0,$/Q)),G=Math.floor(K*Y),V=K*Y-G,U=Math.floor(V*8),q=HB.repeat(G);if(U>0&&G<Y)q+=FB[U];let H=Y-W0(q);q+=RB.repeat(Math.max(0,H));let B=J?`${J}${q}${W.reset}`:q,O=[];if(X)O.push(`${W.dim}${X.padEnd(12)}${W.reset}`);if(O.push(B),z)O.push(` ${W.dim}${$.toFixed(1)}%${W.reset}`);return O.join("")}function C8($,Z){let Y=[];if(Y.push(`${I.ai}${$.model}${W.reset}`),$.project)Y.push(`${I.heading}${$.project}${W.reset}`);if($.tokens){let{input:X,output:K}=$.tokens;Y.push(`${W.dim}${qX(X)}/${qX(K)} tok${W.reset}`)}if($.sessionCost)Y.push(`${W.dim}${$.sessionCost}${W.reset}`);if($.vaultStatus){let X=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",K=$.vaultStatus==="ok"?W.fg(114):$.vaultStatus==="warn"?W.fg(220):W.fg(196);Y.push(`${K}${X}${W.reset}`)}if($.customItems)for(let X of $.customItems){let K=X.color||"";Y.push(`${W.dim}${X.label}:${W.reset}${K}${X.value}${W.reset}`)}let Q=Y.join(` ${W.dim}\u2502${W.reset} `),z=W0(Q),J=Math.max(0,Z-z-2);return`${W.inv} ${Q}${" ".repeat(J)} ${W.reset}`}function Q9($,Z=40){let Y=[];Y.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),Y.push(`${I.heading}${W.bold} System${W.reset}`);let Q=Z9($.cpu,{width:15,color:W.fg(75)}),z=Y9($.currentCpu,{width:10,showValue:!1,color:W.fg(75)});Y.push(` ${W.dim}CPU:${W.reset} ${Q} ${z} ${$.currentCpu.toFixed(0)}%`);let J=Z9($.memory,{width:15,color:W.fg(114)}),X=Y9($.currentMem,{width:10,showValue:!1,color:W.fg(114)});return Y.push(` ${W.dim}MEM:${W.reset} ${J} ${X} ${$.currentMem.toFixed(0)}%`),Y.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),Y}function LB($,Z){if($.length<=Z){let z=[...$];while(z.length<Z)z.unshift(0);return z}let Y=$.length/Z,Q=[];for(let z=0;z<Z;z++){let J=Math.floor(z*Y),X=Math.floor((z+1)*Y),K=$.slice(J,X),G=K.reduce((V,U)=>V+U,0)/K.length;Q.push(G)}return Q}function qX($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function E8($,Z,Y={}){let{title:Q="",padding:z=1,borderColor:J=W.dim,titleColor:X=I.heading}=Y,K=Z-2-z*2,G=[];if(Q){let U=W0(Q),q=2,H=Math.max(1,Z-U-2-4);G.push(`${J}\u250C${"\u2500".repeat(2)}${W.reset}${X}${W.bold} ${Q} ${W.reset}${J}${"\u2500".repeat(H)}\u2510${W.reset}`)}else G.push(`${J}\u250C${"\u2500".repeat(Z-2)}\u2510${W.reset}`);let V=" ".repeat(z);for(let U of $){let q=W0(U)>K?v1(U,K):[U];for(let H of q){let B=W0(H),O=Math.max(0,K-B);G.push(`${J}\u2502${W.reset}${V}${H}${" ".repeat(O)}${V}${J}\u2502${W.reset}`)}}return G.push(`${J}\u2514${"\u2500".repeat(Z-2)}\u2518${W.reset}`),G}function z9($,Z,Y,Q,z={}){let J=E8($,Q,z);for(let X=0;X<J.length;X++)E(W.to(Z+X,Y)),E(J[X])}var B7={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},jB={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function J9($,Z={}){let{width:Y=60,showActions:Q=!0,compact:z=!1}=Z,J=[],X=jB[$.category]||"\uD83D\uDCA1",K=B7.dimYellow+B7.italic;if(z){let U=$.title.length>Y-10?$.title.slice(0,Y-13)+"...":$.title;return J.push(` ${K}${X} ${U}${W.reset}`),J}J.push(` ${K}${X} ${$.title}${W.reset}`);let G=Y-6,V=v1($.explanation,G);for(let U of V)J.push(` ${K} ${x1(U)}${W.reset}`);if($.suggestedAction)J.push(` ${B7.dimCyan} \u2192 ${$.suggestedAction.label}${W.reset}`);if(Q)J.push(` ${W.dim} [Y] Aceitar [N] Ignorar${W.reset}`);return J}function HX($,Z=40){let Y=[],Q=[...$].sort((z,J)=>J.frequency-z.frequency).slice(0,3);if(Q.length===0)return Y.push(`${W.dim} Nenhuma dica disponivel ainda.${W.reset}`),Y.push(`${W.dim} Continue usando para gerar insights.${W.reset}`),Y;for(let z=0;z<Q.length;z++){let J=Q[z],X=z+1,K=X===1?"\uD83E\uDD47":X===2?"\uD83E\uDD48":"\uD83E\uDD49",G=Z-8,V=J.title.length>G?J.title.slice(0,G-3)+"...":J.title;Y.push(`${K} ${B7.dimYellow}${V}${W.reset}`);let U=Z-4,q=J.description.length>U?J.description.slice(0,U-3)+"...":J.description;Y.push(` ${W.dim}${q}${W.reset}`);let H=J.frequency===1?"vez":"vezes";if(Y.push(` ${W.dim}Detectado ${J.frequency}x${W.reset}`),z<Q.length-1)Y.push("")}return Y}function O7($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:HX($,Z)}}class R8{mode="chat";width;height;statusBarEnabled=!0;statusConfig=null;dashboardLayout=null;savedChatLines=[];resizeCallbacks=[];constructor(){this.width=process.stdout.columns||80,this.height=process.stdout.rows||24}getMode(){return this.mode}getViewState(){let Z=this.statusBarEnabled&&this.statusConfig?this.height:0;return{mode:this.mode,width:this.width,height:this.height,statusBarRow:Z,contentStartRow:3,contentEndRow:this.height-2,inputRow:this.height}}enterChatMode(){if(this.mode==="chat")return;this.mode="chat",this.clearScreen()}enterDashboardMode($){this.mode="dashboard",this.dashboardLayout=$,this.clearScreen(),this.renderDashboard()}toggleMode(){if(this.mode==="chat")return;this.enterChatMode()}setStatusBar($){this.statusConfig=$}enableStatusBar($){this.statusBarEnabled=$}renderStatusBar(){if(!this.statusBarEnabled||!this.statusConfig)return;let $=this.height-1;E(W.to($,1)),E(C8(this.statusConfig,this.width))}clearScreen(){E(W.clear),E(W.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)E(W.to(Z,1)),E(W.clearLine)}updateDimensions($,Z){this.width=$,this.height=Z;for(let Y of this.resizeCallbacks)Y()}onResize($){this.resizeCallbacks.push($)}removeResizeCallback($){this.resizeCallbacks=this.resizeCallbacks.filter((Z)=>Z!==$)}renderDashboard(){if(this.mode!=="dashboard"||!this.dashboardLayout)return;this.clearContentArea();let{panels:$,columns:Z=2,gap:Y=1}=this.dashboardLayout,Q=this.getViewState(),z=Q.contentEndRow-Q.contentStartRow,J=Math.floor((this.width-Y*(Z+1))/Z),X=Q.contentStartRow,K=1+Y;for(let G=0;G<$.length;G++){let V=$[G],U=V.row??X,q=V.col??K,H=V.width??J,B=V.height??Math.floor(z/Math.ceil($.length/Z));if(this.drawDashboardPanel(V,U,q,H,B),(G+1)%Z===0)X+=B+Y,K=1+Y;else K+=H+Y}this.renderStatusBar()}drawDashboardPanel($,Z,Y,Q,z){let J=z-2,X=$.content.slice(0,J);z9(X,Z,Y,Q,{title:$.title})}createMorningBriefingLayout($){let Z=[{id:"tasks",title:"Tarefas do Dia",content:$.tasks.length>0?$.tasks:["Nenhuma tarefa para hoje"]},{id:"followups",title:"Follow-ups",content:$.followUps.length>0?$.followUps:["Nenhum follow-up pendente"]},{id:"calendar",title:"Agenda",content:$.calendar.length>0?$.calendar:["Sem eventos hoje"]},{id:"news",title:"Noticias",content:$.news.length>0?$.news:["Sem noticias recentes"]}];if($.projectSummary)Z.push({id:"project",title:"Projetos",content:$.projectSummary});return{panels:Z,columns:2,gap:1}}createMonitoringLayout($){return{panels:[{id:"telemetry",title:"Sistema",content:Q9($,35)}],columns:1,gap:1}}}function N7($,Z){E(`\x1B[${$};${Z}r`)}function M7(){E("\x1B[r")}var AB=new R8;u0();class X9{model;sessionName;authInfo;dataDir;width=80;height=24;lines=[];streamBuf="";streamLines=[];inputBuf="";inputPos=0;isStreaming=!1;scrollOffset=0;history=null;renderTimer=null;spinnerFrame=0;spinnerTimer=null;streamStartTime=0;sessionCost="";viewMode="chat";viewManager;dashboardContent=[];statusBarEnabled=!0;inputTokens=0;outputTokens=0;activeProject="";vaultStatus="ok";stickyStatusRow=0;personaMode="productivity";palette=sZ("productivity");timeContext=null;commands=["/help","/clear","/commit","/persona","/copy","/fork","/new","/load","/sessions","/delete","/model","/export","/cost","/retry","/undo","/search","/lang","/config","/exit","/briefing","/news","/open","/openfile","/openurl","/apps","/sysinfo","/calendar","/ask","/budget","/plugins","/task","/tasks","/done","/rmtask","/people","/team","/family","/person","/addperson","/delegate","/delegations","/followups","/dashboard","/contacts","/investigar","/investigate","/investigacoes","/monitor","/vigiar","/workflow","/fluxo","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/index","/indexar","/reindex","/memory","/memoria","/clipboard","/area","/tela","/screen","/ps1","/refresh","/renovar","/vault","/backup","/feeds","/fontes","/addfeed","/novafonte","/rmfeed","/rmfonte","/disablefeed","/desativarfonte","/enablefeed","/ativarfonte","/projeto","/project","/projetos","/projects","/sessao","/session","/relatorio","/report","/oportunidades","/opportunities","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];subcommands={"/model":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/modelo":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/news":["business","tech","finance","brazil","world","security"],"/noticias":["business","tech","finance","brazil","world","security"],"/open":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/abrir":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/sessao":["start","stop","status"],"/session":["start","stop","status"],"/relatorio":["today","week","month"],"/report":["today","week","month"],"/projeto":["auto"],"/project":["auto"],"/oportunidades":["nova","em_analise","aceita","recusada","concluida"],"/opportunities":["nova","em_analise","aceita","recusada","concluida"],"/persona":["default","business"],"/modo":["default","business"],"/people":["equipe","familia","contato"],"/pessoas":["equipe","familia","contato"],"/investigar":["bug","feature","test","audit","incident"],"/investigate":["bug","feature","test","audit","incident"],"/entrada":[],"/saida":[],"/lang":["pt","en","auto"],"/idioma":["pt","en","auto"],"/pomodoro":["start","stop","status"],"/foco":["start","stop","status"],"/monitor":["start","stop","list"],"/vigiar":["start","stop","list"],"/vault":["status","backup","sync","init"],"/workflow":["list","run","info","create","delete","enable","disable"],"/fluxo":["list","run","info","create","delete","ativar","desativar"]};onSubmit=null;onCancel=null;onExit=null;pickerActive=!1;lastCtrlCTime=0;eventUnsubscribers=[];statusBarContext="";activeInsight=null;insightSnippetLines=0;insightDisplayed=!1;metaLearningEntries=[];constructor($,Z,Y="",Q){this.model=$;this.sessionName=Z;this.authInfo=Y;this.dataDir=Q;this.viewManager=new R8}start($){if(this.onSubmit=$.onSubmit,this.onCancel=$.onCancel,this.onExit=$.onExit,this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.dataDir)this.history=new $9(PB(this.dataDir,"history"));this.setupEventListeners(),E(W.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}setupEventListeners(){this.eventUnsubscribers.push(t.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(t.on("status:update",($)=>{let Z=$.level==="error"?I.err:$.level==="warning"?I.prompt:$.level==="success"?I.sys:W.dim;if(this.lines.push({text:` ${Z}[${$.source}]${W.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(t.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${I.prompt}\u26A0 ${$.message}${W.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${I.err}\u26A0 Rate limit: ${$.message}${W.reset}`});else this.lines.push({text:` ${W.dim}[telemetry] ${$.message}${W.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(t.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${W.dim}[backup] ${$.message||"Backup concluido"}${W.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${I.sys}[pomodoro] ${$.message}${W.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${I.err}[${$.taskType}] ${$.message}${W.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(t.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(t.on("insight:available",($)=>{if(this.isStreaming||this.pickerActive)return;this.showInsight($.insight)}))}cleanupEventListeners(){for(let $ of this.eventUnsubscribers)$();this.eventUnsubscribers=[]}stop(){if(this.stopSpinner(),this.cleanupEventListeners(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),E(W.show),E(W.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=W7(this.streamBuf,this.width).map((Z)=>({text:Z})),this.renderMessages(),this.renderInput()},50)}flushStream(){if(this.streamLines.length>0)this.lines.push(...this.streamLines),this.streamLines=[],this.streamBuf=""}resetStreamBuffer(){this.streamBuf="",this.streamLines=[]}endStream(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer),this.renderTimer=null,this.streamLines=W7(this.streamBuf,this.width).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Y=Z,Q;switch($){case"read_file":if(Q=String(Y.path||""),Y.offset)Q+=`:${Y.offset}`;break;case"write_file":case"edit_file":Q=String(Y.path||"");break;case"search_files":if(Q=`/${Y.pattern||""}/`,Y.include)Q+=` (${Y.include})`;break;case"find_files":Q=String(Y.pattern||"");break;case"list_directory":Q=String(Y.path||".");break;case"run_command":if(Q=String(Y.command||""),Q.length>80)Q=Q.slice(0,77)+"...";break;default:{let z=JSON.stringify(Y);Q=z.length>80?z.slice(0,77)+"...":z}}this.lines.push({text:` ${I.tool}\u2699 ${$}${W.reset} ${W.dim}${Q}${W.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
598
+ `),Q=8,z=Y.slice(0,8);for(let J of z){let X=J.length>this.width-6?J.slice(0,this.width-9)+"...":J;this.lines.push({text:` ${W.dim}${X}${W.reset}`})}if(Y.length>8)this.lines.push({text:` ${W.dim}... (${Y.length-8} more lines)${W.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${I.prompt}? ${$}${W.reset} ${W.dim}[y]es / [n]o / [a]ll${W.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(Q)=>{let z=Q.toString().toLowerCase();if(z==="y"||z==="\r"||z===`
599
+ `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.sys}approved${W.reset}`}),this.renderAll(),Z(!0);else if(z==="n"||z==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.err}rejected${W.reset}`}),this.renderAll(),Z(!1);else if(z==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.sys}approved all for this session${W.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${W.dim}timeout \u2014 auto-rejected${W.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=$.findIndex((V)=>V.isCurrent);if(Y<0)Y=0;let Q="",z=!1,J=()=>{if(!Q)return $;let V=Q.toLowerCase();return $.filter((U)=>U.name.toLowerCase().includes(V))},X=()=>{let q=this.height-2-2,H=J();if(Y>=H.length)Y=Math.max(0,H.length-1);let B=2,O=2,M=q-B-O,C=Math.max(1,M),F=0;if(H.length>C)F=Math.max(0,Y-Math.floor(C/2)),F=Math.min(F,H.length-C);let k=H.slice(F,F+C);if(E(W.hide),E(W.to(3,1)),E(W.clearLine),z)E(` ${I.heading}${W.bold}Sessions${W.reset} ${W.dim}filter: ${Q}\u2588${W.reset}`);else E(` ${I.heading}${W.bold}Sessions${W.reset} ${W.dim}(${H.length})${W.reset}`);E(W.to(4,1)),E(W.clearLine);for(let f=0;f<C;f++){let g=2+B+f+1;if(E(W.to(g,1)),E(W.clearLine),f>=k.length)continue;let Y0=k[f],G0=F+f===Y,c=Y0.isCurrent?"*":" ",V0=Y0.isArchived?`${W.dim}[arch] ${W.reset}`:" ",h0=`${Y0.messageCount} msgs`.padEnd(10),j0=TB(Y0.updated);if(G0)E(` ${I.prompt}${W.bold}\u203A ${c} ${V0}${I.prompt}${W.bold}${Y0.name.padEnd(20)}${W.reset} ${W.dim}${h0} ${j0}${W.reset}`);else{let M0=Y0.isArchived?W.dim:I.sys;E(` ${c} ${V0}${M0}${Y0.name.padEnd(20)}${W.reset} ${W.dim}${h0} ${j0}${W.reset}`)}}for(let f=k.length;f<C;f++){let g=2+B+f+1;E(W.to(g,1)),E(W.clearLine)}let d=2+B+C+1;if(E(W.to(d,1)),E(W.clearLine),H.length>C){let f=Math.round((Y+1)/H.length*100);E(` ${W.dim}${F>0?"\u2191":" "} ${f}% ${F+C<H.length?"\u2193":" "}${W.reset}`)}let D=this.height-2;E(W.to(D,1)),E(W.clearLine),E(` ${W.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${W.reset}`)},K=(V)=>{this.pickerActive=!1,process.stdin.removeListener("data",G),this.renderAll(),Z(V)},G=(V)=>{let U=V.toString("utf-8"),q=J();if(U==="\x1B"&&V.length===1){if(z)z=!1,Q="",X();else K(null);return}if(U==="\x03"){K(null);return}if(U==="\r"||U===`
600
+ `){if(q.length>0&&Y<q.length)K({action:"load",name:q[Y].name});return}if(U==="\x1B[A"||U==="w"&&!z){if(Y>0)Y--,X();return}if(U==="\x1B[B"||U==="s"&&!z){if(Y<q.length-1)Y++,X();return}if(U==="d"&&z===!1){if(q.length>0&&Y<q.length){let H=q[Y];if(!H.isCurrent)K({action:"delete",name:H.name,isArchived:H.isArchived})}return}if(U==="a"&&z===!1){if(q.length>0&&Y<q.length){let H=q[Y];if(!H.isCurrent){let B=H.isArchived?"unarchive":"archive";K({action:B,name:H.name})}}return}if(U==="/"&&z===!1){z=!0,Q="",X();return}if(z){if(U==="\x7F"||U==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,X();else z=!1,X();return}if(U.length===1&&U>=" "){Q+=U,Y=0,X();return}}};process.stdin.on("data",G),X()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=0,Q="",z=!1,J="",X=[...new Set($.map((H)=>H.category))].sort(),K=()=>{let H=J?$.filter((B)=>B.category===J):$;if(Q){let B=Q.toLowerCase();H=H.filter((O)=>O.title.toLowerCase().includes(B)||O.source.toLowerCase().includes(B))}return H},G=(H)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[H]||H},V=()=>{let O=this.height-2-2,M=K();if(Y>=M.length)Y=Math.max(0,M.length-1);let C=2,F=2,k=O-C-F,d=Math.max(1,k),D=0;if(M.length>d)D=Math.max(0,Y-Math.floor(d/2)),D=Math.min(D,M.length-d);let f=M.slice(D,D+d);if(E(W.hide),E(W.to(3,1)),E(W.clearLine),z)E(` ${I.heading}${W.bold}Noticias${W.reset} ${W.dim}filtro: ${Q}\u2588${W.reset}`);else{let _=J?G(J):"Todas";E(` ${I.heading}${W.bold}Noticias${W.reset} ${W.dim}(${M.length}) ${_}${W.reset}`)}E(W.to(4,1)),E(W.clearLine);for(let _=0;_<d;_++){let G0=2+C+_+1;if(E(W.to(G0,1)),E(W.clearLine),_>=f.length)continue;let c=f[_],V0=D+_===Y,h0=c.time?`[${c.time}]`:" ",j0=this.width-30,M0=c.title.length>j0?c.title.slice(0,j0-1)+"\u2026":c.title;if(V0)E(` ${I.prompt}${W.bold}\u203A ${h0} ${M0}${W.reset} ${W.dim}(${c.source})${W.reset}`);else E(` ${W.dim}${h0}${W.reset} ${I.sys}${M0}${W.reset} ${W.dim}(${c.source})${W.reset}`)}for(let _=f.length;_<d;_++){let G0=2+C+_+1;E(W.to(G0,1)),E(W.clearLine)}let g=2+C+d+1;if(E(W.to(g,1)),E(W.clearLine),M.length>d){let _=Math.round((Y+1)/M.length*100);E(` ${W.dim}${D>0?"\u2191":" "} ${_}% ${D+d<M.length?"\u2193":" "}${W.reset}`)}let Y0=this.height-2;E(W.to(Y0,1)),E(W.clearLine),E(` ${W.dim}\u2191\u2193 navegar Enter abrir Ctrl+Enter ler aqui Esc cancelar / filtrar Tab categoria${W.reset}`)},U=(H)=>{this.pickerActive=!1,process.stdin.removeListener("data",q),this.renderAll(),Z(H)},q=(H)=>{let B=H.toString("utf-8"),O=K();if(B==="\x1B"&&H.length===1){if(z)z=!1,Q="",V();else U(null);return}if(B==="\x03"){U(null);return}if(B===`
601
+ `||B==="\x1B\r"||B==="\x1BOM"){if(O.length>0&&Y<O.length)U({action:"read",link:O[Y].link});return}if(B==="\r"||B===`
602
+ `){if(O.length>0&&Y<O.length)U({action:"open",link:O[Y].link});return}if(B==="\x1B[A"||B==="w"&&!z){if(Y>0)Y--,V();return}if(B==="\x1B[B"||B==="s"&&!z){if(Y<O.length-1)Y++,V();return}if(B==="\t"){if(!J)J=X[0]||"";else{let M=X.indexOf(J);J=M<X.length-1?X[M+1]:""}Y=0,V();return}if(B==="/"&&!z){z=!0,Q="",V();return}if(z){if(B==="\x7F"||B==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,V();else z=!1,V();return}if(B.length===1&&B>=" "){Q+=B,Y=0,V();return}}};process.stdin.on("data",q),V()})}showUsage($){this.lines.push({text:` ${W.dim}tokens: ${$}${W.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${I.err}\u2717 ${$}${W.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
603
+ `))this.lines.push({text:` ${I.sys}${Z}${W.reset}`});this.lines.push({text:""}),this.renderAll()}clearMessages(){this.lines=[],this.renderAll()}updateModel($){this.model=$,this.renderHeader()}updateSession($){this.sessionName=$,this.renderHeader()}enableInput(){this.inputBuf="",this.inputPos=0,this.isStreaming=!1,this.history?.reset(),this.renderInput()}disableInput(){E(W.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),M7(),this.render()}enterDashboardMode($){this.viewMode="dashboard";let Z=[...$.panels];if(!Z.some((Q)=>Q.id==="meta-learning")&&this.metaLearningEntries.length>0){let Q=Math.floor(this.width/2)-4,z=O7(this.metaLearningEntries,Q);Z=[...Z,z]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),N7(3,this.height-2),this.renderDashboard()}updateDashboardPanel($,Z){let Y=this.dashboardContent.find((Q)=>Q.id===$);if(Y){if(Y.content=Z,this.viewMode==="dashboard")this.renderDashboard()}}updateStatusBar($){if($.project!==void 0)this.activeProject=$.project;if($.inputTokens!==void 0)this.inputTokens=$.inputTokens;if($.outputTokens!==void 0)this.outputTokens=$.outputTokens;if($.vaultStatus!==void 0)this.vaultStatus=$.vaultStatus;this.renderStickyStatusBar()}setStatusBarEnabled($){this.statusBarEnabled=$,this.render()}showInsight($){if(this.activeInsight)this.dismissInsight();this.activeInsight=$;let Z=J9($,{width:this.width-4,showActions:!0});this.insightSnippetLines=Z.length,this.renderInsightDisplay(Z),this.insightDisplayed=!0}renderInsightDisplay($){let Z=this.height-1-this.insightSnippetLines-1;E(W.hide);for(let Y=0;Y<$.length;Y++)E(W.to(Z+Y,1)),E(W.clearLine),E($[Y]);E(W.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;E(W.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)E(W.to($+Z,1)),E(W.clearLine);E(W.show),this.activeInsight=null,this.insightSnippetLines=0,this.insightDisplayed=!1,this.renderMessages()}acceptInsight(){if(!this.activeInsight)return;let $=this.activeInsight,Z={insightId:$.id,insight:$,timestamp:Date.now()};if(t.emit("insight:accepted",Z),this.lines.push({text:` ${I.sys}\u2713 Dica aceita: ${$.title}${W.reset}`}),$.suggestedAction)this.lines.push({text:` ${W.dim}Executando: ${$.suggestedAction.command}${W.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=O7($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=sZ($),this.renderHeader(),this.statusBarEnabled)this.renderStickyStatusBar()}setTimeContext($){this.timeContext=$,this.setPersonaMode($.persona)}getPersonaMode(){return this.personaMode}getPalette(){return this.palette}getPersonaLabel(){switch(this.personaMode){case"productivity":return"PROD";case"spillover_alert":return"SPILL";case"sharpen_or_relax":return"RELAX"}}addMetaLearningEntry($){if(this.metaLearningEntries.find((Y)=>Y.title===$.title))this.metaLearningEntries=this.metaLearningEntries.map((Y)=>Y.title===$.title?{...Y,frequency:Y.frequency+1,lastSeen:Date.now()}:Y);else this.metaLearningEntries=[...this.metaLearningEntries,{...$,frequency:1,lastSeen:Date.now()}]}renderDashboard(){E(W.hide),E(W.clear),this.renderHeader();let $=2,Z=2+(this.statusBarEnabled?1:0),Y=this.height-$-Z,Q=this.dashboardContent,z=Math.min(2,Q.length),J=Math.ceil(Q.length/z),X=1,K=Math.floor((this.width-X*(z+1))/z),G=Math.floor((Y-X*(J+1))/J),V=0;for(let U=0;U<J;U++)for(let q=0;q<z&&V<Q.length;q++){let H=Q[V],B=$+X+U*(G+X)+1,O=X+q*(K+X)+1;this.drawDashboardPanel(H,B,O,K,G),V++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(W.show)}drawDashboardPanel($,Z,Y,Q,z){let J=this.personaMode==="sharpen_or_relax"?this.palette.muted:W.dim,X=this.palette.primary,K=E8($.content.slice(0,z-2),Q,{title:$.title,borderColor:J,titleColor:X});for(let G=0;G<K.length&&G<z;G++)E(W.to(Z+G,Y)),E(K[G])}renderStickyStatusBar(){if(!this.statusBarEnabled)return;let $=this.height-2;this.stickyStatusRow=$;let Z=[];if(this.personaMode!=="productivity"){let Q=this.personaMode==="spillover_alert"?this.palette.accent:this.palette.primary;Z.push({label:"MODE",value:this.getPersonaLabel(),color:Q})}if(this.timeContext&&this.personaMode==="spillover_alert"){let Q=this.timeContext.urgentTasks.length+this.timeContext.overdueTasks.length+this.timeContext.pendingCommits.length;if(Q>0)Z.push({label:"PEND",value:String(Q),color:this.palette.accent})}let Y={model:this.model,project:this.activeProject||void 0,tokens:{input:this.inputTokens,output:this.outputTokens},sessionCost:this.sessionCost||void 0,vaultStatus:this.vaultStatus,customItems:Z.length>0?Z:void 0};E(W.to($,1)),E(this.renderPersonaAwareStatusBar(Y))}renderPersonaAwareStatusBar($){let Z=C8($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${x1(Z)}${W.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(E(W.hide),E(W.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(W.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){E(W.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();E(Z),E(W.inv);let Q=` smolerclaw${this.personaMode!=="productivity"?` [${this.getPersonaLabel()}]`:""}`,z=[this.model,this.sessionName];if(this.sessionCost)z.push(this.sessionCost);if(this.authInfo)z.push(this.authInfo);let J=z.join(" | ")+" ",X=Math.max(1,this.width-W0(Q)-J.length);E(Q+" ".repeat(X)+J),E(W.reset),E(W.to(2,1));let K=this.personaMode==="sharpen_or_relax"?this.palette.muted:W.dim;E(`${K}${"\u2500".repeat(this.width)}${W.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return W.bg(52);case"sharpen_or_relax":return W.bg(53)}}renderMessages(){let Y=2+(this.statusBarEnabled?1:0),Q=this.height-2-Y,z=[...this.lines,...this.streamLines],J=z.length,X=Math.max(0,J-Q-this.scrollOffset),K=Math.min(J,X+Q),G=z.slice(X,K);E(W.hide);for(let V=0;V<Q;V++)if(E(W.to(2+V+1,1)),E(W.clearLine),V<G.length)E(G[V].text)}completeInput($){let Z=$.split(" "),Y=Z[0];if(Z.length===1){let X=this.commands.filter((K)=>K.startsWith(Y));if(X.length===1){let K=this.subcommands[X[0]];if(K&&K.length>0)return{value:X[0]+" ",options:`Opcoes: ${K.join(" ")}`};return{value:X[0]+" "}}if(X.length>1){let K=X[0];for(let G of X)while(!G.startsWith(K))K=K.slice(0,-1);return{value:K.length>$.length?K:$,options:X.join(" ")}}return null}let Q=this.subcommands[Y];if(!Q||Q.length===0)return null;let z=Z[Z.length-1].toLowerCase(),J=Q.filter((X)=>X.toLowerCase().startsWith(z));if(J.length===1)return Z[Z.length-1]=J[0],{value:Z.join(" ")+" "};if(J.length>1){let X=J[0];for(let K of J)while(!K.toLowerCase().startsWith(X.toLowerCase()))X=X.slice(0,-1);if(X.length>z.length)return Z[Z.length-1]=X,{value:Z.join(" "),options:J.join(" ")};return{value:$,options:J.join(" ")}}if(!z&&Q.length>0)return{value:$,options:Q.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(E(W.to($,1)),E(W.clearLine),E(`${W.dim}${"\u2500".repeat(this.width)}${W.reset}`),E(W.to(Z,1)),E(W.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);E(` ${I.ai}${this.getSpinnerChar()}${W.reset} ${W.dim}streaming... ${Y}s${W.reset}`),E(W.hide)}else{let Y=W0(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;E(`${I.prompt}\u276F${W.reset} ${Y}`);let Q=this.inputBuf.slice(0,this.inputPos),z=W0(Q)+3;E(W.to(Z,Math.min(z,this.width))),E(W.show)}}onKey($){if(this.pickerActive)return;let Z=$.toString("utf-8");if(this.hasActiveInsight()){let Y=Z.toLowerCase();if(Y==="y"){this.acceptInsight();return}if(Y==="n"||Z==="\x1B"){this.dismissInsight();return}this.dismissInsight()}if(Z==="\x03"){if(this.isStreaming){this.onCancel?.();return}let Y=Date.now(),Q=1500;if(this.inputBuf.length>0){this.inputBuf="",this.inputPos=0,this.lastCtrlCTime=Y,this.renderInput();return}if(Y-this.lastCtrlCTime<Q){this.onExit?.();return}this.lastCtrlCTime=Y,this.showSystem("Pressione Ctrl+C novamente para sair.");return}if(Z==="\x04"){this.onExit?.();return}if(Z==="\f"){this.render();return}if(this.isStreaming)return;if(Z==="\t"){if(this.inputBuf.startsWith("/")){let Y=this.completeInput(this.inputBuf);if(Y){if(this.inputBuf=Y.value,this.inputPos=this.inputBuf.length,this.renderInput(),Y.options)this.showSystem(Y.options)}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!OX(Z)){let Y=Z.replace(/\r?\n/g," ").trim();if(Y.length>0)this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Y+this.inputBuf.slice(this.inputPos),this.inputPos+=Y.length,this.renderInput();return}if(Z==="\r"||Z===`
595
604
  `){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
596
- `,this.inputPos=this.inputBuf.length,this.renderInput();return}let Y=this.inputBuf.trim();if(Y)this.history?.add(Y),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(Y);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let Y=Bz(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-Y)+this.inputBuf.slice(this.inputPos),this.inputPos-=Y,this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=Bz(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=Mz(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let Q=this.history?.prev(this.inputBuf);if(Q!==null&&Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let Q=this.history?.next();if(Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.renderInput();break}case"5~":if(this.scrollOffset<this.lines.length)this.scrollOffset=Math.min(this.scrollOffset+5,this.lines.length),this.renderMessages();break;case"6~":if(this.scrollOffset>0)this.scrollOffset=Math.max(0,this.scrollOffset-5),this.renderMessages();break;case"H":this.inputPos=0,this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Q=Mz(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.renderInput()}break}}return}if(lH(Z))this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.renderInput()}onResize(){if(this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.viewManager.updateDimensions(this.width,this.height),this.viewMode==="dashboard")Y2(3,this.height-2);else Q2();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${I.user}${H.bold} You${H.reset} ${H.dim}${Z}${H.reset}`});else this.lines.push({text:`${I.ai}${H.bold} Claude${H.reset} ${H.dim}${Z}${H.reset}`})}startSpinner(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.spinnerFrame=0,this.spinnerTimer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%$.length,this.renderInput()},80)}stopSpinner(){if(this.spinnerTimer)clearInterval(this.spinnerTimer),this.spinnerTimer=null}getSpinnerChar(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];return $[this.spinnerFrame%$.length]}addWrapped($){let Z=_0(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=e5($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function Cz($){return[...$].length===1}function lH($){if(!Cz($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function Bz($,Z){if(Z<=0)return 0;if(Z>=2){let Y=$.charCodeAt(Z-1),Q=$.charCodeAt(Z-2);if(Y>=56320&&Y<=57343&&Q>=55296&&Q<=56319)return 2}return 1}function Mz($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function oH($){let Z=Date.now()-$,Y=Math.floor(Z/1000);if(Y<60)return"just now";let Q=Math.floor(Y/60);if(Q<60)return`${Q}m ago`;let J=Math.floor(Q/60);if(J<24)return`${J}h ago`;let z=Math.floor(J/24);if(z<30)return`${z}d ago`;return`${Math.floor(z/30)}mo ago`}var U4={"claude-haiku-4-5-20251001":{input:1,output:5},"claude-sonnet-4-20250514":{input:3,output:15},"claude-sonnet-4-6-20250627":{input:3,output:15},"claude-opus-4-20250514":{input:15,output:75},"claude-opus-4-6-20250318":{input:15,output:75}},iH={input:3,output:15};function Nz($,Z){let Y=aH(Z),Q=$.inputTokens/1e6*Y.input*100,J=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:J,totalCostCents:Q+J}}function aH($){if(U4[$])return U4[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return U4["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return U4["claude-opus-4-20250514"];if(Z.includes("sonnet"))return U4["claude-sonnet-4-20250514"];return iH}class _Z{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=Nz($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=Nz($,this.model);return`${J2($.inputTokens)} in / ${J2($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${J2(this.totalInput)} in / ${J2(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function J2($){return $.toLocaleString("en-US")}import{existsSync as Oz,readFileSync as Fz,statSync as Rz}from"fs";import{basename as nH,extname as Ez,resolve as Lz}from"path";var jz=new Set([".png",".jpg",".jpeg",".gif",".webp"]),rH=20971520,sH=new Set([".txt",".md",".markdown",".json",".jsonl",".csv",".tsv",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".c",".cpp",".h",".hpp",".cs",".html",".htm",".css",".scss",".sass",".less",".sql",".sh",".bash",".zsh",".ps1",".bat",".cmd",".env",".gitignore",".dockerignore",".editorconfig",".log",".diff",".patch",".vue",".svelte",".astro"]),tH=1048576;function Dz($){let Z=[],Y=$.split(/\s+/),Q=[];for(let J of Y){let z=J.replace(/^["']|["']$/g,""),X=Ez(z).toLowerCase();if(jz.has(X)){let K=Lz(z);if(Oz(K))try{if(Rz(K).size>rH){Q.push(`[image too large: ${z}]`);continue}let q=Fz(K).toString("base64"),U=eH(X);Z.push({path:K,mediaType:U,base64:q}),Q.push(`[image: ${z}]`)}catch{Q.push(J)}else Q.push(J)}else Q.push(J)}return{text:Q.join(" "),images:Z}}function eH($){switch($){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return"image/png"}}function Pz($){let Z=[],Y=$.split(/\s+/),Q=[];for(let J of Y){let z=J.replace(/^["']|["']$/g,""),X=Ez(z).toLowerCase();if(jz.has(X)){Q.push(J);continue}if(!(sH.has(X)||(z.includes("/")||z.includes("\\"))&&X.length>0)){Q.push(J);continue}let V=Lz(z);if(!Oz(V)){Q.push(J);continue}try{let G=Rz(V);if(!G.isFile()){Q.push(J);continue}if(G.size>tH){Q.push(`[file too large: ${z} (${(G.size/1024).toFixed(0)}KB)]`);continue}if(G.size===0){Q.push(`[empty file: ${z}]`);continue}let q=Fz(V,"utf-8"),U=nH(V);Z.push({path:V,name:U,content:q,size:G.size}),Q.push(`[file: ${U}]`)}catch{Q.push(J)}}return{text:Q.join(" "),files:Z}}J1();import{existsSync as Az,readFileSync as $W}from"fs";import{join as Tz}from"path";o();function ZW(){let $=new Date().getDay();return $===0||$===6}function YW(){return ZW()?"weekend":"weekday"}async function QW($){let Z=[],Y=[],Q=[],J=new Date,z=new Date(J);z.setHours(23,59,59,999);let X=Tz($,"tasks.json");if(Az(X))try{let G=JSON.parse($W(X,"utf-8"));for(let q of G){if(q.done)continue;if(q.dueAt){let U=new Date(q.dueAt),W=U<J,B=!W&&U<=z;if(W)Y.push({id:q.id,title:q.title,dueAt:q.dueAt,isOverdue:!0});else if(B)Z.push({id:q.id,title:q.title,dueAt:q.dueAt,isOverdue:!1})}}}catch(G){x.debug("Failed to parse task for spillover check",{error:G})}let K=b1(!0);for(let G of K.slice(0,5)){let q=await JW(G);if(q)Q.push(q)}return{hasSpillover:Z.length>0||Y.length>0||Q.length>0,urgentTasks:Z,overdueTasks:Y,pendingCommits:Q}}async function JW($){if(!Az(Tz($.path,".git")))return null;try{let Z=Bun.spawn(["git","status","--porcelain"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),Y=await new Response(Z.stdout).text();await Z.exited;let Q=Y.trim().length>0,J=Bun.spawn(["git","rev-list","--count","@{u}..HEAD"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),z=await new Response(J.stdout).text(),K=await J.exited===0?parseInt(z.trim())||0:0;if(Q||K>0)return{projectName:$.name,projectPath:$.path,uncommittedChanges:Q,unpushedCommits:K}}catch(Z){x.debug("Git status check failed for project",{error:Z})}return null}function zW($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function H4($){let Z=YW(),Y=await QW($),Q=zW(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function XW($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
605
+ `,this.inputPos=this.inputBuf.length,this.renderInput();return}let Y=this.inputBuf.trim();if(Y)this.history?.add(Y),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(Y);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let Y=WX(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-Y)+this.inputBuf.slice(this.inputPos),this.inputPos-=Y,this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=WX(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=BX(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let Q=this.history?.prev(this.inputBuf);if(Q!==null&&Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let Q=this.history?.next();if(Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.renderInput();break}case"5~":if(this.scrollOffset<this.lines.length)this.scrollOffset=Math.min(this.scrollOffset+5,this.lines.length),this.renderMessages();break;case"6~":if(this.scrollOffset>0)this.scrollOffset=Math.max(0,this.scrollOffset-5),this.renderMessages();break;case"H":this.inputPos=0,this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Q=BX(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.renderInput()}break}}return}if(DB(Z))this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.renderInput()}onResize(){if(this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.viewManager.updateDimensions(this.width,this.height),this.viewMode==="dashboard")N7(3,this.height-2);else M7();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${I.user}${W.bold} You${W.reset} ${W.dim}${Z}${W.reset}`});else this.lines.push({text:`${I.ai}${W.bold} Claude${W.reset} ${W.dim}${Z}${W.reset}`})}startSpinner(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.spinnerFrame=0,this.spinnerTimer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%$.length,this.renderInput()},80)}stopSpinner(){if(this.spinnerTimer)clearInterval(this.spinnerTimer),this.spinnerTimer=null}getSpinnerChar(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];return $[this.spinnerFrame%$.length]}addWrapped($){let Z=v1(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=W7($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function OX($){return[...$].length===1}function DB($){if(!OX($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function WX($,Z){if(Z<=0)return 0;if(Z>=2){let Y=$.charCodeAt(Z-1),Q=$.charCodeAt(Z-2);if(Y>=56320&&Y<=57343&&Q>=55296&&Q<=56319)return 2}return 1}function BX($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function TB($){let Z=Date.now()-$,Y=Math.floor(Z/1000);if(Y<60)return"just now";let Q=Math.floor(Y/60);if(Q<60)return`${Q}m ago`;let z=Math.floor(Q/60);if(z<24)return`${z}h ago`;let J=Math.floor(z/24);if(J<30)return`${J}d ago`;return`${Math.floor(J/30)}mo ago`}var F8={"claude-haiku-4-5-20251001":{input:1,output:5},"claude-sonnet-4-20250514":{input:3,output:15},"claude-sonnet-4-6-20250627":{input:3,output:15},"claude-opus-4-20250514":{input:15,output:75},"claude-opus-4-6-20250318":{input:15,output:75}},IB={input:3,output:15};function NX($,Z){let Y=SB(Z),Q=$.inputTokens/1e6*Y.input*100,z=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:z,totalCostCents:Q+z}}function SB($){if(F8[$])return F8[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return F8["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return F8["claude-opus-4-20250514"];if(Z.includes("sonnet"))return F8["claude-sonnet-4-20250514"];return IB}class K9{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=NX($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=NX($,this.model);return`${C7($.inputTokens)} in / ${C7($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${C7(this.totalInput)} in / ${C7(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function C7($){return $.toLocaleString("en-US")}import{existsSync as MX,readFileSync as CX,statSync as EX}from"fs";import{basename as wB,extname as RX,resolve as FX}from"path";var LX=new Set([".png",".jpg",".jpeg",".gif",".webp"]),kB=20971520,fB=new Set([".txt",".md",".markdown",".json",".jsonl",".csv",".tsv",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".c",".cpp",".h",".hpp",".cs",".html",".htm",".css",".scss",".sass",".less",".sql",".sh",".bash",".zsh",".ps1",".bat",".cmd",".env",".gitignore",".dockerignore",".editorconfig",".log",".diff",".patch",".vue",".svelte",".astro"]),bB=1048576;function jX($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=RX(J).toLowerCase();if(LX.has(X)){let K=FX(J);if(MX(K))try{if(EX(K).size>kB){Q.push(`[image too large: ${J}]`);continue}let U=CX(K).toString("base64"),q=yB(X);Z.push({path:K,mediaType:q,base64:U}),Q.push(`[image: ${J}]`)}catch{Q.push(z)}else Q.push(z)}else Q.push(z)}return{text:Q.join(" "),images:Z}}function yB($){switch($){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return"image/png"}}function AX($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=RX(J).toLowerCase();if(LX.has(X)){Q.push(z);continue}if(!(fB.has(X)||(J.includes("/")||J.includes("\\"))&&X.length>0)){Q.push(z);continue}let G=FX(J);if(!MX(G)){Q.push(z);continue}try{let V=EX(G);if(!V.isFile()){Q.push(z);continue}if(V.size>bB){Q.push(`[file too large: ${J} (${(V.size/1024).toFixed(0)}KB)]`);continue}if(V.size===0){Q.push(`[empty file: ${J}]`);continue}let U=CX(G,"utf-8"),q=wB(G);Z.push({path:G,name:q,content:U,size:V.size}),Q.push(`[file: ${q}]`)}catch{Q.push(z)}}return{text:Q.join(" "),files:Z}}X$();import{existsSync as PX,readFileSync as _B}from"fs";import{join as DX}from"path";s();function xB(){let $=new Date().getDay();return $===0||$===6}function vB(){return xB()?"weekend":"weekday"}async function hB($){let Z=[],Y=[],Q=[],z=new Date,J=new Date(z);J.setHours(23,59,59,999);let X=DX($,"tasks.json");if(PX(X))try{let V=JSON.parse(_B(X,"utf-8"));for(let U of V){if(U.done)continue;if(U.dueAt){let q=new Date(U.dueAt),H=q<z,B=!H&&q<=J;if(H)Y.push({id:U.id,title:U.title,dueAt:U.dueAt,isOverdue:!0});else if(B)Z.push({id:U.id,title:U.title,dueAt:U.dueAt,isOverdue:!1})}}}catch(V){m.debug("Failed to parse task for spillover check",{error:V})}let K=g$(!0);for(let V of K.slice(0,5)){let U=await gB(V);if(U)Q.push(U)}return{hasSpillover:Z.length>0||Y.length>0||Q.length>0,urgentTasks:Z,overdueTasks:Y,pendingCommits:Q}}async function gB($){if(!PX(DX($.path,".git")))return null;try{let Z=Bun.spawn(["git","status","--porcelain"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),Y=await new Response(Z.stdout).text();await Z.exited;let Q=Y.trim().length>0,z=Bun.spawn(["git","rev-list","--count","@{u}..HEAD"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),J=await new Response(z.stdout).text(),K=await z.exited===0?parseInt(J.trim())||0:0;if(Q||K>0)return{projectName:$.name,projectPath:$.path,uncommittedChanges:Q,unpushedCommits:K}}catch(Z){m.debug("Git status check failed for project",{error:Z})}return null}function mB($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function L8($){let Z=vB(),Y=await hB($),Q=mB(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function uB($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
597
606
  Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${Y}
598
607
  \u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${Y}
599
- Modo: Sharpen or Relax`}}function KW($){let Z=[];if($.overdueTasks.length>0){Z.push(`
608
+ Modo: Sharpen or Relax`}}function pB($){let Z=[];if($.overdueTasks.length>0){Z.push(`
600
609
  --- Tarefas Atrasadas ---`);for(let Y of $.overdueTasks.slice(0,5)){let Q=Y.dueAt?new Date(Y.dueAt).toLocaleDateString("pt-BR"):"";Z.push(` \u26A0 ${Y.title} (venceu ${Q})`)}}if($.urgentTasks.length>0){Z.push(`
601
610
  --- Tarefas Urgentes (Hoje) ---`);for(let Y of $.urgentTasks.slice(0,5)){let Q=Y.dueAt?new Date(Y.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";Z.push(` ! ${Y.title} (${Q})`)}}if($.pendingCommits.length>0){Z.push(`
602
611
  --- Git Pendente ---`);for(let Y of $.pendingCommits){let Q=[];if(Y.uncommittedChanges)Q.push("uncommitted");if(Y.unpushedCommits>0)Q.push(`${Y.unpushedCommits} unpushed`);Z.push(` ${Y.projectName}: ${Q.join(", ")}`)}}return Z.join(`
603
- `)}function VW($){if($.persona!=="sharpen_or_relax")return"";return`
612
+ `)}function dB($){if($.persona!=="sharpen_or_relax")return"";return`
604
613
  --- Fim de Semana Livre ---
605
614
 
606
615
  [A] Amolar o Machado
607
616
  Estudo de arquitetura, refatoracao, melhoria do CLI
608
617
 
609
618
  [B] Descompressao Criativa
610
- Projetos paralelos sem prazo, foco pessoal/familia`}function GW($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
619
+ Projetos paralelos sem prazo, foco pessoal/familia`}function cB($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
611
620
  --- Sugestao: Timebox ---
612
621
  Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
613
- Depois: descanso merecido.`}async function Iz($){let Z=[],Y=null;if($)Y=await H4($),Z.push(XW(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await Q1();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let z=KW(Y);if(z)Z.push(z);let X=GW(Y);if(X)Z.push(X)}if(Y){let z=VW(Y);if(z)Z.push(z)}if(L)try{let z=await f$();Z.push(`
622
+ Depois: descanso merecido.`}async function TX($){let Z=[],Y=null;if($)Y=await L8($),Z.push(uB(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await J$();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let J=pB(Y);if(J)Z.push(J);let X=cB(Y);if(X)Z.push(X)}if(Y){let J=dB(Y);if(J)Z.push(J)}if(j)try{let J=await l0();Z.push(`
614
623
  --- Agenda ---
615
- ${z}`)}catch{Z.push(`
624
+ ${J}`)}catch{Z.push(`
616
625
  --- Agenda ---
617
- Outlook nao disponivel.`)}if(L)try{let z=await Y1();Z.push(`
626
+ Outlook nao disponivel.`)}if(j)try{let J=await z$();Z.push(`
618
627
  --- Sistema ---
619
- ${z}`)}catch(z){x.debug("System info unavailable for briefing",{error:z})}let J=Y?.persona==="sharpen_or_relax"?2:3;try{let z=await L0(["finance","business","tech"],J);Z.push(`
620
- ${z}`)}catch{Z.push(`
628
+ ${J}`)}catch(J){m.debug("System info unavailable for briefing",{error:J})}let z=Y?.persona==="sharpen_or_relax"?2:3;try{let J=await P1(["finance","business","tech"],z);Z.push(`
629
+ ${J}`)}catch{Z.push(`
621
630
  --- Noticias ---
622
631
  Falha ao carregar noticias.`)}return Z.push(`
623
632
  ======================`),Z.join(`
624
- `)}o();p$();var _=null,z2=null,xZ=null,vZ=0;function kz($){xZ=$}function bz($="foco",Z=25,Y=5){if(_)return`Pomodoro ja ativo: "${_.label}" (${xz()}). Use /pomodoro stop para parar.`;return _={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},vZ++,_z(),`Pomodoro #${vZ} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function yz(){if(!_)return"Nenhum pomodoro ativo.";let $=_.label,Z=Math.floor((Date.now()-_.startedAt)/60000);return X2(),_=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function fZ(){if(!_)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=xz();return`${_.type==="work"?"Trabalhando":"Pausa"}: "${_.label}" \u2014 ${$} restante(s) (ciclo #${vZ})`}function _z(){if(!_)return;X2();let $=_.startedAt+_.durationMs-Date.now();if($<=0){Sz();return}z2=setTimeout(Sz,$)}function Sz(){if(!_)return;if(_.type==="work"){let $=`Pomodoro: "${_.label}" concluido! Hora da pausa (${_.breakMs/60000}min).`;wz("Pausa!",`"${_.label}" concluido. Descanse ${_.breakMs/60000} minutos.`),xZ?.($),_={..._,type:"break",startedAt:Date.now(),durationMs:_.breakMs},_z()}else wz("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),xZ?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),X2(),_=null}function X2(){if(z2)clearTimeout(z2),z2=null}function xz(){if(!_)return"0min";let $=Math.max(0,_.startedAt+_.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function wz($,Z){if(!L)return;try{await U0($,Z,{timeout:1e4})}catch{}}function vz(){X2(),_=null}o();p$();var b$=new Map,hZ=null;function hz($){hZ=$}function gz($,Z=60){if(!L)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(b$.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>fz(Y),Z*1000);return b$.set(Y,{name:$,interval:Q,lastSeen:!0}),fz(Y),`Monitorando "${$}" a cada ${Z}s.`}function mz($){let Z=$.toLowerCase(),Y=b$.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),b$.delete(Z),`Monitor parado: "${$}"`}function uz(){if(b$.size===0)return"Nenhum processo monitorado.";let $=[...b$.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${b$.size}):
633
+ `)}s();n0();var h=null,E7=null,G9=null,V9=0;function wX($){G9=$}function kX($="foco",Z=25,Y=5){if(h)return`Pomodoro ja ativo: "${h.label}" (${yX()}). Use /pomodoro stop para parar.`;return h={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},V9++,bX(),`Pomodoro #${V9} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function fX(){if(!h)return"Nenhum pomodoro ativo.";let $=h.label,Z=Math.floor((Date.now()-h.startedAt)/60000);return R7(),h=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function U9(){if(!h)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=yX();return`${h.type==="work"?"Trabalhando":"Pausa"}: "${h.label}" \u2014 ${$} restante(s) (ciclo #${V9})`}function bX(){if(!h)return;R7();let $=h.startedAt+h.durationMs-Date.now();if($<=0){IX();return}E7=setTimeout(IX,$)}function IX(){if(!h)return;if(h.type==="work"){let $=`Pomodoro: "${h.label}" concluido! Hora da pausa (${h.breakMs/60000}min).`;SX("Pausa!",`"${h.label}" concluido. Descanse ${h.breakMs/60000} minutos.`),G9?.($),h={...h,type:"break",startedAt:Date.now(),durationMs:h.breakMs},bX()}else SX("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),G9?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),R7(),h=null}function R7(){if(E7)clearTimeout(E7),E7=null}function yX(){if(!h)return"0min";let $=Math.max(0,h.startedAt+h.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function SX($,Z){if(!j)return;try{await B1($,Z,{timeout:1e4})}catch{}}function _X(){R7(),h=null}s();n0();var m0=new Map,q9=null;function vX($){q9=$}function hX($,Z=60){if(!j)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(m0.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>xX(Y),Z*1000);return m0.set(Y,{name:$,interval:Q,lastSeen:!0}),xX(Y),`Monitorando "${$}" a cada ${Z}s.`}function gX($){let Z=$.toLowerCase(),Y=m0.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),m0.delete(Z),`Monitor parado: "${$}"`}function mX(){if(m0.size===0)return"Nenhum processo monitorado.";let $=[...m0.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${m0.size}):
625
634
  ${$.join(`
626
- `)}`}function pz(){for(let $ of b$.values())clearInterval($.interval);b$.clear()}async function fz($){let Z=b$.get($);if(!Z)return;let Y=await E4(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;U0("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),hZ?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;hZ?.(Q)}b$.set($,{...Z,lastSeen:Y})}g();d$();var qW=60000,UW=300000,w$={timer:null,lastRefresh:0,refreshCount:0,running:!1},x0=null;function dz($,Z={}){gZ(),x0=$;let Y=Z.checkIntervalMs??qW,Q=Z.refreshBufferMs??UW,J=setInterval(()=>{WW(Q,Z)},Y);if(J.unref)J.unref();w$={timer:J,lastRefresh:Date.now(),refreshCount:0,running:!0},x.debug("Auto-refresh started",{checkInterval:Y,refreshBuffer:Q}),s("status:update",{source:"auto-refresh",message:"Auto-refresh ativo",level:"info",timestamp:Date.now()})}function gZ(){if(w$.timer)clearInterval(w$.timer);w$={...w$,timer:null,running:!1},x0=null}function cz($){x0=$}function HW(){let $=x0?.expiresAt??null,Z=null;if($){let Y=$-Date.now();if(Y<=0)Z="expirado";else{let Q=Math.floor(Y/60000),J=Math.floor(Q/60);Z=J>0?`${J}h ${Q%60}m`:`${Q}m`}}return{running:w$.running,lastRefresh:w$.lastRefresh,refreshCount:w$.refreshCount,tokenExpiresAt:$,tokenExpiresIn:Z}}function lz(){let $=HW(),Z=[`Auto-refresh: ${$.running?"ativo":"inativo"}`,`Renovacoes: ${$.refreshCount}`];if($.tokenExpiresIn)Z.push(`Token expira em: ${$.tokenExpiresIn}`);if($.lastRefresh>0){let Y=Math.round((Date.now()-$.lastRefresh)/60000);Z.push(`Ultima renovacao: ${Y===0?"agora":`${Y}m atras`}`)}return Z.join(`
627
- `)}function WW($,Z){if(!x0)return;let Y=Date.now(),Q=x0.expiresAt-Y;if(Q>$)return;x.debug("Token near expiration, attempting refresh",{expiresIn:Math.round(Q/1000)}),s("status:update",{source:"auto-refresh",message:"Renovando token automaticamente...",level:"warning",timestamp:Y});try{let J=g0();if(J&&J.expiresAt>x0.expiresAt){oz(J,Y,Z);return}BW(Y,Z)}catch(J){let z=`Erro ao renovar: ${J instanceof Error?J.message:String(J)}`;Z.onRefreshFailed?.(z),s("status:update",{source:"auto-refresh",message:z,level:"error",timestamp:Y})}}function oz($,Z,Y){x0=$,w$={...w$,lastRefresh:Z,refreshCount:w$.refreshCount+1},Y.onRefreshed?.($),s("status:update",{source:"auto-refresh",message:`Token renovado (expira ${MW($.expiresAt)})`,level:"success",timestamp:Z}),x.debug("Auto-refresh successful",{expiresAt:new Date($.expiresAt).toISOString(),refreshCount:w$.refreshCount})}function BW($,Z){try{let Y=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>Y.kill(),15000);Y.exited.then(()=>{clearTimeout(Q);let J=g0();if(J&&J.expiresAt>$)oz(J,Date.now(),Z);else Z.onRefreshFailed?.("Falha ao renovar token \u2014 claude nao rotacionou credenciais"),s("status:update",{source:"auto-refresh",message:"Falha ao renovar token \u2014 claude nao rotacionou credenciais",level:"error",timestamp:Date.now()})}).catch(()=>{clearTimeout(Q);let J="Falha ao executar claude para renovar token";Z.onRefreshFailed?.(J),s("status:update",{source:"auto-refresh",message:J,level:"error",timestamp:Date.now()})})}catch{Z.onRefreshFailed?.("claude CLI nao encontrado \u2014 renovacao automatica indisponivel"),s("status:update",{source:"auto-refresh",message:"claude CLI nao encontrado \u2014 renovacao automatica indisponivel",level:"error",timestamp:Date.now()})}}function MW($){return new Date($).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}J1();import{existsSync as CW,readFileSync as NW,writeFileSync as OW}from"fs";import{join as FW}from"path";o();var iz="",az=()=>FW(iz,"last-morning.txt");function nz($){iz=$;let Z=az(),Y=new Date().toISOString().split("T")[0];if(!CW(Z))return!0;try{return NW(Z,"utf-8").trim()!==Y}catch{return!0}}function rz(){let $=new Date().toISOString().split("T")[0];OW(az(),$)}async function sz(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
628
- `);let Q=await Q1();$.push(Q);let z=t$().filter((U)=>{if(!U.dueAt)return!1;let W=new Date(U.dueAt),B=new Date;return W.toDateString()===B.toDateString()});if(z.length>0)$.push(`
629
- --- Tarefas do dia ---`),$.push(i0(z));let X=I1();if(X.length>0)$.push(`
630
- --- Follow-ups pendentes ---`),$.push(t7(X));let V=r0().filter((U)=>U.status==="atrasado");if(V.length>0)$.push(`
631
- --- Delegacoes atrasadas ---`),$.push(s7(V));let G=U5();if(G)$.push(`
632
- ${G}`);if(L)try{let U=await f$();$.push(`
633
- --- Agenda ---`),$.push(U)}catch{}try{let U=await L0(["finance","business","tech"],2);$.push(`
634
- `+U)}catch{}let q=t$();if(q.length>0&&z.length!==q.length)$.push(`
635
- ${q.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
635
+ `)}`}function uX(){for(let $ of m0.values())clearInterval($.interval);m0.clear()}async function xX($){let Z=m0.get($);if(!Z)return;let Y=await v8(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;B1("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),q9?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;q9?.(Q)}m0.set($,{...Z,lastSeen:Y})}l();u0();var lB=60000,oB=300000,v0={timer:null,lastRefresh:0,refreshCount:0,running:!1},h1=null;function pX($,Z={}){H9(),h1=$;let Y=Z.checkIntervalMs??lB,Q=Z.refreshBufferMs??oB,z=setInterval(()=>{rB(Q,Z)},Y);if(z.unref)z.unref();v0={timer:z,lastRefresh:Date.now(),refreshCount:0,running:!0},m.debug("Auto-refresh started",{checkInterval:Y,refreshBuffer:Q}),Q0("status:update",{source:"auto-refresh",message:"Auto-refresh ativo",level:"info",timestamp:Date.now()})}function H9(){if(v0.timer)clearInterval(v0.timer);v0={...v0,timer:null,running:!1},h1=null}function dX($){h1=$}function iB(){let $=h1?.expiresAt??null,Z=null;if($){let Y=$-Date.now();if(Y<=0)Z="expirado";else{let Q=Math.floor(Y/60000),z=Math.floor(Q/60);Z=z>0?`${z}h ${Q%60}m`:`${Q}m`}}return{running:v0.running,lastRefresh:v0.lastRefresh,refreshCount:v0.refreshCount,tokenExpiresAt:$,tokenExpiresIn:Z}}function cX(){let $=iB(),Z=[`Auto-refresh: ${$.running?"ativo":"inativo"}`,`Renovacoes: ${$.refreshCount}`];if($.tokenExpiresIn)Z.push(`Token expira em: ${$.tokenExpiresIn}`);if($.lastRefresh>0){let Y=Math.round((Date.now()-$.lastRefresh)/60000);Z.push(`Ultima renovacao: ${Y===0?"agora":`${Y}m atras`}`)}return Z.join(`
636
+ `)}function rB($,Z){if(!h1)return;let Y=Date.now(),Q=h1.expiresAt-Y;if(Q>$)return;m.debug("Token near expiration, attempting refresh",{expiresIn:Math.round(Q/1000)}),Q0("status:update",{source:"auto-refresh",message:"Renovando token automaticamente...",level:"warning",timestamp:Y});try{let z=u1();if(z&&z.expiresAt>h1.expiresAt){lX(z,Y,Z);return}nB(Y,Z)}catch(z){let J=`Erro ao renovar: ${z instanceof Error?z.message:String(z)}`;Z.onRefreshFailed?.(J),Q0("status:update",{source:"auto-refresh",message:J,level:"error",timestamp:Y})}}function lX($,Z,Y){h1=$,v0={...v0,lastRefresh:Z,refreshCount:v0.refreshCount+1},Y.onRefreshed?.($),Q0("status:update",{source:"auto-refresh",message:`Token renovado (expira ${aB($.expiresAt)})`,level:"success",timestamp:Z}),m.debug("Auto-refresh successful",{expiresAt:new Date($.expiresAt).toISOString(),refreshCount:v0.refreshCount})}function nB($,Z){try{let Y=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>Y.kill(),15000);Y.exited.then(()=>{clearTimeout(Q);let z=u1();if(z&&z.expiresAt>$)lX(z,Date.now(),Z);else Z.onRefreshFailed?.("Falha ao renovar token \u2014 claude nao rotacionou credenciais"),Q0("status:update",{source:"auto-refresh",message:"Falha ao renovar token \u2014 claude nao rotacionou credenciais",level:"error",timestamp:Date.now()})}).catch(()=>{clearTimeout(Q);let z="Falha ao executar claude para renovar token";Z.onRefreshFailed?.(z),Q0("status:update",{source:"auto-refresh",message:z,level:"error",timestamp:Date.now()})})}catch{Z.onRefreshFailed?.("claude CLI nao encontrado \u2014 renovacao automatica indisponivel"),Q0("status:update",{source:"auto-refresh",message:"claude CLI nao encontrado \u2014 renovacao automatica indisponivel",level:"error",timestamp:Date.now()})}}function aB($){return new Date($).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}X$();import{existsSync as sB,readFileSync as tB,writeFileSync as eB}from"fs";import{join as $O}from"path";s();var oX="",iX=()=>$O(oX,"last-morning.txt");function rX($){oX=$;let Z=iX(),Y=new Date().toISOString().split("T")[0];if(!sB(Z))return!0;try{return tB(Z,"utf-8").trim()!==Y}catch{return!0}}function nX(){let $=new Date().toISOString().split("T")[0];eB(iX(),$)}async function aX(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
637
+ `);let Q=await J$();$.push(Q);let J=Q1().filter((q)=>{if(!q.dueAt)return!1;let H=new Date(q.dueAt),B=new Date;return H.toDateString()===B.toDateString()});if(J.length>0)$.push(`
638
+ --- Tarefas do dia ---`),$.push(n1(J));let X=_$();if(X.length>0)$.push(`
639
+ --- Follow-ups pendentes ---`),$.push(H5(X));let G=t1().filter((q)=>q.status==="atrasado");if(G.length>0)$.push(`
640
+ --- Delegacoes atrasadas ---`),$.push(q5(G));let V=P5();if(V)$.push(`
641
+ ${V}`);if(j)try{let q=await l0();$.push(`
642
+ --- Agenda ---`),$.push(q)}catch{}try{let q=await P1(["finance","business","tech"],2);$.push(`
643
+ `+q)}catch{}let U=Q1();if(U.length>0&&J.length!==U.length)$.push(`
644
+ ${U.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
636
645
  ==============================`),$.join(`
637
- `)}g();g();J1();o();p$();import{existsSync as tz,mkdirSync as RW,readFileSync as EW}from"fs";import{join as LW}from"path";import{randomUUID as jW}from"crypto";var ez="",G$=[],$X=()=>LW(ez,"workflows.json");function W4(){P($X(),JSON.stringify(G$,null,2))}function DW(){let $=$X();if(!tz($)){G$=mZ(),W4();return}try{let Z=JSON.parse(EW($,"utf-8"));if(!Array.isArray(Z)){G$=mZ(),W4();return}G$=Z.map((Y)=>({id:Y.id||uZ(),name:Y.name||"unnamed",description:Y.description||"",steps:Array.isArray(Y.steps)?Y.steps:[],tags:Array.isArray(Y.tags)?Y.tags:[],enabled:Y.enabled!==!1,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString()}))}catch{G$=mZ(),W4()}}function mZ(){let $=new Date().toISOString();return[{id:uZ(),name:"iniciar-dia",description:"Abrir apps de trabalho: terminal e ferramentas",steps:[{action:"notify",target:"Iniciando ambiente de trabalho..."},{action:"open_app",target:"terminal",label:"Terminal"},{action:"wait",target:"2"},{action:"open_app",target:"vscode",label:"VS Code",on_error:"skip"},{action:"notify",target:"Ambiente pronto!"}],tags:["trabalho","diario"],enabled:!0,createdAt:$,updatedAt:$},{id:uZ(),name:"dev",description:"Ambiente de desenvolvimento: VSCode + Terminal",steps:[{action:"open_app",target:"vscode",label:"VS Code"},{action:"wait",target:"1"},{action:"open_app",target:"terminal",label:"Terminal"}],tags:["dev"],enabled:!0,createdAt:$,updatedAt:$}]}function ZX($){if(ez=$,!tz($))RW($,{recursive:!0});DW()}function B4($){let Z=$.toLowerCase().trim();return G$.find((Y)=>Y.id===$)||G$.find((Y)=>Y.name.toLowerCase()===Z)||G$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function YX($){let Z=[...G$];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((J)=>J.toLowerCase()===Y))}return Z}function pZ($,Z){let Y=B4($);if(!Y)return null;return G$=G$.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),W4(),G$.find((Q)=>Q.id===Y.id)||null}function QX($){let Z=B4($);if(!Z)return!1;return G$=G$.filter((Y)=>Y.id!==Z.id),W4(),!0}async function dZ($,Z){let Y=B4($);if(!Y){let J=G$.map((z)=>z.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${J}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await JX(Y.name,Y.steps,Z);return AW(Q)}async function JX($,Z,Y){let Q=performance.now(),J=[`Executando workflow: "${$}"`],z=0,X=0,K=0,V=!0;for(let G=0;G<Z.length;G++){let q=Z[G],U=q.label||`${q.action}:${q.target}`,W=`[${G+1}/${Z.length}]`,B=q.on_error||"continue";Y?.(`${W} ${U}...`);try{let M=await PW(q,Y);J.push(` ${W} ${M}`),z++}catch(M){let N=M instanceof Error?M.message:String(M);switch(K++,B){case"stop":return J.push(` ${W} ERRO (parando): ${N}`),V=!1,{workflow:$,success:V,stepsRun:z,stepsSkipped:X,stepsFailed:K,log:J,duration:Math.round(performance.now()-Q)};case"skip":J.push(` ${W} ERRO (pulado): ${N}`),X++;break;case"continue":default:J.push(` ${W} ERRO (continuando): ${N}`);break}}}return{workflow:$,success:V,stepsRun:z,stepsSkipped:X,stepsFailed:K,log:J,duration:Math.round(performance.now()-Q)}}async function PW($,Z){switch($.action){case"open_app":{if(!L)return`skip: ${$.target} (not Windows)`;return await $1($.target)}case"open_url":{if(!L)return`skip: ${$.target} (not Windows)`;let Y=$.target.trim();if(!Y.startsWith("http://")&&!Y.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Y}`);return await Z1(Y)}case"run_command":{if(!L)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await q$(Y,{timeout:30000});if(Q.timedOut)throw Error("Command timeout (30s)");if(Q.exitCode!==0&&Q.stderr.trim())throw Error(`exit ${Q.exitCode}: ${Q.stderr.trim().slice(0,200)}`);let J=Q.stdout.trim().slice(0,200);return`Command: ${Y.slice(0,60)}${J?" -> "+J:""}`}case"wait":{let Y=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Q)=>setTimeout(Q,Y*1000)),`Wait: ${Y}s`}case"notify":{if(L)try{U0("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!L)return"skip: condition (not Windows)";let Y=$.target.toLowerCase(),Q=await E4(Y,{timeout:5000});if(Q&&$.condition_steps&&$.condition_steps.length>0){let J=await JX(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${Y} running=true, ran ${J.stepsRun} sub-steps`}return`Condition: ${Y} running=${Q}${!Q?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function zX($){let Z=$||G$;if(Z.length===0)return"Nenhum workflow configurado.";let Y=Z.map((Q)=>{let J=Q.enabled?"":" [DESATIVADO]",z=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"",X=Q.steps.map((K)=>{let V=K.label||K.target;return K.action==="wait"?`${K.target}s`:V}).join(" -> ");return` ${Q.name}${J}${z} \u2014 ${Q.description}
646
+ `)}l();l();X$();s();n0();import{existsSync as sX,mkdirSync as ZO,readFileSync as YO}from"fs";import{join as QO}from"path";import{randomUUID as zO}from"crypto";var tX="",B0=[],eX=()=>QO(tX,"workflows.json");function j8(){P(eX(),JSON.stringify(B0,null,2))}function JO(){let $=eX();if(!sX($)){B0=W9(),j8();return}try{let Z=JSON.parse(YO($,"utf-8"));if(!Array.isArray(Z)){B0=W9(),j8();return}B0=Z.map((Y)=>({id:Y.id||B9(),name:Y.name||"unnamed",description:Y.description||"",steps:Array.isArray(Y.steps)?Y.steps:[],tags:Array.isArray(Y.tags)?Y.tags:[],enabled:Y.enabled!==!1,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString()}))}catch{B0=W9(),j8()}}function W9(){let $=new Date().toISOString();return[{id:B9(),name:"iniciar-dia",description:"Abrir apps de trabalho: terminal e ferramentas",steps:[{action:"notify",target:"Iniciando ambiente de trabalho..."},{action:"open_app",target:"terminal",label:"Terminal"},{action:"wait",target:"2"},{action:"open_app",target:"vscode",label:"VS Code",on_error:"skip"},{action:"notify",target:"Ambiente pronto!"}],tags:["trabalho","diario"],enabled:!0,createdAt:$,updatedAt:$},{id:B9(),name:"dev",description:"Ambiente de desenvolvimento: VSCode + Terminal",steps:[{action:"open_app",target:"vscode",label:"VS Code"},{action:"wait",target:"1"},{action:"open_app",target:"terminal",label:"Terminal"}],tags:["dev"],enabled:!0,createdAt:$,updatedAt:$}]}function $K($){if(tX=$,!sX($))ZO($,{recursive:!0});JO()}function A8($){let Z=$.toLowerCase().trim();return B0.find((Y)=>Y.id===$)||B0.find((Y)=>Y.name.toLowerCase()===Z)||B0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function ZK($){let Z=[...B0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z}function O9($,Z){let Y=A8($);if(!Y)return null;return B0=B0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),j8(),B0.find((Q)=>Q.id===Y.id)||null}function YK($){let Z=A8($);if(!Z)return!1;return B0=B0.filter((Y)=>Y.id!==Z.id),j8(),!0}async function N9($,Z){let Y=A8($);if(!Y){let z=B0.map((J)=>J.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${z}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await QK(Y.name,Y.steps,Z);return KO(Q)}async function QK($,Z,Y){let Q=performance.now(),z=[`Executando workflow: "${$}"`],J=0,X=0,K=0,G=!0;for(let V=0;V<Z.length;V++){let U=Z[V],q=U.label||`${U.action}:${U.target}`,H=`[${V+1}/${Z.length}]`,B=U.on_error||"continue";Y?.(`${H} ${q}...`);try{let O=await XO(U,Y);z.push(` ${H} ${O}`),J++}catch(O){let M=O instanceof Error?O.message:String(O);switch(K++,B){case"stop":return z.push(` ${H} ERRO (parando): ${M}`),G=!1,{workflow:$,success:G,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)};case"skip":z.push(` ${H} ERRO (pulado): ${M}`),X++;break;case"continue":default:z.push(` ${H} ERRO (continuando): ${M}`);break}}}return{workflow:$,success:G,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)}}async function XO($,Z){switch($.action){case"open_app":{if(!j)return`skip: ${$.target} (not Windows)`;return await Y$($.target)}case"open_url":{if(!j)return`skip: ${$.target} (not Windows)`;let Y=$.target.trim();if(!Y.startsWith("http://")&&!Y.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Y}`);return await Q$(Y)}case"run_command":{if(!j)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await O0(Y,{timeout:30000});if(Q.timedOut)throw Error("Command timeout (30s)");if(Q.exitCode!==0&&Q.stderr.trim())throw Error(`exit ${Q.exitCode}: ${Q.stderr.trim().slice(0,200)}`);let z=Q.stdout.trim().slice(0,200);return`Command: ${Y.slice(0,60)}${z?" -> "+z:""}`}case"wait":{let Y=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Q)=>setTimeout(Q,Y*1000)),`Wait: ${Y}s`}case"notify":{if(j)try{B1("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!j)return"skip: condition (not Windows)";let Y=$.target.toLowerCase(),Q=await v8(Y,{timeout:5000});if(Q&&$.condition_steps&&$.condition_steps.length>0){let z=await QK(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${Y} running=true, ran ${z.stepsRun} sub-steps`}return`Condition: ${Y} running=${Q}${!Q?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function zK($){let Z=$||B0;if(Z.length===0)return"Nenhum workflow configurado.";let Y=Z.map((Q)=>{let z=Q.enabled?"":" [DESATIVADO]",J=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"",X=Q.steps.map((K)=>{let G=K.label||K.target;return K.action==="wait"?`${K.target}s`:G}).join(" -> ");return` ${Q.name}${z}${J} \u2014 ${Q.description}
638
647
  ${" ".repeat(4)}${X} {${Q.id}}`});return`Workflows (${Z.length}):
639
648
  ${Y.join(`
640
649
 
641
- `)}`}function XX($){let Z=$.enabled?"ativo":"desativado",Y=$.tags.length>0?`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`:"",Q=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(Y)Q.push(Y);return Q.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Q.push(""),Q.push("Steps:"),$.steps.forEach((J,z)=>{let X=J.label?` (${J.label})`:"",K=J.on_error&&J.on_error!=="continue"?` [on_error: ${J.on_error}]`:"";if(Q.push(` ${z+1}. ${J.action}: ${J.target}${X}${K}`),J.action==="if_app_running"&&J.condition_steps)for(let V of J.condition_steps)Q.push(` \u21B3 ${V.action}: ${V.target}`)}),Q.join(`
642
- `)}function AW($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
643
- `)}function uZ(){return jW().slice(0,8)}i8();function KX($,Z,Y){C6($,y4().replace(/[/\\]config\.json$/,"")),OY($),f3($),AY($),j3($),GZ(Y),$Y($),YY(),KY($),kz((Q)=>Z.showSystem(`
650
+ `)}`}function JK($){let Z=$.enabled?"ativo":"desativado",Y=$.tags.length>0?`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`:"",Q=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(Y)Q.push(Y);return Q.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Q.push(""),Q.push("Steps:"),$.steps.forEach((z,J)=>{let X=z.label?` (${z.label})`:"",K=z.on_error&&z.on_error!=="continue"?` [on_error: ${z.on_error}]`:"";if(Q.push(` ${J+1}. ${z.action}: ${z.target}${X}${K}`),z.action==="if_app_running"&&z.condition_steps)for(let G of z.condition_steps)Q.push(` \u21B3 ${G.action}: ${G.target}`)}),Q.join(`
651
+ `)}function KO($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
652
+ `)}function B9(){return zO().slice(0,8)}Z8();var XK=!1;function M9($,Z){if(XK)return;XK=!0,GY($,i8().replace(/[/\\]config\.json$/,"")),qz($),wQ($),Ez($),MQ($),gZ(Z),iQ($),nQ(),$z($),$K($),v6($),uJ($),kz($),mz($),JJ($),S6($,()=>{})}function KK($,Z,Y){M9($,Y),wX((Q)=>Z.showSystem(`
644
653
  *** ${Q} ***
645
- `)),ZX($),U9($),aQ($),hY($),iY($),HQ($),wQ($,(Q)=>{Z.showSystem(`
654
+ `)),jJ($,(Q)=>{Z.showSystem(`
646
655
  *** Meta-Insight: ${Q.title} ***
647
656
  ${Q.recommendation}
648
- `)}),hz((Q)=>Z.showSystem(`
657
+ `)}),vX((Q)=>Z.showSystem(`
649
658
  *** ${Q} ***
650
- `)),l3($,(Q)=>Z.showSystem(`
659
+ `)),hQ($,(Q)=>Z.showSystem(`
651
660
  *** ${Q} ***
652
- `)),S3($,(Q)=>{Z.showSystem(`
661
+ `)),S6($,(Q)=>{Z.showSystem(`
653
662
  *** LEMBRETE: ${Q.title} ***
654
- `)})}function VX($,Z={}){let{includeToolCalls:Y=!0,includeTimestamps:Q=!0}=Z,J=[];J.push(`# smolerclaw session: ${$.name}`),J.push(`Created: ${new Date($.created).toLocaleString()}`),J.push(""),J.push("---"),J.push("");for(let z of $.messages){let X=Q?` (${new Date(z.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(z.role==="user")J.push(`## You${X}`),J.push(""),J.push(z.content),J.push("");else{if(J.push(`## Claude${X}`),J.push(""),J.push(z.content),Y&&z.toolCalls?.length){J.push("");for(let K of z.toolCalls){let V=TW(K.name,K.input);J.push(`> **Tool:** \`${K.name}\`${V}`);let G=K.result.split(`
663
+ `)})}function GK($,Z={}){let{includeToolCalls:Y=!0,includeTimestamps:Q=!0}=Z,z=[];z.push(`# smolerclaw session: ${$.name}`),z.push(`Created: ${new Date($.created).toLocaleString()}`),z.push(""),z.push("---"),z.push("");for(let J of $.messages){let X=Q?` (${new Date(J.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(J.role==="user")z.push(`## You${X}`),z.push(""),z.push(J.content),z.push("");else{if(z.push(`## Claude${X}`),z.push(""),z.push(J.content),Y&&J.toolCalls?.length){z.push("");for(let K of J.toolCalls){let G=GO(K.name,K.input);z.push(`> **Tool:** \`${K.name}\`${G}`);let V=K.result.split(`
655
664
  `).slice(0,5).join(`
656
- `);if(G.trim()){J.push("> ```");for(let q of G.split(`
657
- `))J.push(`> ${q}`);J.push("> ```")}}}if(z.usage)J.push(""),J.push(`*Tokens: ${z.usage.inputTokens} in / ${z.usage.outputTokens} out (~$${(z.usage.costCents/100).toFixed(4)})*`);J.push("")}J.push("---"),J.push("")}return J.join(`
658
- `)}function TW($,Z){switch($){case"read_file":case"write_file":case"edit_file":return Z.path?` \`${Z.path}\``:"";case"search_files":return Z.pattern?` \`/${Z.pattern}/\``:"";case"find_files":return Z.pattern?` \`${Z.pattern}\``:"";case"run_command":return Z.command?` \`${Z.command}\``:"";default:return""}}async function K1(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Y,Q]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),J=await Z.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:J===0}}async function GX(){let $=await K1("git","diff","--cached"),Z=await K1("git","diff"),Y=await K1("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
665
+ `);if(V.trim()){z.push("> ```");for(let U of V.split(`
666
+ `))z.push(`> ${U}`);z.push("> ```")}}}if(J.usage)z.push(""),z.push(`*Tokens: ${J.usage.inputTokens} in / ${J.usage.outputTokens} out (~$${(J.usage.costCents/100).toFixed(4)})*`);z.push("")}z.push("---"),z.push("")}return z.join(`
667
+ `)}function GO($,Z){switch($){case"read_file":case"write_file":case"edit_file":return Z.path?` \`${Z.path}\``:"";case"search_files":return Z.pattern?` \`/${Z.pattern}/\``:"";case"find_files":return Z.pattern?` \`${Z.pattern}\``:"";case"run_command":return Z.command?` \`${Z.command}\``:"";default:return""}}async function V$(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Y,Q]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),z=await Z.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:z===0}}async function VK(){let $=await V$("git","diff","--cached"),Z=await V$("git","diff"),Y=await V$("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
659
668
  `+$.stdout);if(Z.stdout)Q.push(`=== UNSTAGED ===
660
669
  `+Z.stdout);if(Y.stdout)Q.push(`=== UNTRACKED ===
661
670
  `+Y.stdout);return Q.join(`
662
671
 
663
- `)||"(no changes)"}async function qX(){let $=await K1("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function UX(){return(await K1("git","add","-A")).ok}async function HX($){let Z=await K1("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function WX(){let $=await K1("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var BX={default:{name:"default",description:"Versatile assistant (general + coding)",systemPrompt:""},coder:{name:"coder",description:"Focused software engineer",systemPrompt:`You are a senior software engineer. Focus exclusively on code quality, architecture, and implementation.
672
+ `)||"(no changes)"}async function UK(){let $=await V$("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function qK(){return(await V$("git","add","-A")).ok}async function HK($){let Z=await V$("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function WK(){let $=await V$("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var BK={default:{name:"default",description:"Versatile assistant (general + coding)",systemPrompt:""},coder:{name:"coder",description:"Focused software engineer",systemPrompt:`You are a senior software engineer. Focus exclusively on code quality, architecture, and implementation.
664
673
 
665
674
  Behavior:
666
675
  - Write clean, production-grade code. No shortcuts.
@@ -691,63 +700,1183 @@ Behavior:
691
700
  - Be specific. Show the line, explain the problem, suggest the fix.
692
701
  - Check for: error handling, input validation, edge cases, naming, complexity.
693
702
  - Don't nitpick formatting unless it affects readability.
694
- - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function MX($){return BX[$.toLowerCase()]||null}function CX($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(BX)){let J=Y===$?" *":" ";Z.push(`${J} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
695
- `)}o();async function NX($){try{let Z=L?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:z6?["pbcopy"]:["xclip","-selection","clipboard"],Y=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return Y.stdin.write($),Y.stdin.end(),await Y.exited===0}catch{return!1}}g();J1();import{writeFileSync as IW}from"fs";async function OX($,Z){let Y=$.slice(1).split(" "),Q=Y[0].toLowerCase(),J=Y.slice(1);switch(Q){case"exit":case"quit":case"sair":case"q":Z.cleanup();break;case"clear":case"limpar":Z.sessions.clear(),Z.tui.clearMessages(),Z.tui.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let z=J[0]||`s-${Date.now()}`;Z.sessions.switchTo(z),Z.tui.clearMessages(),Z.tui.updateSession(z),Z.tui.showSystem(`New session: ${z}`);break}case"load":case"carregar":{let z=J[0];if(!z){Z.tui.showError("Usage: /load <name>");break}Z.sessions.switchTo(z),Z.tui.clearMessages();for(let X of Z.sessions.messages)if(X.role==="user")Z.tui.addUserMessage(X.content);else Z.tui.addAssistantMessage(X.content);Z.tui.updateSession(z),Z.tui.showSystem(`Loaded: ${z}`);break}case"sessions":case"sessoes":case"ls":{let z=Z.sessions.list().map((V)=>{let G=Z.sessions.getInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:V===Z.sessions.session.name,isArchived:!1}}),X=Z.sessions.listArchived().map((V)=>{let G=Z.sessions.getArchivedInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:!1,isArchived:!0}}),K=await Z.tui.promptSessionPicker([...z,...X]);if(K)switch(K.action){case"load":{let V=K.name;if(X.some((q)=>q.name===V))Z.sessions.unarchive(V);Z.sessions.switchTo(V),Z.tui.clearMessages();for(let q of Z.sessions.messages)if(q.role==="user")Z.tui.addUserMessage(q.content);else Z.tui.addAssistantMessage(q.content);Z.tui.updateSession(V),Z.tui.showSystem(`Loaded: ${V}`);break}case"delete":{let V=K.name;if(K.isArchived?Z.sessions.deleteArchived(V):Z.sessions.delete(V))Z.tui.showSystem(`Deleted: ${V}`);else Z.tui.showError(`Not found: ${V}`);break}case"archive":if(Z.sessions.archive(K.name))Z.tui.showSystem(`Archived: ${K.name}`);else Z.tui.showError(`Failed to archive: ${K.name}`);break;case"unarchive":if(Z.sessions.unarchive(K.name))Z.tui.showSystem(`Restored: ${K.name}`);else Z.tui.showError(`Not found in archive: ${K.name}`);break}break}case"delete":case"deletar":case"rm":{let z=J[0];if(!z){Z.tui.showError("Usage: /delete <name>");break}if(Z.sessions.delete(z))Z.tui.showSystem(`Deleted: ${z}`);else Z.tui.showError(`Session not found: ${z}`);break}case"archive":case"arquivar":{let z=J[0];if(!z){Z.tui.showError("Uso: /archive <nome> ou /archive all");break}if(z==="all"||z==="todas"){let X=Z.sessions.archiveAll();if(X.length>0)Z.tui.showSystem(`Arquivadas ${X.length} sessoes: ${X.join(", ")}`);else Z.tui.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.sessions.archive(z))Z.tui.showSystem(`Sessao arquivada: "${z}"`);else Z.tui.showError(`Falha ao arquivar "${z}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let z=J[0];if(!z){Z.tui.showError("Uso: /unarchive <nome>");break}if(Z.sessions.unarchive(z))Z.tui.showSystem(`Sessao restaurada: "${z}"`);else Z.tui.showError(`Sessao arquivada nao encontrada: "${z}"`);break}case"archived":case"arquivadas":{let z=Z.sessions.listArchived();if(z.length===0){Z.tui.showSystem("Nenhuma sessao arquivada.");break}let X=z.map((K)=>{let V=Z.sessions.getArchivedInfo(K),G=V?SW(V.updated):"",q=V?`${V.messageCount} msgs`:"";return` ${K.padEnd(20)} ${q.padEnd(10)} ${G}`});Z.tui.showSystem(`Sessoes arquivadas (${z.length}):
703
+ - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function OK($){return BK[$.toLowerCase()]||null}function NK($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(BK)){let z=Y===$?" *":" ";Z.push(`${z} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
704
+ `)}s();async function MK($){try{let Z=j?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:s9?["pbcopy"]:["xclip","-selection","clipboard"],Y=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return Y.stdin.write($),Y.stdin.end(),await Y.exited===0}catch{return!1}}l();X$();import{writeFileSync as VO}from"fs";async function CK($,Z){let Y=$.slice(1).split(" "),Q=Y[0].toLowerCase(),z=Y.slice(1);switch(Q){case"exit":case"quit":case"sair":case"q":Z.cleanup();break;case"clear":case"limpar":Z.sessions.clear(),Z.tui.clearMessages(),Z.tui.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let J=z[0]||`s-${Date.now()}`;Z.sessions.switchTo(J),Z.tui.clearMessages(),Z.tui.updateSession(J),Z.tui.showSystem(`New session: ${J}`);break}case"load":case"carregar":{let J=z[0];if(!J){Z.tui.showError("Usage: /load <name>");break}Z.sessions.switchTo(J),Z.tui.clearMessages();for(let X of Z.sessions.messages)if(X.role==="user")Z.tui.addUserMessage(X.content);else Z.tui.addAssistantMessage(X.content);Z.tui.updateSession(J),Z.tui.showSystem(`Loaded: ${J}`);break}case"sessions":case"sessoes":case"ls":{let J=Z.sessions.list().map((G)=>{let V=Z.sessions.getInfo(G);return{name:G,messageCount:V?.messageCount??0,updated:V?.updated??0,isCurrent:G===Z.sessions.session.name,isArchived:!1}}),X=Z.sessions.listArchived().map((G)=>{let V=Z.sessions.getArchivedInfo(G);return{name:G,messageCount:V?.messageCount??0,updated:V?.updated??0,isCurrent:!1,isArchived:!0}}),K=await Z.tui.promptSessionPicker([...J,...X]);if(K)switch(K.action){case"load":{let G=K.name;if(X.some((U)=>U.name===G))Z.sessions.unarchive(G);Z.sessions.switchTo(G),Z.tui.clearMessages();for(let U of Z.sessions.messages)if(U.role==="user")Z.tui.addUserMessage(U.content);else Z.tui.addAssistantMessage(U.content);Z.tui.updateSession(G),Z.tui.showSystem(`Loaded: ${G}`);break}case"delete":{let G=K.name;if(K.isArchived?Z.sessions.deleteArchived(G):Z.sessions.delete(G))Z.tui.showSystem(`Deleted: ${G}`);else Z.tui.showError(`Not found: ${G}`);break}case"archive":if(Z.sessions.archive(K.name))Z.tui.showSystem(`Archived: ${K.name}`);else Z.tui.showError(`Failed to archive: ${K.name}`);break;case"unarchive":if(Z.sessions.unarchive(K.name))Z.tui.showSystem(`Restored: ${K.name}`);else Z.tui.showError(`Not found in archive: ${K.name}`);break}break}case"delete":case"deletar":case"rm":{let J=z[0];if(!J){Z.tui.showError("Usage: /delete <name>");break}if(Z.sessions.delete(J))Z.tui.showSystem(`Deleted: ${J}`);else Z.tui.showError(`Session not found: ${J}`);break}case"archive":case"arquivar":{let J=z[0];if(!J){Z.tui.showError("Uso: /archive <nome> ou /archive all");break}if(J==="all"||J==="todas"){let X=Z.sessions.archiveAll();if(X.length>0)Z.tui.showSystem(`Arquivadas ${X.length} sessoes: ${X.join(", ")}`);else Z.tui.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.sessions.archive(J))Z.tui.showSystem(`Sessao arquivada: "${J}"`);else Z.tui.showError(`Falha ao arquivar "${J}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let J=z[0];if(!J){Z.tui.showError("Uso: /unarchive <nome>");break}if(Z.sessions.unarchive(J))Z.tui.showSystem(`Sessao restaurada: "${J}"`);else Z.tui.showError(`Sessao arquivada nao encontrada: "${J}"`);break}case"archived":case"arquivadas":{let J=Z.sessions.listArchived();if(J.length===0){Z.tui.showSystem("Nenhuma sessao arquivada.");break}let X=J.map((K)=>{let G=Z.sessions.getArchivedInfo(K),V=G?UO(G.updated):"",U=G?`${G.messageCount} msgs`:"";return` ${K.padEnd(20)} ${U.padEnd(10)} ${V}`});Z.tui.showSystem(`Sessoes arquivadas (${J.length}):
696
705
  ${X.join(`
697
- `)}`);break}case"model":case"modelo":{let z=J[0];if(!z){Z.tui.showSystem(j6(Z.config.model)+`
706
+ `)}`);break}case"model":case"modelo":{let J=z[0];if(!J){Z.tui.showSystem(MY(Z.config.model)+`
698
707
 
699
- `+uJ());break}let{provider:X,model:K}=o5(z),V=X==="anthropic"?x4(K):K;if(Z.config.model=X==="anthropic"?V:`${X}:${V}`,b4(Z.config),X==="anthropic")Z.claude.setModel(V);else Z.tui.showSystem(`Note: ${X} provider selected. Restart smolerclaw for full provider switch.`);Z.tracker.setModel(V),Z.tui.updateModel(Z.config.model),Z.tui.showSystem(`Model -> ${Z.config.model}`);break}case"skills":case"habilidades":{Z.tui.showSystem(tJ(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
700
- Expires: ${new Date(Z.auth.auth.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{Z.tui.showSystem("Renovando sessao Claude...");try{let z=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>z.kill(),15000);await z.exited,clearTimeout(X);let K=g0();if(K){if(Z.auth.auth=K,"updateToken"in Z.claude)Z.claude.updateToken(K.token);cz(K),Z.tui.showSystem(`Sessao renovada. Expira: ${new Date(K.expiresAt).toLocaleString()}`)}else Z.tui.showSystem("claude executado, mas credenciais nao atualizaram. Tente novamente.")}catch(z){Z.tui.showError(`Falha ao renovar: ${z instanceof Error?z.message:String(z)}`)}break}case"auto-refresh":case"autorefresh":{Z.tui.showSystem(lz());break}case"config":Z.tui.showSystem(`Config: ${y4()}`);break;case"export":case"exportar":{let z=new Date().toISOString().split("T")[0],X=J[0]||`smolerclaw-${Z.sessions.session.name}-${z}.md`;try{let K=VX(Z.sessions.session);IW(X,K),Z.tui.showSystem(`Exported to: ${X}`)}catch(K){Z.tui.showError(`Export failed: ${K instanceof Error?K.message:K}`)}break}case"cost":case"custo":Z.tui.showSystem(`Session: ${Z.tracker.formatSession()}`);break;case"retry":case"repetir":{let z=[...Z.sessions.messages].reverse().find((G)=>G.role==="user");if(!z){Z.tui.showError("No previous message to retry.");break}let X=Z.sessions.messages,K=0;if(X.length>0&&X[X.length-1].role==="assistant")K++;if(X.length>K&&X[X.length-1-K].role==="user")K++;if(K>0)Z.sessions.popMessages(K);Z.tui.showSystem("Retrying...");let V=z.images?.length?z.content:z.content;await Z.handleSubmit(V);break}case"help":case"ajuda":case"?":Z.tui.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar Deletar sessao"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma"," /commit /commitar Git commit com IA"," /exit /sair Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias"," /open /abrir Abrir app Windows"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral","","Monitor:"," /monitor /vigiar Monitorar processo (ex: /monitor nginx)"," /monitor stop <nome> Parar monitoramento","","Workflows:"," /workflow /fluxo Listar workflows"," /workflow run <nome> Executar (ex: /workflow iniciar-dia)","","Pomodoro:"," /pomodoro /foco Iniciar (ex: /foco revisar codigo)"," /pomodoro status Ver tempo restante"," /pomodoro stop Parar","","Financas / Finance:"," /entrada <$> <cat> Registrar entrada"," /saida <$> <cat> Registrar saida"," /finance /balanco Resumo mensal","","Auth:"," /refresh /renovar Renovar sessao manualmente"," /auto-refresh Status do auto-refresh de token","","Plugins:"," /plugins /plugin Listar plugins"," /plugin install owner/r Instalar do GitHub"," /plugin uninstall <n> Desinstalar plugin"," /plugin installed Listar instalados"," /plugin info <nome> Detalhes do plugin"," /plugin enable <n> Habilitar plugin"," /plugin disable <n> Desabilitar plugin","","Decisoes / Decisions:"," /decisoes [busca] Listar/buscar decisoes","","Email:"," /email /rascunho Rascunho (ex: /email joao@x.com oi | texto)","","Memos / Notes:"," /memo /anotar Salvar memo (ex: /memo senha wifi #casa)"," /memos /notas Buscar memos (ex: /memos docker)"," /tags /memotags Listar tags"," /rmmemo /rmnota Remover memo","","Materiais / Materials:"," /material /mat Salvar material (ex: /mat titulo | conteudo)"," /materials /materiais Listar/buscar materiais"," /matcats /categorias Listar categorias"," /rmmat /rmmaterial Remover material","","Arquivo / Archive:"," /archive /arquivar Arquivar sessao (ex: /archive minha-sessao)"," /archive all Arquivar todas exceto a atual"," /archived /arquivadas Listar sessoes arquivadas"," /unarchive /restaurar Restaurar sessao arquivada","","Investigacao / Investigation:"," /investigar /investigate Listar investigacoes"," /investigar <busca> Buscar por palavra-chave","","Tarefas / Tasks:"," /task /tarefa Criar tarefa (ex: /tarefa 18h buscar pao)"," /tasks /tarefas Listar pendentes"," /done /feito Marcar como concluida"," /rmtask /rmtarefa Remover tarefa","","Meta-Learning:"," /reflect /reflexao Analisa uso e gera insights","","Tab completes commands. Use \\ at end of line for multi-line.","","Keys:"," Ctrl+C Cancel stream / exit"," Ctrl+D Exit"," Ctrl+L Redraw screen"," Up/Down Input history"," PgUp/PgDown Scroll messages"].join(`
701
- `));break;case"commit":case"commitar":{if(!await WX()){Z.tui.showError("Not a git repository.");break}let z=await qX();if(z==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
702
- `+z),Z.tui.disableInput();try{let K=`Generate a concise git commit message for these changes. Use conventional commits format (feat:, fix:, refactor:, docs:, chore:, etc.). One line, max 72 chars. No quotes. Just the message.
708
+ `+s3());break}let{provider:X,model:K}=U7(J),G=X==="anthropic"?n8(K):K;if(Z.config.model=X==="anthropic"?G:`${X}:${G}`,o8(Z.config),X==="anthropic")Z.claude.setModel(G);else Z.tui.showSystem(`Note: ${X} provider selected. Restart smolerclaw for full provider switch.`);Z.tracker.setModel(G),Z.tui.updateModel(Z.config.model),Z.tui.showSystem(`Model -> ${Z.config.model}`);break}case"skills":case"habilidades":{Z.tui.showSystem(GX(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
709
+ Expires: ${new Date(Z.auth.auth.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{Z.tui.showSystem("Renovando sessao Claude...");try{let J=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>J.kill(),15000);await J.exited,clearTimeout(X);let K=u1();if(K){if(Z.auth.auth=K,"updateToken"in Z.claude)Z.claude.updateToken(K.token);dX(K),Z.tui.showSystem(`Sessao renovada. Expira: ${new Date(K.expiresAt).toLocaleString()}`)}else Z.tui.showSystem("claude executado, mas credenciais nao atualizaram. Tente novamente.")}catch(J){Z.tui.showError(`Falha ao renovar: ${J instanceof Error?J.message:String(J)}`)}break}case"auto-refresh":case"autorefresh":{Z.tui.showSystem(cX());break}case"config":Z.tui.showSystem(`Config: ${i8()}`);break;case"export":case"exportar":{let J=new Date().toISOString().split("T")[0],X=z[0]||`smolerclaw-${Z.sessions.session.name}-${J}.md`;try{let K=GK(Z.sessions.session);VO(X,K),Z.tui.showSystem(`Exported to: ${X}`)}catch(K){Z.tui.showError(`Export failed: ${K instanceof Error?K.message:K}`)}break}case"cost":case"custo":Z.tui.showSystem(`Session: ${Z.tracker.formatSession()}`);break;case"retry":case"repetir":{let J=[...Z.sessions.messages].reverse().find((V)=>V.role==="user");if(!J){Z.tui.showError("No previous message to retry.");break}let X=Z.sessions.messages,K=0;if(X.length>0&&X[X.length-1].role==="assistant")K++;if(X.length>K&&X[X.length-1-K].role==="user")K++;if(K>0)Z.sessions.popMessages(K);Z.tui.showSystem("Retrying...");let G=J.images?.length?J.content:J.content;await Z.handleSubmit(G);break}case"help":case"ajuda":case"?":Z.tui.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar Deletar sessao"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma"," /commit /commitar Git commit com IA"," /exit /sair Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias"," /open /abrir Abrir app Windows"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral","","Monitor:"," /monitor /vigiar Monitorar processo (ex: /monitor nginx)"," /monitor stop <nome> Parar monitoramento","","Workflows:"," /workflow /fluxo Listar workflows"," /workflow run <nome> Executar (ex: /workflow iniciar-dia)","","Pomodoro:"," /pomodoro /foco Iniciar (ex: /foco revisar codigo)"," /pomodoro status Ver tempo restante"," /pomodoro stop Parar","","Financas / Finance:"," /entrada <$> <cat> Registrar entrada"," /saida <$> <cat> Registrar saida"," /finance /balanco Resumo mensal","","Auth:"," /refresh /renovar Renovar sessao manualmente"," /auto-refresh Status do auto-refresh de token","","Plugins:"," /plugins /plugin Listar plugins"," /plugin install owner/r Instalar do GitHub"," /plugin uninstall <n> Desinstalar plugin"," /plugin installed Listar instalados"," /plugin info <nome> Detalhes do plugin"," /plugin enable <n> Habilitar plugin"," /plugin disable <n> Desabilitar plugin","","Decisoes / Decisions:"," /decisoes [busca] Listar/buscar decisoes","","Email:"," /email /rascunho Rascunho (ex: /email joao@x.com oi | texto)","","Memos / Notes:"," /memo /anotar Salvar memo (ex: /memo senha wifi #casa)"," /memos /notas Buscar memos (ex: /memos docker)"," /tags /memotags Listar tags"," /rmmemo /rmnota Remover memo","","Materiais / Materials:"," /material /mat Salvar material (ex: /mat titulo | conteudo)"," /materials /materiais Listar/buscar materiais"," /matcats /categorias Listar categorias"," /rmmat /rmmaterial Remover material","","Arquivo / Archive:"," /archive /arquivar Arquivar sessao (ex: /archive minha-sessao)"," /archive all Arquivar todas exceto a atual"," /archived /arquivadas Listar sessoes arquivadas"," /unarchive /restaurar Restaurar sessao arquivada","","Investigacao / Investigation:"," /investigar /investigate Listar investigacoes"," /investigar <busca> Buscar por palavra-chave","","Tarefas / Tasks:"," /task /tarefa Criar tarefa (ex: /tarefa 18h buscar pao)"," /tasks /tarefas Listar pendentes"," /done /feito Marcar como concluida"," /rmtask /rmtarefa Remover tarefa","","Meta-Learning:"," /reflect /reflexao Analisa uso e gera insights","","Tab completes commands. Use \\ at end of line for multi-line.","","Keys:"," Ctrl+C Cancel stream / exit"," Ctrl+D Exit"," Ctrl+L Redraw screen"," Up/Down Input history"," PgUp/PgDown Scroll messages"].join(`
710
+ `));break;case"commit":case"commitar":{if(!await WK()){Z.tui.showError("Not a git repository.");break}let J=await UK();if(J==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
711
+ `+J),Z.tui.disableInput();try{let K=`Generate a concise git commit message for these changes. Use conventional commits format (feat:, fix:, refactor:, docs:, chore:, etc.). One line, max 72 chars. No quotes. Just the message.
703
712
 
704
713
  Diff:
705
- ${(await GX()).slice(0,8000)}`;Z.tui.startStream();let V="";for await(let q of Z.claude.chat([{role:"user",content:K,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(q.type==="text")V+=q.text,Z.tui.appendStream(q.text);else if(q.type==="error")Z.tui.showError(q.error);if(Z.tui.endStream(),V=V.trim().replace(/^["']|["']$/g,""),!V){Z.tui.showError("Failed to generate commit message. Aborting.");break}await UX();let G=await HX(V);if(G.ok)Z.tui.showSystem(`Committed: ${V}`);else Z.tui.showError(`Commit failed: ${G.output}`)}catch(X){Z.tui.showError(`Commit error: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput();break}case"persona":case"modo":{let z=J[0];if(!z){Z.tui.showSystem(CX(Z.currentPersona));break}let X=MX(z);if(!X){Z.tui.showError(`Unknown persona: ${z}. Try /persona to see options.`);break}if(Z.setCurrentPersona(X.name),X.systemPrompt)Z.setActiveSystemPrompt(n5(X.systemPrompt,Z.skills,Z.config.language));else Z.setActiveSystemPrompt(Z.systemPrompt);Z.tui.showSystem(`Persona -> ${X.name}: ${X.description}`);break}case"copy":case"copiar":{let z=[...Z.sessions.messages].reverse().find((K)=>K.role==="assistant");if(!z){Z.tui.showError("No assistant message to copy.");break}if(await NX(z.content))Z.tui.showSystem("Copied last response to clipboard.");else Z.tui.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let z=J.join(" ");if(!z){Z.tui.showError("Usage: /ask <question>");break}Z.tui.addUserMessage(`(ephemeral) ${z}`),Z.tui.disableInput(),Z.tui.startStream();let X="";for await(let K of Z.claude.chat([{role:"user",content:z,timestamp:Date.now()}],Z.activeSystemPrompt,!1))if(K.type==="text")X+=K.text,Z.tui.appendStream(K.text);else if(K.type==="error")Z.tui.showError(K.error);else if(K.type==="usage")Z.tui.showUsage(`${K.inputTokens} in / ${K.outputTokens} out (ephemeral)`);Z.tui.endStream(),Z.tui.enableInput();break}case"fork":{let z=J[0]||`fork-${Date.now()}`;Z.sessions.fork(z),Z.tui.updateSession(z),Z.tui.showSystem(`Forked session -> ${z} (${Z.sessions.messages.length} messages copied)`);break}case"plugins":case"plugin":{let z=J[0];if(z==="disable"||z==="desabilitar"){let X=J[1];if(!X){Z.tui.showSystem("Uso: /plugin disable <nome>");break}if(Yz(X))Z.tui.showSystem(`Plugin "${X}" desabilitado.`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else if(z==="enable"||z==="habilitar"){let X=J[1];if(!X){Z.tui.showSystem("Uso: /plugin enable <nome>");break}if(await Qz(X))Z.tui.showSystem(`Plugin "${X}" habilitado.`);else Z.tui.showError(`Plugin "${X}" nao encontrado ou ja habilitado.`)}else if(z==="install"||z==="instalar"){let X=J[1];if(!X){Z.tui.showSystem("Uso: /plugin install owner/repo");break}Z.tui.showSystem(`Instalando plugin de ${X}...`);let K=await Jz(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(z==="uninstall"||z==="desinstalar"){let X=J[1];if(!X){Z.tui.showSystem("Uso: /plugin uninstall <nome>");break}let K=zz(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(z==="installed"||z==="instalados"){let X=Xz();if(X.length===0)Z.tui.showSystem("Nenhum plugin instalado do GitHub.");else{let K=["Plugins instalados do GitHub:"];for(let V of X){let G=new Date(V.installedAt).toLocaleDateString("pt-BR");K.push(` ${V.name} \u2014 github.com/${V.source} (${G})`)}Z.tui.showSystem(K.join(`
706
- `))}}else if(z==="info"){let X=J[1];if(!X){Z.tui.showSystem("Uso: /plugin info <nome>");break}let K=Kz(X);if(K)Z.tui.showSystem(`${K.name} v${K.version} (${K.type})
714
+ ${(await VK()).slice(0,8000)}`;Z.tui.startStream();let G="";for await(let U of Z.claude.chat([{role:"user",content:K,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(U.type==="text")G+=U.text,Z.tui.appendStream(U.text);else if(U.type==="error")Z.tui.showError(U.error);if(Z.tui.endStream(),G=G.trim().replace(/^["']|["']$/g,""),!G){Z.tui.showError("Failed to generate commit message. Aborting.");break}await qK();let V=await HK(G);if(V.ok)Z.tui.showSystem(`Committed: ${G}`);else Z.tui.showError(`Commit failed: ${V.output}`)}catch(X){Z.tui.showError(`Commit error: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput();break}case"persona":case"modo":{let J=z[0];if(!J){Z.tui.showSystem(NK(Z.currentPersona));break}let X=OK(J);if(!X){Z.tui.showError(`Unknown persona: ${J}. Try /persona to see options.`);break}if(Z.setCurrentPersona(X.name),X.systemPrompt)Z.setActiveSystemPrompt(H7(X.systemPrompt,Z.skills,Z.config.language));else Z.setActiveSystemPrompt(Z.systemPrompt);Z.tui.showSystem(`Persona -> ${X.name}: ${X.description}`);break}case"copy":case"copiar":{let J=[...Z.sessions.messages].reverse().find((K)=>K.role==="assistant");if(!J){Z.tui.showError("No assistant message to copy.");break}if(await MK(J.content))Z.tui.showSystem("Copied last response to clipboard.");else Z.tui.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let J=z.join(" ");if(!J){Z.tui.showError("Usage: /ask <question>");break}Z.tui.addUserMessage(`(ephemeral) ${J}`),Z.tui.disableInput(),Z.tui.startStream();let X="";for await(let K of Z.claude.chat([{role:"user",content:J,timestamp:Date.now()}],Z.activeSystemPrompt,!1))if(K.type==="text")X+=K.text,Z.tui.appendStream(K.text);else if(K.type==="error")Z.tui.showError(K.error);else if(K.type==="usage")Z.tui.showUsage(`${K.inputTokens} in / ${K.outputTokens} out (ephemeral)`);Z.tui.endStream(),Z.tui.enableInput();break}case"fork":{let J=z[0]||`fork-${Date.now()}`;Z.sessions.fork(J),Z.tui.updateSession(J),Z.tui.showSystem(`Forked session -> ${J} (${Z.sessions.messages.length} messages copied)`);break}case"plugins":case"plugin":{let J=z[0];if(J==="disable"||J==="desabilitar"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin disable <nome>");break}if(B3(X))Z.tui.showSystem(`Plugin "${X}" desabilitado.`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else if(J==="enable"||J==="habilitar"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin enable <nome>");break}if(await O3(X))Z.tui.showSystem(`Plugin "${X}" habilitado.`);else Z.tui.showError(`Plugin "${X}" nao encontrado ou ja habilitado.`)}else if(J==="install"||J==="instalar"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin install owner/repo");break}Z.tui.showSystem(`Instalando plugin de ${X}...`);let K=await N3(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(J==="uninstall"||J==="desinstalar"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin uninstall <nome>");break}let K=M3(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(J==="installed"||J==="instalados"){let X=C3();if(X.length===0)Z.tui.showSystem("Nenhum plugin instalado do GitHub.");else{let K=["Plugins instalados do GitHub:"];for(let G of X){let V=new Date(G.installedAt).toLocaleDateString("pt-BR");K.push(` ${G.name} \u2014 github.com/${G.source} (${V})`)}Z.tui.showSystem(K.join(`
715
+ `))}}else if(J==="info"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin info <nome>");break}let K=E3(X);if(K)Z.tui.showSystem(`${K.name} v${K.version} (${K.type})
707
716
  ${K.description}
708
717
  Status: ${K.enabled?"ativo":"desabilitado"}
709
718
  Source: ${K.source}
710
- Tools: ${K.tools.map((V)=>V.name).join(", ")||"nenhuma"}`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else Z.tui.showSystem(Vz());break}case"budget":case"orcamento":{let z=J[0];if(!z){let K=Z.config.maxSessionCost,V=Z.tracker.totals.costCents;if(K===0)Z.tui.showSystem(`Budget: unlimited (spent ~$${(V/100).toFixed(4)})`);else{let G=Math.round(V/K*100);Z.tui.showSystem(`Budget: ~$${(V/100).toFixed(4)} / $${(K/100).toFixed(4)} (${G}%)`)}break}let X=Number(z);if(isNaN(X)||X<0){Z.tui.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Z.config.maxSessionCost=X,b4(Z.config),Z.tui.showSystem(X===0?"Budget: unlimited":`Budget set: $${(X/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!g1.peek()){Z.tui.showError("Nothing to undo.");break}let X=g1.undo();if(X)Z.tui.showSystem(X);break}case"search":case"buscar":{let z=J.join(" ").toLowerCase();if(!z){Z.tui.showError("Usage: /search <text>");break}let X=[];for(let K of Z.sessions.messages)if(K.content.toLowerCase().includes(z)){let V=K.content.slice(0,100).replace(/\n/g," "),G=new Date(K.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});X.push(` [${K.role} ${G}] ${V}${K.content.length>100?"...":""}`)}Z.tui.showSystem(X.length>0?`Found ${X.length} match${X.length>1?"es":""}:
719
+ Tools: ${K.tools.map((G)=>G.name).join(", ")||"nenhuma"}`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else Z.tui.showSystem(R3());break}case"budget":case"orcamento":{let J=z[0];if(!J){let K=Z.config.maxSessionCost,G=Z.tracker.totals.costCents;if(K===0)Z.tui.showSystem(`Budget: unlimited (spent ~$${(G/100).toFixed(4)})`);else{let V=Math.round(G/K*100);Z.tui.showSystem(`Budget: ~$${(G/100).toFixed(4)} / $${(K/100).toFixed(4)} (${V}%)`)}break}let X=Number(J);if(isNaN(X)||X<0){Z.tui.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Z.config.maxSessionCost=X,o8(Z.config),Z.tui.showSystem(X===0?"Budget: unlimited":`Budget set: $${(X/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!o$.peek()){Z.tui.showError("Nothing to undo.");break}let X=o$.undo();if(X)Z.tui.showSystem(X);break}case"search":case"buscar":{let J=z.join(" ").toLowerCase();if(!J){Z.tui.showError("Usage: /search <text>");break}let X=[];for(let K of Z.sessions.messages)if(K.content.toLowerCase().includes(J)){let G=K.content.slice(0,100).replace(/\n/g," "),V=new Date(K.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});X.push(` [${K.role} ${V}] ${G}${K.content.length>100?"...":""}`)}Z.tui.showSystem(X.length>0?`Found ${X.length} match${X.length>1?"es":""}:
711
720
  ${X.join(`
712
- `)}`:`No matches for "${z}".`);break}case"lang":case"language":case"idioma":{let z=J[0];if(!z){Z.tui.showSystem(`Language: ${Z.config.language} (auto = match user's language)`);break}Z.config.language=z,b4(Z.config),Z.tui.showSystem(`Language -> ${z}`);break}case"briefing":case"resumo":{Z.tui.showSystem("Carregando briefing..."),Z.tui.disableInput();try{let z=await Iz(Z.config.dataDir);Z.tui.showSystem(z);let X=await H4(Z.config.dataDir);Z.tui.setTimeContext(X),Z.setTimeContext(X)}catch(z){Z.tui.showError(`Briefing falhou: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"news":case"noticias":{let z=J[0];if(z)Z.tui.showSystem(`Buscando noticias (${z})...`);else Z.tui.showSystem("Buscando noticias...");Z.tui.disableInput();try{let{items:X,errors:K}=await Y9(z?[z]:void 0);if(X.length===0){Z.tui.showSystem(K.length>0?`Nenhuma noticia encontrada.
713
- Falhas: ${K.join(", ")}`:"Nenhuma noticia encontrada."),Z.tui.enableInput();break}let V=X.map((q)=>({title:q.title,link:q.link,source:q.source,category:q.category,time:q.pubDate?q.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),G=await Z.tui.promptNewsPicker(V);if(G){if(G.action==="open"){let{openUrl:q}=await Promise.resolve().then(() => (J1(),gQ));q(G.link),Z.tui.showSystem(`Abrindo: ${G.link}`)}else if(G.action==="read"){Z.tui.showSystem("Buscando conteudo...");let q=await D3(G.link);if(typeof q==="string")Z.tui.showError(q);else{let W=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
721
+ `)}`:`No matches for "${J}".`);break}case"lang":case"language":case"idioma":{let J=z[0];if(!J){Z.tui.showSystem(`Language: ${Z.config.language} (auto = match user's language)`);break}Z.config.language=J,o8(Z.config),Z.tui.showSystem(`Language -> ${J}`);break}case"briefing":case"resumo":{Z.tui.showSystem("Carregando briefing..."),Z.tui.disableInput();try{let J=await TX(Z.config.dataDir);Z.tui.showSystem(J);let X=await L8(Z.config.dataDir);Z.tui.setTimeContext(X),Z.setTimeContext(X)}catch(J){Z.tui.showError(`Briefing falhou: ${J instanceof Error?J.message:String(J)}`)}Z.tui.enableInput();break}case"news":case"noticias":{let J=z[0];if(J)Z.tui.showSystem(`Buscando noticias (${J})...`);else Z.tui.showSystem("Buscando noticias...");Z.tui.disableInput();try{let{items:X,errors:K}=await T6(J?[J]:void 0);if(X.length===0){Z.tui.showSystem(K.length>0?`Nenhuma noticia encontrada.
722
+ Falhas: ${K.join(", ")}`:"Nenhuma noticia encontrada."),Z.tui.enableInput();break}let G=X.map((U)=>({title:U.title,link:U.link,source:U.source,category:U.category,time:U.pubDate?U.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),V=await Z.tui.promptNewsPicker(G);if(V){if(V.action==="open"){let{openUrl:U}=await Promise.resolve().then(() => (X$(),fJ));U(V.link),Z.tui.showSystem(`Abrindo: ${V.link}`)}else if(V.action==="read"){Z.tui.showSystem("Buscando conteudo...");let U=await CQ(V.link);if(typeof U==="string")Z.tui.showError(U);else{let H=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
714
723
 
715
- ${`Noticia: ${q.title}
716
- Fonte: ${G.link}
724
+ ${`Noticia: ${U.title}
725
+ Fonte: ${V.link}
717
726
 
718
- ${q.content}`}`;Z.tui.enableInput(),Z.handleSubmit(W);return}}}}catch(X){Z.tui.showError(`Falha ao buscar noticias: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput();break}case"feeds":case"fontes":{Z.tui.showSystem(O7());break}case"addfeed":case"novafonte":{if(J.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
719
- Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let z=J[0],X=J[1],K=J[2],V=B7(z,X,K);if(typeof V==="string")Z.tui.showError(V);else Z.tui.showSystem(`Fonte adicionada: ${V.name} (${V.category}) \u2014 ${V.url}`);break}case"rmfeed":case"rmfonte":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /rmfeed <nome ou url>");break}if(M7(z))Z.tui.showSystem(`Fonte removida: ${z}`);else Z.tui.showError(`Fonte custom nao encontrada: "${z}". Para desativar uma built-in, use /disablefeed.`);break}case"disablefeed":case"desativarfonte":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /disablefeed <nome ou url>");break}if(C7(z))Z.tui.showSystem(`Fonte desativada: ${z}`);else Z.tui.showError(`Fonte built-in nao encontrada ou ja desativada: "${z}"`);break}case"enablefeed":case"ativarfonte":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /enablefeed <nome ou url>");break}if(N7(z))Z.tui.showSystem(`Fonte reativada: ${z}`);else Z.tui.showError(`Fonte built-in nao encontrada ou nao esta desativada: "${z}"`);break}case"open":case"abrir":{if(!J.join(" ")){Z.tui.showSystem(`Apps disponiveis: ${o9().join(", ")}
720
- Uso: /open <app> ou /open <app> <arquivo>`);break}let X=J.length>1?J.slice(1).join(" "):void 0,K=await $1(J[0],X);Z.tui.showSystem(K);break}case"openfile":case"abrirarquivo":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /openfile <caminho>");break}let X=await s8(z);Z.tui.showSystem(X);break}case"openurl":{let z=J[0];if(!z){Z.tui.showError("Uso: /openurl <url>");break}let X=await Z1(z);Z.tui.showSystem(X);break}case"apps":case"programas":{Z.tui.disableInput();try{let z=await t8();Z.tui.showSystem(z)}catch(z){Z.tui.showError(`Apps: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"sysinfo":case"sistema":{Z.tui.disableInput();try{let z=await Y1();Z.tui.showSystem(z)}catch(z){Z.tui.showError(`Sysinfo: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{Z.tui.disableInput();try{let z=await Q1(),X=await f$();Z.tui.showSystem(`${z}
727
+ ${U.content}`}`;Z.tui.enableInput(),Z.handleSubmit(H);return}}}}catch(X){Z.tui.showError(`Falha ao buscar noticias: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput();break}case"feeds":case"fontes":{Z.tui.showSystem(f4());break}case"addfeed":case"novafonte":{if(z.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
728
+ Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let J=z[0],X=z[1],K=z[2],G=I4(J,X,K);if(typeof G==="string")Z.tui.showError(G);else Z.tui.showSystem(`Fonte adicionada: ${G.name} (${G.category}) \u2014 ${G.url}`);break}case"rmfeed":case"rmfonte":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /rmfeed <nome ou url>");break}if(S4(J))Z.tui.showSystem(`Fonte removida: ${J}`);else Z.tui.showError(`Fonte custom nao encontrada: "${J}". Para desativar uma built-in, use /disablefeed.`);break}case"disablefeed":case"desativarfonte":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /disablefeed <nome ou url>");break}if(w4(J))Z.tui.showSystem(`Fonte desativada: ${J}`);else Z.tui.showError(`Fonte built-in nao encontrada ou ja desativada: "${J}"`);break}case"enablefeed":case"ativarfonte":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /enablefeed <nome ou url>");break}if(k4(J))Z.tui.showSystem(`Fonte reativada: ${J}`);else Z.tui.showError(`Fonte built-in nao encontrada ou nao esta desativada: "${J}"`);break}case"open":case"abrir":{if(!z.join(" ")){Z.tui.showSystem(`Apps disponiveis: ${CZ().join(", ")}
729
+ Uso: /open <app> ou /open <app> <arquivo>`);break}let X=z.length>1?z.slice(1).join(" "):void 0,K=await Y$(z[0],X);Z.tui.showSystem(K);break}case"openfile":case"abrirarquivo":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /openfile <caminho>");break}let X=await J8(J);Z.tui.showSystem(X);break}case"openurl":{let J=z[0];if(!J){Z.tui.showError("Uso: /openurl <url>");break}let X=await Q$(J);Z.tui.showSystem(X);break}case"apps":case"programas":{Z.tui.disableInput();try{let J=await X8();Z.tui.showSystem(J)}catch(J){Z.tui.showError(`Apps: ${J instanceof Error?J.message:String(J)}`)}Z.tui.enableInput();break}case"sysinfo":case"sistema":{Z.tui.disableInput();try{let J=await z$();Z.tui.showSystem(J)}catch(J){Z.tui.showError(`Sysinfo: ${J instanceof Error?J.message:String(J)}`)}Z.tui.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{Z.tui.disableInput();try{let J=await J$(),X=await l0();Z.tui.showSystem(`${J}
721
730
 
722
731
  --- Agenda ---
723
- ${X}`)}catch(z){Z.tui.showError(`Calendar: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"monitor":case"vigiar":{let z=J[0]?.toLowerCase();if(!z||z==="list"||z==="listar")Z.tui.showSystem(uz());else if(z==="stop"||z==="parar"){let X=J[1];if(!X){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(mz(X))}else{let X=parseInt(J[1])||60;Z.tui.showSystem(gz(z,X))}break}case"workflow":case"fluxo":{let z=J[0]?.toLowerCase();if(!z||z==="list"||z==="listar"){let X=J[1];Z.tui.showSystem(zX(YX(X)))}else if(z==="run"||z==="rodar"){let X=J[1];if(!X){Z.tui.showError("Uso: /workflow run <nome>");break}Z.tui.disableInput();try{let K=await dZ(X,(V)=>Z.tui.showSystem(V));Z.tui.showSystem(K)}catch(K){Z.tui.showError(`Workflow: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput()}else if(z==="info"||z==="detalhe"){let X=J[1];if(!X){Z.tui.showError("Uso: /workflow info <nome>");break}let K=B4(X);if(K)Z.tui.showSystem(XX(K));else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else if(z==="delete"||z==="deletar"){let X=J[1];if(!X){Z.tui.showError("Uso: /workflow delete <nome>");break}if(QX(X))Z.tui.showSystem(`Workflow removido: ${X}`);else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else if(z==="enable"||z==="ativar"){let X=J[1];if(!X){Z.tui.showError("Uso: /workflow enable <nome>");break}let K=pZ(X,{enabled:!0});if(K)Z.tui.showSystem(`Workflow ativado: ${K.name}`);else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else if(z==="disable"||z==="desativar"){let X=J[1];if(!X){Z.tui.showError("Uso: /workflow disable <nome>");break}let K=pZ(X,{enabled:!1});if(K)Z.tui.showSystem(`Workflow desativado: ${K.name}`);else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else{Z.tui.disableInput();try{let X=await dZ(z,(K)=>Z.tui.showSystem(K));Z.tui.showSystem(X)}catch(X){Z.tui.showError(`Workflow: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput()}break}case"pomodoro":case"foco":{let z=J[0]?.toLowerCase();if(z==="stop"||z==="parar")Z.tui.showSystem(yz());else if(z==="status")Z.tui.showSystem(fZ());else if(!z)Z.tui.showSystem(fZ());else{let X=J.join(" "),K=25,V=5;Z.tui.showSystem(bz(X,25,5))}break}case"agendar":case"schedule":{let z=J[0]?.toLowerCase();if(!z||z==="list"||z==="listar"){let M=m8(J[1]==="all"||J[1]==="todos");Z.tui.showSystem(u8(M));break}if(z==="remove"||z==="remover"||z==="delete"){if(!J[1]){Z.tui.showSystem("Uso: /agendar remove <id ou nome>");break}let M=await w7(J[1]);Z.tui.showSystem(M?"Agendamento removido.":"Agendamento nao encontrado.");break}if(z==="enable"||z==="ativar"){if(!J[1]){Z.tui.showSystem("Uso: /agendar ativar <id ou nome>");break}let M=await k7(J[1]);Z.tui.showSystem(M?`Agendamento "${M.name}" ativado.`:"Agendamento nao encontrado.");break}if(z==="disable"||z==="desativar"){if(!J[1]){Z.tui.showSystem("Uso: /agendar desativar <id ou nome>");break}let M=await b7(J[1]);Z.tui.showSystem(M?`Agendamento "${M.name}" desativado.`:"Agendamento nao encontrado.");break}if(z==="run"||z==="executar"){if(!J[1]){Z.tui.showSystem("Uso: /agendar executar <id ou nome>");break}Z.tui.showSystem(await y7(J[1]));break}if(z==="clear"||z==="limpar"){Z.tui.showSystem(await n3());break}if(z==="detail"||z==="detalhe"||z==="info"){if(!J[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let M=o3(J[1]);Z.tui.showSystem(M?K9(M):"Agendamento nao encontrado.");break}let X=J.join(" "),K=X.match(/"([^"]+)"/g);if(!K||K.length<2){Z.tui.showSystem(`Uso: /agendar "<mensagem>" "<horario>" [once|daily|weekly] [data/dia]
732
+ ${X}`)}catch(J){Z.tui.showError(`Calendar: ${J instanceof Error?J.message:String(J)}`)}Z.tui.enableInput();break}case"monitor":case"vigiar":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar")Z.tui.showSystem(mX());else if(J==="stop"||J==="parar"){let X=z[1];if(!X){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(gX(X))}else{let X=parseInt(z[1])||60;Z.tui.showSystem(hX(J,X))}break}case"workflow":case"fluxo":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let X=z[1];Z.tui.showSystem(zK(ZK(X)))}else if(J==="run"||J==="rodar"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow run <nome>");break}Z.tui.disableInput();try{let K=await N9(X,(G)=>Z.tui.showSystem(G));Z.tui.showSystem(K)}catch(K){Z.tui.showError(`Workflow: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput()}else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow info <nome>");break}let K=A8(X);if(K)Z.tui.showSystem(JK(K));else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else if(J==="delete"||J==="deletar"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow delete <nome>");break}if(YK(X))Z.tui.showSystem(`Workflow removido: ${X}`);else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else if(J==="enable"||J==="ativar"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow enable <nome>");break}let K=O9(X,{enabled:!0});if(K)Z.tui.showSystem(`Workflow ativado: ${K.name}`);else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else if(J==="disable"||J==="desativar"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow disable <nome>");break}let K=O9(X,{enabled:!1});if(K)Z.tui.showSystem(`Workflow desativado: ${K.name}`);else Z.tui.showError(`Workflow nao encontrado: ${X}`)}else{Z.tui.disableInput();try{let X=await N9(J,(K)=>Z.tui.showSystem(K));Z.tui.showSystem(X)}catch(X){Z.tui.showError(`Workflow: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput()}break}case"pomodoro":case"foco":{let J=z[0]?.toLowerCase();if(J==="stop"||J==="parar")Z.tui.showSystem(fX());else if(J==="status")Z.tui.showSystem(U9());else if(!J)Z.tui.showSystem(U9());else{let X=z.join(" "),K=25,G=5;Z.tui.showSystem(kX(X,25,5))}break}case"agendar":case"schedule":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let O=r2(z[1]==="all"||z[1]==="todos");Z.tui.showSystem(n2(O));break}if(J==="remove"||J==="remover"||J==="delete"){if(!z[1]){Z.tui.showSystem("Uso: /agendar remove <id ou nome>");break}let O=await c4(z[1]);Z.tui.showSystem(O?"Agendamento removido.":"Agendamento nao encontrado.");break}if(J==="enable"||J==="ativar"){if(!z[1]){Z.tui.showSystem("Uso: /agendar ativar <id ou nome>");break}let O=await l4(z[1]);Z.tui.showSystem(O?`Agendamento "${O.name}" ativado.`:"Agendamento nao encontrado.");break}if(J==="disable"||J==="desativar"){if(!z[1]){Z.tui.showSystem("Uso: /agendar desativar <id ou nome>");break}let O=await o4(z[1]);Z.tui.showSystem(O?`Agendamento "${O.name}" desativado.`:"Agendamento nao encontrado.");break}if(J==="run"||J==="executar"){if(!z[1]){Z.tui.showSystem("Uso: /agendar executar <id ou nome>");break}Z.tui.showSystem(await i4(z[1]));break}if(J==="clear"||J==="limpar"){Z.tui.showSystem(await pQ());break}if(J==="detail"||J==="detalhe"||J==="info"){if(!z[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let O=gQ(z[1]);Z.tui.showSystem(O?b6(O):"Agendamento nao encontrado.");break}let X=z.join(" "),K=X.match(/"([^"]+)"/g);if(!K||K.length<2){Z.tui.showSystem(`Uso: /agendar "<mensagem>" "<horario>" [once|daily|weekly] [data/dia]
724
733
  Exemplos:
725
734
  /agendar "Reuniao" "14:00"
726
735
  /agendar "Standup" "09:00" daily
727
736
  /agendar "Review" "15:00" weekly sexta
728
- /agendar "Dentista" "10:00" once 15/04/2026`);break}let V=K[0].slice(1,-1),G=K[1].slice(1,-1),q=_7(G);if(!q){Z.tui.showSystem(`Horario invalido: "${G}". Use formato HH:MM ou HHh.`);break}let U=X.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),W="once",B;for(let M of U){let N=M.toLowerCase();if(N==="daily"||N==="diario")W="daily";else if(N==="weekly"||N==="semanal")W="weekly";else if(N==="once"||N==="uma-vez")W="once";else if(W==="weekly"){let F=v7(M);if(F)B=F}else if(W==="once"){let F=x7(M);if(F)B=F}}if(W==="once"&&!B){let M=new Date,[N,F]=q.split(":").map(Number),j=new Date(M);if(j.setHours(N,F,0,0),j<=M)j.setDate(j.getDate()+1);B=[String(j.getMonth()+1).padStart(2,"0"),String(j.getDate()).padStart(2,"0"),String(j.getFullYear())].join("/")}try{let M=await S7(V,W,q,"toast",V,B);Z.tui.showSystem(`Tarefa "${M.name}" agendada para ${K9(M).split(`
729
- `).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(M){Z.tui.showError(`Erro ao agendar: ${M instanceof Error?M.message:String(M)}`)}break}case"agendamentos":case"schedules":{let z=m8(J[0]==="all"||J[0]==="todos");Z.tui.showSystem(u8(z));break}case"entrada":case"income":{let z=parseFloat(J[0]);if(isNaN(z)||J.length<3){Z.tui.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let X=J[1],K=J.slice(2).join(" "),V=d8("entrada",z,X,K);if(!V.allowed){Z.tui.showError(V.blocked);break}let G=p8("entrada",z,X,K);c8("entrada",z,X);let q=l8(V);if(Z.tui.showSystem(`+ R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description}`),q)Z.tui.showSystem(q);break}case"saida":case"expense":{let z=parseFloat(J[0]);if(isNaN(z)||J.length<3){Z.tui.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let X=J[1],K=J.slice(2).join(" "),V=d8("saida",z,X,K);if(!V.allowed){Z.tui.showError(V.blocked);break}let G=p8("saida",z,X,K);c8("saida",z,X);let q=l8(V);if(Z.tui.showSystem(`- R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description}`),q)Z.tui.showSystem(q);break}case"finance":case"financas":case"balanco":{let z=J[0];if(z==="recent"||z==="recentes")Z.tui.showSystem(G9());else Z.tui.showSystem(h7()+`
737
+ /agendar "Dentista" "10:00" once 15/04/2026`);break}let G=K[0].slice(1,-1),V=K[1].slice(1,-1),U=r4(V);if(!U){Z.tui.showSystem(`Horario invalido: "${V}". Use formato HH:MM ou HHh.`);break}let q=X.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),H="once",B;for(let O of q){let M=O.toLowerCase();if(M==="daily"||M==="diario")H="daily";else if(M==="weekly"||M==="semanal")H="weekly";else if(M==="once"||M==="uma-vez")H="once";else if(H==="weekly"){let C=a4(O);if(C)B=C}else if(H==="once"){let C=n4(O);if(C)B=C}}if(H==="once"&&!B){let O=new Date,[M,C]=U.split(":").map(Number),F=new Date(O);if(F.setHours(M,C,0,0),F<=O)F.setDate(F.getDate()+1);B=[String(F.getMonth()+1).padStart(2,"0"),String(F.getDate()).padStart(2,"0"),String(F.getFullYear())].join("/")}try{let O=await d4(G,H,U,"toast",G,B);Z.tui.showSystem(`Tarefa "${O.name}" agendada para ${b6(O).split(`
738
+ `).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(O){Z.tui.showError(`Erro ao agendar: ${O instanceof Error?O.message:String(O)}`)}break}case"agendamentos":case"schedules":{let J=r2(z[0]==="all"||z[0]==="todos");Z.tui.showSystem(n2(J));break}case"entrada":case"income":{let J=parseFloat(z[0]);if(isNaN(J)||z.length<3){Z.tui.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let X=z[1],K=z.slice(2).join(" "),G=s2("entrada",J,X,K);if(!G.allowed){Z.tui.showError(G.blocked);break}let V=a2("entrada",J,X,K);t2("entrada",J,X);let U=e2(G);if(Z.tui.showSystem(`+ R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description}`),U)Z.tui.showSystem(U);break}case"saida":case"expense":{let J=parseFloat(z[0]);if(isNaN(J)||z.length<3){Z.tui.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let X=z[1],K=z.slice(2).join(" "),G=s2("saida",J,X,K);if(!G.allowed){Z.tui.showError(G.blocked);break}let V=a2("saida",J,X,K);t2("saida",J,X);let U=e2(G);if(Z.tui.showSystem(`- R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description}`),U)Z.tui.showSystem(U);break}case"finance":case"financas":case"balanco":{let J=z[0];if(J==="recent"||J==="recentes")Z.tui.showSystem(_6());else Z.tui.showSystem(t4()+`
730
739
 
731
- `+G9(5));break}case"decisions":case"decisoes":{let z=J.join(" ");if(z){let X=n0(z);Z.tui.showSystem(T1(X))}else Z.tui.showSystem(T1(p7()));break}case"investigar":case"investigate":case"investigacoes":{let z=J.join(" ");if(z){let{searchInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (i8(),L9));Z.tui.showSystem(K(X(z)))}else{let{listInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (i8(),L9));Z.tui.showSystem(K(X()))}break}case"email":case"rascunho":{if(!J.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
732
- Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let X=J[0],K=J.slice(1).join(" "),V=K.indexOf("|");if(V===-1){Z.tui.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
733
- Use | para separar assunto do corpo.`);break}let G=K.slice(0,V).trim(),q=K.slice(V+1).trim();if(!G||!q){Z.tui.showError("Assunto e corpo sao obrigatorios.");break}let U={to:X,subject:G,body:q};Z.tui.showSystem(P7(U)),Z.tui.disableInput();try{let W=await D7(U);Z.tui.showSystem(W)}catch(W){Z.tui.showError(`Email: ${W instanceof Error?W.message:String(W)}`)}Z.tui.enableInput();break}case"memo":case"anotar":case"note":{let z=J.join(" ");if(!z){let V=g8();Z.tui.showSystem(a0(V));break}let X=L7(z),K=X.tags.length>0?` [${X.tags.map((V)=>"#"+V).join(" ")}]`:"";Z.tui.showSystem(`Memo salvo${K} {${X.id}}`);break}case"memos":case"notas":{let z=J.join(" ");if(z){let X=j7(z);Z.tui.showSystem(a0(X))}else{let X=g8();Z.tui.showSystem(a0(X))}break}case"memotags":case"tags":{Z.tui.showSystem(g3());break}case"rmmemo":case"rmnota":{let z=J[0];if(!z){Z.tui.showError("Uso: /rmmemo <id>");break}if(h3(z))Z.tui.showSystem("Memo removido.");else Z.tui.showError(`Memo nao encontrado: ${z}`);break}case"material":case"mat":{let z=J.join(" ");if(!z){let U=w1(10);Z.tui.showSystem(A0(U));break}if(/^[a-z0-9]{6}$/.test(z)){let U=IY(z);if(U)Z.tui.showSystem(kY(U));else Z.tui.showError(`Material nao encontrado: ${z}`);break}let X=z.indexOf("|");if(X===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
734
- Ou peca a IA: "salva esse material sobre..."`);break}let K=z.slice(0,X).trim(),V=z.slice(X+1).trim();if(!K||!V){Z.tui.showError("Titulo e conteudo sao obrigatorios.");break}let G=e7(K,V),q=G.tags.length>0?` [${G.tags.map((U)=>"#"+U).join(" ")}]`:"";Z.tui.showSystem(`Material salvo: "${G.title}" (${G.category})${q} {${G.id}}`);break}case"materials":case"materiais":{let z=J.join(" ");if(z){let X=S1(z);Z.tui.showSystem(A0(X))}else{let X=w1();Z.tui.showSystem(A0(X))}break}case"matcats":case"categorias":{Z.tui.showSystem(bY());break}case"rmmat":case"rmmaterial":{let z=J[0];if(!z){Z.tui.showError("Uso: /rmmat <id>");break}if($5(z))Z.tui.showSystem("Material removido.");else Z.tui.showError(`Material nao encontrado: ${z}`);break}case"reflect":case"reflexao":case"aprender":{Z.tui.showSystem("Executando reflexao de uso..."),Z.tui.disableInput();try{let z=await x1();Z.tui.showSystem(z.summary)}catch(z){Z.tui.showError(`Reflexao falhou: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"indexar":case"index":case"reindex":{Z.tui.showSystem("Indexando memoria local...");let z=m5();Z.tui.showSystem(`Indexacao concluida: ${z.indexed} fonte(s) indexada(s), ${z.skipped} sem alteracao. Total: ${z.total} chunks.`);break}case"memoria":case"memory":{let z=J.join(" ");if(z){let X=u5(z);Z.tui.showSystem(p5(X))}else{let X=g5(),K=X.builtAt?new Date(X.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
740
+ `+_6(5));break}case"decisions":case"decisoes":{let J=z.join(" ");if(J){let X=s1(J);Z.tui.showSystem(y$(X))}else Z.tui.showSystem(y$(Y5()));break}case"investigar":case"investigate":case"investigacoes":{let J=z.join(" ");if(J){let{searchInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (Z8(),r6));Z.tui.showSystem(K(X(J)))}else{let{listInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (Z8(),r6));Z.tui.showSystem(K(X()))}break}case"email":case"rascunho":{if(!z.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
741
+ Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let X=z[0],K=z.slice(1).join(" "),G=K.indexOf("|");if(G===-1){Z.tui.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
742
+ Use | para separar assunto do corpo.`);break}let V=K.slice(0,G).trim(),U=K.slice(G+1).trim();if(!V||!U){Z.tui.showError("Assunto e corpo sao obrigatorios.");break}let q={to:X,subject:V,body:U};Z.tui.showSystem(g4(q)),Z.tui.disableInput();try{let H=await h4(q);Z.tui.showSystem(H)}catch(H){Z.tui.showError(`Email: ${H instanceof Error?H.message:String(H)}`)}Z.tui.enableInput();break}case"memo":case"anotar":case"note":{let J=z.join(" ");if(!J){let G=i2();Z.tui.showSystem(a1(G));break}let X=x4(J),K=X.tags.length>0?` [${X.tags.map((G)=>"#"+G).join(" ")}]`:"";Z.tui.showSystem(`Memo salvo${K} {${X.id}}`);break}case"memos":case"notas":{let J=z.join(" ");if(J){let X=v4(J);Z.tui.showSystem(a1(X))}else{let X=i2();Z.tui.showSystem(a1(X))}break}case"memotags":case"tags":{Z.tui.showSystem(fQ());break}case"rmmemo":case"rmnota":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmemo <id>");break}if(kQ(J))Z.tui.showSystem("Memo removido.");else Z.tui.showError(`Memo nao encontrado: ${J}`);break}case"material":case"mat":{let J=z.join(" ");if(!J){let q=v$(10);Z.tui.showSystem(S1(q));break}if(/^[a-z0-9]{6}$/.test(J)){let q=Fz(J);if(q)Z.tui.showSystem(Az(q));else Z.tui.showError(`Material nao encontrado: ${J}`);break}let X=J.indexOf("|");if(X===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
743
+ Ou peca a IA: "salva esse material sobre..."`);break}let K=J.slice(0,X).trim(),G=J.slice(X+1).trim();if(!K||!G){Z.tui.showError("Titulo e conteudo sao obrigatorios.");break}let V=W5(K,G),U=V.tags.length>0?` [${V.tags.map((q)=>"#"+q).join(" ")}]`:"";Z.tui.showSystem(`Material salvo: "${V.title}" (${V.category})${U} {${V.id}}`);break}case"materials":case"materiais":{let J=z.join(" ");if(J){let X=x$(J);Z.tui.showSystem(S1(X))}else{let X=v$();Z.tui.showSystem(S1(X))}break}case"matcats":case"categorias":{Z.tui.showSystem(Pz());break}case"rmmat":case"rmmaterial":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmat <id>");break}if(B5(J))Z.tui.showSystem("Material removido.");else Z.tui.showError(`Material nao encontrado: ${J}`);break}case"reflect":case"reflexao":case"aprender":{Z.tui.showSystem("Executando reflexao de uso..."),Z.tui.disableInput();try{let J=await p$();Z.tui.showSystem(J.summary)}catch(J){Z.tui.showError(`Reflexao falhou: ${J instanceof Error?J.message:String(J)}`)}Z.tui.enableInput();break}case"indexar":case"index":case"reindex":{Z.tui.showSystem("Indexando memoria local...");let J=$7();Z.tui.showSystem(`Indexacao concluida: ${J.indexed} fonte(s) indexada(s), ${J.skipped} sem alteracao. Total: ${J.total} chunks.`);break}case"memoria":case"memory":{let J=z.join(" ");if(J){let X=Z7(J);Z.tui.showSystem(Y7(X))}else{let X=e5(),K=X.builtAt?new Date(X.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
735
744
  Chunks: ${X.chunks}
736
745
  Fontes: ${X.sources}
737
- Ultima indexacao: ${K}`)}break}case"vault":{let z=J[0]?.toLowerCase();if(!z||z==="status")Z.tui.showSystem(T4(A4()));else if(z==="backup"){Z.tui.showSystem("Realizando backup...");let X=J.slice(1).join(" ")||void 0,K=await U1(X);Z.tui.showSystem(K)}else if(z==="sync"||z==="push"){Z.tui.showSystem("Sincronizando com remote...");let X=await S4();Z.tui.showSystem(X)}else if(z==="init"){let X=await I4();Z.tui.showSystem(X),O6(30),Z.tui.showSystem("Auto-backup ativado (a cada 30 minutos).")}else Z.tui.showError("Uso: /vault [status|backup|sync|init]");break}case"backup":{Z.tui.showSystem("Realizando backup...");let z=await U1();Z.tui.showSystem(z);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let z=await N5();switch(z.type){case"text":Z.tui.showSystem(`Clipboard (texto):
738
- ${z.text}`);break;case"image":Z.tui.showSystem(z.text);break;case"empty":Z.tui.showSystem("Clipboard vazio.");break;case"error":Z.tui.showError(z.text);break}break}case"tela":case"screen":{Z.tui.showSystem("Analisando tela...");let z=await O5();Z.tui.showSystem(z);break}case"ps1":{let z=J.join(" ");if(!z.trim()){Z.tui.showError("Uso: /ps1 <script powershell>");break}Z.tui.showSystem("Executando script...");let X=await e8(z),K=[];if(X.stdout.trim())K.push(X.stdout.trim());if(X.stderr.trim())K.push(`stderr: ${X.stderr.trim()}`);K.push(`(exit: ${X.exitCode}, ${X.duration}ms)`),Z.tui.showSystem(K.join(`
739
- `));break}case"projeto":case"project":{let z=J.join(" ");if(z){let X=Q5(z);if(X)y1(X.id),Z.tui.showSystem(G5(X));else if(z==="auto"){let K=H5(process.cwd());if(K)y1(K.id),Z.tui.showSystem(`Projeto detectado: ${G5(K)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${z}"`)}else{let X=I0();if(X)Z.tui.showSystem(G5(X));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(V5(b1()));break}case"sessao":case"session":{let z=J[0],X=I0();if(!X){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(z==="start"||z==="iniciar"){let K=J.slice(1).join(" "),V=J5(X.id,K);if(V)Z.tui.showSystem(`Sessao iniciada para "${X.name}" [${V.id}]`)}else if(z==="stop"||z==="parar"){let K=S0(X.id);if(K){let V=z5(K.id,J.slice(1).join(" "));if(V)Z.tui.showSystem(`Sessao encerrada: ${V.durationMinutes} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta.")}else{let K=S0(X.id);if(K){let V=Math.round((Date.now()-new Date(K.startedAt).getTime())/60000);Z.tui.showSystem(`Sessao aberta: ${V} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let z=I0();if(!z){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let X=J[0]||"today";Z.tui.showSystem("Gerando relatorio...");let K=await K5(z.id,X,"pt");if(K)Z.tui.showSystem(K.markdown);else Z.tui.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let z=J[0]||void 0,X=X5(z);Z.tui.showSystem(q5(X));break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let X={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[Q]||J[0],K=i7(X);Z.tui.showSystem(n7(K));break}case"person":case"pessoa":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /person <nome>");break}let X=e$(z);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${z}"`);break}Z.tui.showSystem(r7(X));break}case"addperson":case"addpessoa":case"novapessoa":{let z=J[0];if(!z||!["equipe","familia","contato"].includes(z)){Z.tui.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
740
- Ex: /addperson equipe Joao dev frontend`);break}let K=J.slice(1).join(" ");if(!K){Z.tui.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[V,...G]=K.split(","),q=G.join(",").trim()||void 0,U=o7(V.trim(),z,q);Z.tui.showSystem(`Adicionado: ${U.name} (${z}) [${U.id}]`);break}case"delegate":case"delegar":{let z=J[0];if(!z||J.length<2){Z.tui.showSystem(`Uso: /delegate <pessoa> <tarefa>
741
- Ex: /delegate Joao revisar relatorio`);break}let X=J.slice(1).join(" "),K=a7(z,X);if(!K){Z.tui.showError(`Pessoa nao encontrada: "${z}"`);break}Z.tui.showSystem(`Delegado para ${z}: "${X}" [${K.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let z=J[0],X=r0(z);Z.tui.showSystem(s7(X));break}case"followups":{let z=I1();Z.tui.showSystem(t7(z));break}case"dashboard":case"painel":{let z=await cZ(Z.config.dataDir);Z.tui.enterDashboardMode(z),process.stdin.once("data",()=>{if(Z.tui.getViewMode()==="dashboard")Z.tui.enterChatMode()});break}case"chat":{Z.tui.enterChatMode();break}case"task":case"tarefa":{let z=J.join(" ");if(!z){let q=t$();Z.tui.showSystem(i0(q));break}let X=P1(z),K=z.replace(/\b(para\s+(as\s+)?)?\d{1,2}\s*[h:]\s*\d{0,2}\b/gi,"").replace(/\b(em\s+\d+\s*(min|minutos?|h|horas?))\b/gi,"").replace(/\b(amanha|amanh\u00E3)\b/gi,"").replace(/\s{2,}/g," ").trim();if(!K)K=z;let V=R7(K,X||void 0),G=X?` \u2014 lembrete: ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";Z.tui.showSystem(`Tarefa criada: "${V.title}"${G} [${V.id}]`);break}case"tasks":case"tarefas":{let z=J[0]==="all"||J[0]==="todas",X=t$(z);Z.tui.showSystem(i0(X));break}case"done":case"feito":case"concluido":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /done <id ou parte do titulo>");break}let X=E7(z);if(X)Z.tui.showSystem(`Concluida: "${X.title}"`);else Z.tui.showError(`Tarefa nao encontrada: "${z}"`);break}case"rmtask":case"rmtarefa":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /rmtask <id ou parte do titulo>");break}if(k3(z))Z.tui.showSystem("Tarefa removida.");else Z.tui.showError(`Tarefa nao encontrada: "${z}"`);break}default:Z.tui.showError(`Unknown command: /${Q}. Try /help`)}}async function cZ($){let Z=[],Y=new Date().getHours(),Q=Y<12?"BOM DIA":Y<18?"BOA TARDE":"BOA NOITE",J=new Date().toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),z=t$(),X=z.filter((U)=>{if(!U.dueAt)return!0;let W=new Date(U.dueAt),B=new Date;return W.toDateString()===B.toDateString()});if(X.length>0||z.length>0){let U=X.slice(0,8).map((W)=>{let B=W.dueAt?new Date(W.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${B?`[${B}] `:""}${W.title}`});if(z.length>X.length)U.push(`... +${z.length-X.length} outras`);Z.push({id:"tasks",title:`${Q}! Tarefas (${X.length})`,content:U.length>0?U:["Nenhuma tarefa para hoje"]})}let K=I1();if(K.length>0){let U=K.slice(0,6).map((W)=>{let B=W.person.name||"Alguem",M=W.interaction.summary||"Follow-up pendente";return`${B}: ${M.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${K.length})`,content:U})}let G=r0().filter((U)=>U.status==="atrasado");if(G.length>0){let U=G.slice(0,5).map((W)=>{return`${e$(W.personId)?.name||"Alguem"}: ${W.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${G.length})`,content:U})}try{let W=(await f$()).split(`
742
- `).filter((M)=>M.trim()).slice(0,6);if(W.length===1&&(W[0].startsWith("Outlook nao disponivel")||W[0].startsWith("Outlook timeout")||W[0].startsWith("Outlook integration only")))Z.push({id:"calendar",title:"Agenda",content:[W[0]]}),x.debug("Calendar fallback in dashboard",{message:W[0]});else if(W.length>0)Z.push({id:"calendar",title:`Agenda (${W.length>1||W[0]!=="Nenhum evento hoje."?W.length:0})`,content:W})}catch(U){x.debug("Calendar unavailable for dashboard",{error:U}),Z.push({id:"calendar",title:"Agenda",content:["Erro ao acessar Outlook"]})}let q=U5();if(q){let U=q.split(`
743
- `).filter((W)=>W.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:U})}try{let W=(await L0(["finance","business","tech"],2)).split(`
744
- `).filter((B)=>B.trim()).slice(0,6);if(W.length>0)Z.push({id:"news",title:"Noticias",content:W})}catch(U){x.debug("News fetch failed for dashboard",{error:U})}if(Z.length===0)Z.push({id:"greeting",title:Q,content:[J,"","Nenhuma tarefa ou evento pendente.","Use /ajuda para ver comandos dispon\xEDveis."]});return{panels:Z,columns:Math.min(2,Z.length),gap:1}}function SW($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let Y=Math.floor(Z/60000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;let Q=Math.floor(Y/60);if(Q<24)return`${Q}h ago`;let J=Math.floor(Q/24);if(J>365)return`${Math.floor(J/365)}y ago`;return`${J}d ago`}async function FX($,Z,Y,Q,J,z,X,K,V,G){let q=new _Z(Y.model),U=new yZ(Y.model,Z.session.name,L6(Q.auth),Y.dataDir),W="default",B=X;KX(Y.dataDir,U,Z);let M=null;try{M=await H4(Y.dataDir),U.setTimeContext(M)}catch(T){x.debug("Time context init failed, using productivity mode",{error:T}),U.setPersonaMode("productivity")}if(dz(Q.auth,{onRefreshed:(T)=>{if(Q.auth=T,"updateToken"in $)$.updateToken(T.token)},onRefreshFailed:(T)=>{U.showError(`Auto-refresh: ${T}`)}}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(T,b,$$)=>{if(T==="edit_file"&&b.old_text&&b.new_text){let y$=mJ(String(b.old_text),String(b.new_text));for(let H$ of y$)U.showSystem(H$)}let J$=gJ(T,b),v=await U.promptApproval(J$);if(U._approveAllRequested)$.setAutoApproveAll?.(!0),U._approveAllRequested=!1;return v});for(let T of Z.messages)if(T.role==="user")U.addUserMessage(T.content);else U.addAssistantMessage(T.content);let N=null;async function F(T){if(T.startsWith("/")){await OX(T,p);return}if(Y.maxSessionCost>0){let y=q.totals.costCents;if(y>=Y.maxSessionCost){U.showError(`Budget exceeded (~$${(y/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(y>=Y.maxSessionCost*0.8)U.showSystem(`Budget: ${Math.round(y/Y.maxSessionCost*100)}% used`)}let{text:b,images:$$}=Dz(T),{text:J$,files:v}=Pz(b),y$=J$;if(v.length>0)y$=`${v.map((C4)=>`<file name="${C4.name}" path="${C4.path}" size="${C4.size}">
745
- ${C4.content}
746
+ Ultima indexacao: ${K}`)}break}case"vault":{let J=z[0]?.toLowerCase();if(!J||J==="status")Z.tui.showSystem(d8(p8()));else if(J==="backup"){Z.tui.showSystem("Realizando backup...");let X=z.slice(1).join(" ")||void 0,K=await O$(X);Z.tui.showSystem(K)}else if(J==="sync"||J==="push"){Z.tui.showSystem("Sincronizando com remote...");let X=await l8();Z.tui.showSystem(X)}else if(J==="init"){let X=await c8();Z.tui.showSystem(X),UY(30),Z.tui.showSystem("Auto-backup ativado (a cada 30 minutos).")}else Z.tui.showError("Uso: /vault [status|backup|sync|init]");break}case"backup":{Z.tui.showSystem("Realizando backup...");let J=await O$();Z.tui.showSystem(J);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let J=await k5();switch(J.type){case"text":Z.tui.showSystem(`Clipboard (texto):
747
+ ${J.text}`);break;case"image":Z.tui.showSystem(J.text);break;case"empty":Z.tui.showSystem("Clipboard vazio.");break;case"error":Z.tui.showError(J.text);break}break}case"tela":case"screen":{Z.tui.showSystem("Analisando tela...");let J=await f5();Z.tui.showSystem(J);break}case"ps1":{let J=z.join(" ");if(!J.trim()){Z.tui.showError("Uso: /ps1 <script powershell>");break}Z.tui.showSystem("Executando script...");let X=await K8(J),K=[];if(X.stdout.trim())K.push(X.stdout.trim());if(X.stderr.trim())K.push(`stderr: ${X.stderr.trim()}`);K.push(`(exit: ${X.exitCode}, ${X.duration}ms)`),Z.tui.showSystem(K.join(`
748
+ `));break}case"projeto":case"project":{let J=z.join(" ");if(J){let X=M5(J);if(X)m$(X.id),Z.tui.showSystem(j5(X));else if(J==="auto"){let K=D5(process.cwd());if(K)m$(K.id),Z.tui.showSystem(`Projeto detectado: ${j5(K)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${J}"`)}else{let X=k1();if(X)Z.tui.showSystem(j5(X));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(L5(g$()));break}case"sessao":case"session":{let J=z[0],X=k1();if(!X){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(J==="start"||J==="iniciar"){let K=z.slice(1).join(" "),G=C5(X.id,K);if(G)Z.tui.showSystem(`Sessao iniciada para "${X.name}" [${G.id}]`)}else if(J==="stop"||J==="parar"){let K=f1(X.id);if(K){let G=E5(K.id,z.slice(1).join(" "));if(G)Z.tui.showSystem(`Sessao encerrada: ${G.durationMinutes} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta.")}else{let K=f1(X.id);if(K){let G=Math.round((Date.now()-new Date(K.startedAt).getTime())/60000);Z.tui.showSystem(`Sessao aberta: ${G} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let J=k1();if(!J){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let X=z[0]||"today";Z.tui.showSystem("Gerando relatorio...");let K=await F5(J.id,X,"pt");if(K)Z.tui.showSystem(K.markdown);else Z.tui.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let J=z[0]||void 0,X=R5(J);Z.tui.showSystem(A5(X));break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let X={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[Q]||z[0],K=K5(X);Z.tui.showSystem(V5(K));break}case"person":case"pessoa":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /person <nome>");break}let X=z1(J);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${J}"`);break}Z.tui.showSystem(U5(X));break}case"addperson":case"addpessoa":case"novapessoa":{let J=z[0];if(!J||!["equipe","familia","contato"].includes(J)){Z.tui.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
749
+ Ex: /addperson equipe Joao dev frontend`);break}let K=z.slice(1).join(" ");if(!K){Z.tui.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[G,...V]=K.split(","),U=V.join(",").trim()||void 0,q=X5(G.trim(),J,U);Z.tui.showSystem(`Adicionado: ${q.name} (${J}) [${q.id}]`);break}case"delegate":case"delegar":{let J=z[0];if(!J||z.length<2){Z.tui.showSystem(`Uso: /delegate <pessoa> <tarefa>
750
+ Ex: /delegate Joao revisar relatorio`);break}let X=z.slice(1).join(" "),K=G5(J,X);if(!K){Z.tui.showError(`Pessoa nao encontrada: "${J}"`);break}Z.tui.showSystem(`Delegado para ${J}: "${X}" [${K.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let J=z[0],X=t1(J);Z.tui.showSystem(q5(X));break}case"followups":{let J=_$();Z.tui.showSystem(H5(J));break}case"dashboard":case"painel":{let J=await C9(Z.config.dataDir);Z.tui.enterDashboardMode(J),process.stdin.once("data",()=>{if(Z.tui.getViewMode()==="dashboard")Z.tui.enterChatMode()});break}case"chat":{Z.tui.enterChatMode();break}case"task":case"tarefa":{let J=z.join(" ");if(!J){let U=Q1();Z.tui.showSystem(n1(U));break}let X=f$(J),K=J.replace(/\b(para\s+(as\s+)?)?\d{1,2}\s*[h:]\s*\d{0,2}\b/gi,"").replace(/\b(em\s+\d+\s*(min|minutos?|h|horas?))\b/gi,"").replace(/\b(amanha|amanh\u00E3)\b/gi,"").replace(/\s{2,}/g," ").trim();if(!K)K=J;let G=y4(K,X||void 0),V=X?` \u2014 lembrete: ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";Z.tui.showSystem(`Tarefa criada: "${G.title}"${V} [${G.id}]`);break}case"tasks":case"tarefas":{let J=z[0]==="all"||z[0]==="todas",X=Q1(J);Z.tui.showSystem(n1(X));break}case"done":case"feito":case"concluido":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /done <id ou parte do titulo>");break}let X=_4(J);if(X)Z.tui.showSystem(`Concluida: "${X.title}"`);else Z.tui.showError(`Tarefa nao encontrada: "${J}"`);break}case"rmtask":case"rmtarefa":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /rmtask <id ou parte do titulo>");break}if(AQ(J))Z.tui.showSystem("Tarefa removida.");else Z.tui.showError(`Tarefa nao encontrada: "${J}"`);break}default:Z.tui.showError(`Unknown command: /${Q}. Try /help`)}}async function C9($){let Z=[],Y=new Date().getHours(),Q=Y<12?"BOM DIA":Y<18?"BOA TARDE":"BOA NOITE",z=new Date().toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),J=Q1(),X=J.filter((q)=>{if(!q.dueAt)return!0;let H=new Date(q.dueAt),B=new Date;return H.toDateString()===B.toDateString()});if(X.length>0||J.length>0){let q=X.slice(0,8).map((H)=>{let B=H.dueAt?new Date(H.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${B?`[${B}] `:""}${H.title}`});if(J.length>X.length)q.push(`... +${J.length-X.length} outras`);Z.push({id:"tasks",title:`${Q}! Tarefas (${X.length})`,content:q.length>0?q:["Nenhuma tarefa para hoje"]})}let K=_$();if(K.length>0){let q=K.slice(0,6).map((H)=>{let B=H.person.name||"Alguem",O=H.interaction.summary||"Follow-up pendente";return`${B}: ${O.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${K.length})`,content:q})}let V=t1().filter((q)=>q.status==="atrasado");if(V.length>0){let q=V.slice(0,5).map((H)=>{return`${z1(H.personId)?.name||"Alguem"}: ${H.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${V.length})`,content:q})}try{let H=(await l0()).split(`
751
+ `).filter((O)=>O.trim()).slice(0,6);if(H.length===1&&(H[0].startsWith("Outlook nao disponivel")||H[0].startsWith("Outlook timeout")||H[0].startsWith("Outlook integration only")))Z.push({id:"calendar",title:"Agenda",content:[H[0]]}),m.debug("Calendar fallback in dashboard",{message:H[0]});else if(H.length>0)Z.push({id:"calendar",title:`Agenda (${H.length>1||H[0]!=="Nenhum evento hoje."?H.length:0})`,content:H})}catch(q){m.debug("Calendar unavailable for dashboard",{error:q}),Z.push({id:"calendar",title:"Agenda",content:["Erro ao acessar Outlook"]})}let U=P5();if(U){let q=U.split(`
752
+ `).filter((H)=>H.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:q})}try{let H=(await P1(["finance","business","tech"],2)).split(`
753
+ `).filter((B)=>B.trim()).slice(0,6);if(H.length>0)Z.push({id:"news",title:"Noticias",content:H})}catch(q){m.debug("News fetch failed for dashboard",{error:q})}if(Z.length===0)Z.push({id:"greeting",title:Q,content:[z,"","Nenhuma tarefa ou evento pendente.","Use /ajuda para ver comandos dispon\xEDveis."]});return{panels:Z,columns:Math.min(2,Z.length),gap:1}}function UO($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let Y=Math.floor(Z/60000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;let Q=Math.floor(Y/60);if(Q<24)return`${Q}h ago`;let z=Math.floor(Q/24);if(z>365)return`${Math.floor(z/365)}y ago`;return`${z}d ago`}async function EK($,Z,Y,Q,z,J,X,K,G,V){let U=new K9(Y.model),q=new X9(Y.model,Z.session.name,NY(Q.auth),Y.dataDir),H="default",B=X;KK(Y.dataDir,q,Z);let O=null;try{O=await L8(Y.dataDir),q.setTimeContext(O)}catch(D){m.debug("Time context init failed, using productivity mode",{error:D}),q.setPersonaMode("productivity")}if(pX(Q.auth,{onRefreshed:(D)=>{if(Q.auth=D,"updateToken"in $)$.updateToken(D.token)},onRefreshFailed:(D)=>{q.showError(`Auto-refresh: ${D}`)}}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(D,f,g)=>{if(D==="edit_file"&&f.old_text&&f.new_text){let G0=a3(String(f.old_text),String(f.new_text));for(let c of G0)q.showSystem(c)}let Y0=n3(D,f),_=await q.promptApproval(Y0);if(q._approveAllRequested)$.setAutoApproveAll?.(!0),q._approveAllRequested=!1;return _});for(let D of Z.messages)if(D.role==="user")q.addUserMessage(D.content);else q.addAssistantMessage(D.content);let M=null;async function C(D){if(D.startsWith("/")){await CK(D,k);return}if(Y.maxSessionCost>0){let x=U.totals.costCents;if(x>=Y.maxSessionCost){q.showError(`Budget exceeded (~$${(x/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(x>=Y.maxSessionCost*0.8)q.showSystem(`Budget: ${Math.round(x/Y.maxSessionCost*100)}% used`)}let{text:f,images:g}=jX(D),{text:Y0,files:_}=AX(f),G0=Y0;if(_.length>0)G0=`${_.map((f8)=>`<file name="${f8.name}" path="${f8.path}" size="${f8.size}">
754
+ ${f8.content}
746
755
  </file>`).join(`
747
756
 
748
757
  `)}
749
758
 
750
- ${J$}`;let H$={role:"user",content:y$,images:$$.length>0?$$.map((y)=>({mediaType:y.mediaType,base64:y.base64})):void 0,files:v.length>0?v:void 0,timestamp:Date.now()};Z.addMessage(H$);let m$=[];if($$.length>0)m$.push(`${$$.length} image${$$.length>1?"s":""}`);if(v.length>0)m$.push(`${v.length} file${v.length>1?"s":""}`);let v0=m$.length>0?`${J$} (${m$.join(", ")})`:J$;U.addUserMessage(v0),U.disableInput(),U.startStream();let G0="",q0=[],K2={},m1=0,M4=0;N=new AbortController;try{for await(let y of $.chat(Z.messages,B,K)){if(N.signal.aborted)break;switch(y.type){case"text":U.appendStream(y.text),G0+=y.text;break;case"tool_call":U.flushStream(),U.showToolCall(y.name,y.input),K2=y.input;break;case"tool_result":U.showToolResult(y.name,y.result),q0.push({id:y.id,name:y.name,input:K2,result:y.result}),K2={},U.resetStreamBuffer();break;case"tool_blocked":U.showError(y.reason);break;case"usage":m1+=y.inputTokens,M4+=y.outputTokens;break;case"error":U.showError(y.error);break;case"done":break}}}catch(y){if(!N.signal.aborted)U.showError(y instanceof Error?y.message:String(y))}N=null,U.endStream();let lZ={inputTokens:m1,outputTokens:M4},RX=q.add(lZ);if(m1>0||M4>0)U.showUsage(q.formatUsage(lZ)),U.updateSessionCost(`~$${(q.totals.costCents/100).toFixed(4)}`);let EX={role:"assistant",content:G0,toolCalls:q0.length>0?q0:void 0,usage:m1>0?{inputTokens:m1,outputTokens:M4,costCents:RX.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(EX),Z.trimHistory(Y.maxHistory),U.enableInput()}function j(){Z.saveLastSession(),w3(),vz(),pz(),a3(),F2(),gZ(),Gz().catch(()=>{}),x1().catch(()=>{}),U.stop(),process.exit(0)}let p={tui:U,sessions:Z,claude:$,config:Y,auth:Q,skills:J,tracker:q,plugins:V,systemPrompt:z,activeSystemPrompt:B,setActiveSystemPrompt:(T)=>{B=T,p.activeSystemPrompt=T},currentPersona:W,setCurrentPersona:(T)=>{W=T,p.currentPersona=T},timeContext:M,setTimeContext:(T)=>{M=T,p.timeContext=T},handleSubmit:F,cleanup:j};process.on("SIGINT",j),process.on("SIGTERM",j),U.start({onSubmit:F,onCancel:()=>{N?.abort(),U.endStream(),U.showSystem("Cancelled."),U.enableInput()},onExit:j});let n=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(U.showSystem(`smolerclaw v${u1()} \u2014 the micro AI assistant.
759
+ ${Y0}`;let c={role:"user",content:G0,images:g.length>0?g.map((x)=>({mediaType:x.mediaType,base64:x.base64})):void 0,files:_.length>0?_:void 0,timestamp:Date.now()};Z.addMessage(c);let V0=[];if(g.length>0)V0.push(`${g.length} image${g.length>1?"s":""}`);if(_.length>0)V0.push(`${_.length} file${_.length>1?"s":""}`);let h0=V0.length>0?`${Y0} (${V0.join(", ")})`:Y0;q.addUserMessage(h0),q.disableInput(),q.startStream();let j0="",M0=[],k7={},r$=0,k8=0;M=new AbortController;try{for await(let x of $.chat(Z.messages,B,K)){if(M.signal.aborted)break;switch(x.type){case"text":q.appendStream(x.text),j0+=x.text;break;case"tool_call":q.flushStream(),q.showToolCall(x.name,x.input),k7=x.input;break;case"tool_result":q.showToolResult(x.name,x.result),M0.push({id:x.id,name:x.name,input:k7,result:x.result}),k7={},q.resetStreamBuffer();break;case"tool_blocked":q.showError(x.reason);break;case"usage":r$+=x.inputTokens,k8+=x.outputTokens;break;case"error":q.showError(x.error);break;case"done":break}}}catch(x){if(!M.signal.aborted)q.showError(x instanceof Error?x.message:String(x))}M=null,q.endStream();let v9={inputTokens:r$,outputTokens:k8},eK=U.add(v9);if(r$>0||k8>0)q.showUsage(U.formatUsage(v9)),q.updateSessionCost(`~$${(U.totals.costCents/100).toFixed(4)}`);let $G={role:"assistant",content:j0,toolCalls:M0.length>0?M0:void 0,usage:r$>0?{inputTokens:r$,outputTokens:k8,costCents:eK.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage($G),Z.trimHistory(Y.maxHistory),q.enableInput()}function F(){Z.saveLastSession(),jQ(),_X(),uX(),uQ(),d7(),H9(),F3().catch(()=>{}),p$().catch(()=>{}),q.stop(),process.exit(0)}let k={tui:q,sessions:Z,claude:$,config:Y,auth:Q,skills:z,tracker:U,plugins:G,systemPrompt:J,activeSystemPrompt:B,setActiveSystemPrompt:(D)=>{B=D,k.activeSystemPrompt=D},currentPersona:H,setCurrentPersona:(D)=>{H=D,k.currentPersona=D},timeContext:O,setTimeContext:(D)=>{O=D,k.timeContext=D},handleSubmit:C,cleanup:F};process.on("SIGINT",F),process.on("SIGTERM",F),q.start({onSubmit:C,onCancel:()=>{M?.abort(),q.endStream(),q.showSystem("Cancelled."),q.enableInput()},onExit:F});let d=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(q.showSystem(`smolerclaw v${a$()} \u2014 the micro AI assistant.
751
760
  Criado por Aldeia Viva - Impactando Vida (aldeia-viva.com.br)
752
- ${n}
753
- Type /ajuda for commands.`),nz(Y.dataDir))try{let T=await cZ(Y.dataDir);if(T.panels.length>0){U.enterDashboardMode(T);let b=()=>{U.enterChatMode(),U.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",b)};setTimeout(()=>{if(U.getViewMode()==="dashboard")U.enterChatMode()},30000),process.stdin.once("data",()=>{if(U.getViewMode()==="dashboard")U.enterChatMode()})}else{let b=await sz();U.showSystem(b)}rz()}catch(T){x.debug("Morning briefing failed at startup",{error:T})}if(G)await F(G)}async function wW(){let $=iZ(process.argv.slice(2));if($.help)aZ(),process.exit(0);if($.version)console.log(`smolerclaw v${u1()}`),process.exit(0);let Z=R6();if($.model)Z.model=x4($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=E2()}catch(W){console.error("smolerclaw:",W instanceof Error?W.message:W),process.exit(1)}let Q={auth:Y},J=pJ(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:z,skills:X,systemPrompt:K,activeSystemPrompt:V,enableTools:G,plugins:q}=await qz(Z,$.session,$.noTools),U=!process.stdin.isTTY;if($.print||U)await Uz(J,z,K,G,$.prompt,U),process.exit(0);await FX(J,z,Z,Q,X,K,V,G,q,$.prompt)}wW().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
761
+ ${d}
762
+ Type /ajuda for commands.`),rX(Y.dataDir))try{let D=await C9(Y.dataDir);if(D.panels.length>0){q.enterDashboardMode(D);let f=()=>{q.enterChatMode(),q.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",f)};setTimeout(()=>{if(q.getViewMode()==="dashboard")q.enterChatMode()},30000),process.stdin.once("data",()=>{if(q.getViewMode()==="dashboard")q.enterChatMode()})}else{let f=await aX();q.showSystem(f)}nX()}catch(D){m.debug("Morning briefing failed at startup",{error:D})}if(V)await C(V)}import{exec as lO}from"child_process";var E9=($,Z,Y)=>{return(Q,z)=>{let J=-1;return X(0);async function X(K){if(K<=J)throw Error("next() called multiple times");J=K;let G,V=!1,U;if($[K])U=$[K][0][0],Q.req.routeIndex=K;else U=K===$.length&&z||void 0;if(U)try{G=await U(Q,()=>X(K+1))}catch(q){if(q instanceof Error&&Z)Q.error=q,G=await Z(q,Q),V=!0;else throw q}else if(Q.finalized===!1&&Y)G=await Y(Q);if(G&&(Q.finalized===!1||V))Q.res=G;return Q}}};var RK=Symbol();var FK=async($,Z=Object.create(null))=>{let{all:Y=!1,dot:Q=!1}=Z,J=($ instanceof F7?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return qO($,{all:Y,dot:Q});return{}};async function qO($,Z){let Y=await $.formData();if(Y)return HO(Y,Z);return{}}function HO($,Z){let Y=Object.create(null);if($.forEach((Q,z)=>{if(!(Z.all||z.endsWith("[]")))Y[z]=Q;else WO(Y,z,Q)}),Z.dot)Object.entries(Y).forEach(([Q,z])=>{if(Q.includes("."))BO(Y,Q,z),delete Y[Q]});return Y}var WO=($,Z,Y)=>{if($[Z]!==void 0)if(Array.isArray($[Z]))$[Z].push(Y);else $[Z]=[$[Z],Y];else if(!Z.endsWith("[]"))$[Z]=Y;else $[Z]=[Y]},BO=($,Z,Y)=>{if(/(?:^|\.)__proto__\./.test(Z))return;let Q=$,z=Z.split(".");z.forEach((J,X)=>{if(X===z.length-1)Q[J]=Y;else{if(!Q[J]||typeof Q[J]!=="object"||Array.isArray(Q[J])||Q[J]instanceof File)Q[J]=Object.create(null);Q=Q[J]}})};var F9=($)=>{let Z=$.split("/");if(Z[0]==="")Z.shift();return Z},LK=($)=>{let{groups:Z,path:Y}=OO($),Q=F9(Y);return NO(Q,Z)},OO=($)=>{let Z=[];return $=$.replace(/\{[^}]+\}/g,(Y,Q)=>{let z=`@${Q}`;return Z.push([z,Y]),z}),{groups:Z,path:$}},NO=($,Z)=>{for(let Y=Z.length-1;Y>=0;Y--){let[Q]=Z[Y];for(let z=$.length-1;z>=0;z--)if($[z].includes(Q)){$[z]=$[z].replace(Q,Z[Y][1]);break}}return $},L7={},jK=($,Z)=>{if($==="*")return"*";let Y=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let Q=`${$}#${Z}`;if(!L7[Q])if(Y[2])L7[Q]=Z&&Z[0]!==":"&&Z[0]!=="*"?[Q,Y[1],new RegExp(`^${Y[2]}(?=/${Z})`)]:[$,Y[1],new RegExp(`^${Y[2]}$`)];else L7[Q]=[$,Y[1],!0];return L7[Q]}return null},j7=($,Z)=>{try{return Z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return Z(Y)}catch{return Y}})}},L9=($)=>j7($,decodeURI),j9=($)=>{let Z=$.url,Y=Z.indexOf("/",Z.indexOf(":")+4),Q=Y;for(;Q<Z.length;Q++){let z=Z.charCodeAt(Q);if(z===37){let J=Z.indexOf("?",Q),X=Z.indexOf("#",Q),K=J===-1?X===-1?void 0:X:X===-1?J:Math.min(J,X),G=Z.slice(Y,K);return L9(G.includes("%25")?G.replace(/%25/g,"%2525"):G)}else if(z===63||z===35)break}return Z.slice(Y,Q)};var AK=($)=>{let Z=j9($);return Z.length>1&&Z.at(-1)==="/"?Z.slice(0,-1):Z},U$=($,Z,...Y)=>{if(Y.length)Z=U$(Z,...Y);return`${$?.[0]==="/"?"":"/"}${$}${Z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${Z?.[0]==="/"?Z.slice(1):Z}`}`},A7=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let Z=$.split("/"),Y=[],Q="";return Z.forEach((z)=>{if(z!==""&&!/\:/.test(z))Q+="/"+z;else if(/\:/.test(z))if(/\?/.test(z)){if(Y.length===0&&Q==="")Y.push("/");else Y.push(Q);let J=z.replace("?","");Q+="/"+J,Y.push(Q)}else Q+="/"+z}),Y.filter((z,J,X)=>X.indexOf(z)===J)},R9=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?j7($,A9):$},PK=($,Z,Y)=>{let Q;if(!Y&&Z&&!/[%+]/.test(Z)){let X=$.indexOf("?",8);if(X===-1)return;if(!$.startsWith(Z,X+1))X=$.indexOf(`&${Z}`,X+1);while(X!==-1){let K=$.charCodeAt(X+Z.length+1);if(K===61){let G=X+Z.length+2,V=$.indexOf("&",G);return R9($.slice(G,V===-1?void 0:V))}else if(K==38||isNaN(K))return"";X=$.indexOf(`&${Z}`,X+1)}if(Q=/[%+]/.test($),!Q)return}let z={};Q??=/[%+]/.test($);let J=$.indexOf("?",8);while(J!==-1){let X=$.indexOf("&",J+1),K=$.indexOf("=",J);if(K>X&&X!==-1)K=-1;let G=$.slice(J+1,K===-1?X===-1?void 0:X:K);if(Q)G=R9(G);if(J=X,G==="")continue;let V;if(K===-1)V="";else if(V=$.slice(K+1,X===-1?void 0:X),Q)V=R9(V);if(Y){if(!(z[G]&&Array.isArray(z[G])))z[G]=[];z[G].push(V)}else z[G]??=V}return Z?z[Z]:z},DK=PK,TK=($,Z)=>{return PK($,Z,!0)},A9=decodeURIComponent;var IK=($)=>j7($,A9),F7=class{raw;#$;#Z;routeIndex=0;path;bodyCache={};constructor($,Z="/",Y=[[]]){this.raw=$,this.path=Z,this.#Z=Y,this.#$={}}param($){return $?this.#Y($):this.#J()}#Y($){let Z=this.#Z[0][this.routeIndex][1][$],Y=this.#z(Z);return Y&&/\%/.test(Y)?IK(Y):Y}#J(){let $={},Z=Object.keys(this.#Z[0][this.routeIndex][1]);for(let Y of Z){let Q=this.#z(this.#Z[0][this.routeIndex][1][Y]);if(Q!==void 0)$[Y]=/\%/.test(Q)?IK(Q):Q}return $}#z($){return this.#Z[1]?this.#Z[1][$]:$}query($){return DK(this.url,$)}queries($){return TK(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let Z={};return this.raw.headers.forEach((Y,Q)=>{Z[Q]=Y}),Z}async parseBody($){return FK(this,$)}#Q=($)=>{let{bodyCache:Z,raw:Y}=this,Q=Z[$];if(Q)return Q;let z=Object.keys(Z)[0];if(z)return Z[z].then((J)=>{if(z==="json")J=JSON.stringify(J);return new Response(J)[$]()});return Z[$]=Y[$]()};json(){return this.#Q("text").then(($)=>JSON.parse($))}text(){return this.#Q("text")}arrayBuffer(){return this.#Q("arrayBuffer")}blob(){return this.#Q("blob")}formData(){return this.#Q("formData")}addValidatedData($,Z){this.#$[$]=Z}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[RK](){return this.#Z}get matchedRoutes(){return this.#Z[0].map(([[,$]])=>$)}get routePath(){return this.#Z[0].map(([[,$]])=>$)[this.routeIndex].path}};var SK={Stringify:1,BeforeStream:2,Stream:3},wK=($,Z)=>{let Y=new String($);return Y.isEscaped=!0,Y.callbacks=Z,Y};var P9=async($,Z,Y,Q,z)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let J=$.callbacks;if(!J?.length)return Promise.resolve($);if(z)z[0]+=$;else z=[$];let X=Promise.all(J.map((K)=>K({phase:Z,buffer:z,context:Q}))).then((K)=>Promise.all(K.filter(Boolean).map((G)=>P9(G,Z,!1,Q,z))).then(()=>z[0]));if(Y)return wK(await X,J);else return X};var MO="text/plain; charset=UTF-8",D9=($,Z)=>{return{"Content-Type":$,...Z}},P8=($,Z)=>new Response($,Z),kK=class{#$;#Z;env={};#Y;finalized=!1;error;#J;#z;#Q;#U;#G;#V;#K;#q;#H;constructor($,Z){if(this.#$=$,Z)this.#z=Z.executionCtx,this.env=Z.env,this.#V=Z.notFoundHandler,this.#H=Z.path,this.#q=Z.matchResult}get req(){return this.#Z??=new F7(this.#$,this.#H,this.#q),this.#Z}get event(){if(this.#z&&"respondWith"in this.#z)return this.#z;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#z)return this.#z;else throw Error("This context has no ExecutionContext")}get res(){return this.#Q||=P8(null,{headers:this.#K??=new Headers})}set res($){if(this.#Q&&$){$=P8($.body,$);for(let[Z,Y]of this.#Q.headers.entries()){if(Z==="content-type")continue;if(Z==="set-cookie"){let Q=this.#Q.headers.getSetCookie();$.headers.delete("set-cookie");for(let z of Q)$.headers.append("set-cookie",z)}else $.headers.set(Z,Y)}}this.#Q=$,this.finalized=!0}render=(...$)=>{return this.#G??=(Z)=>this.html(Z),this.#G(...$)};setLayout=($)=>this.#U=$;getLayout=()=>this.#U;setRenderer=($)=>{this.#G=$};header=($,Z,Y)=>{if(this.finalized)this.#Q=P8(this.#Q.body,this.#Q);let Q=this.#Q?this.#Q.headers:this.#K??=new Headers;if(Z===void 0)Q.delete($);else if(Y?.append)Q.append($,Z);else Q.set($,Z)};status=($)=>{this.#J=$};set=($,Z)=>{this.#Y??=new Map,this.#Y.set($,Z)};get=($)=>{return this.#Y?this.#Y.get($):void 0};get var(){if(!this.#Y)return{};return Object.fromEntries(this.#Y)}#X($,Z,Y){let Q=this.#Q?new Headers(this.#Q.headers):this.#K??new Headers;if(typeof Z==="object"&&"headers"in Z){let J=Z.headers instanceof Headers?Z.headers:new Headers(Z.headers);for(let[X,K]of J)if(X.toLowerCase()==="set-cookie")Q.append(X,K);else Q.set(X,K)}if(Y)for(let[J,X]of Object.entries(Y))if(typeof X==="string")Q.set(J,X);else{Q.delete(J);for(let K of X)Q.append(J,K)}let z=typeof Z==="number"?Z:Z?.status??this.#J;return P8($,{status:z,headers:Q})}newResponse=(...$)=>this.#X(...$);body=($,Z,Y)=>this.#X($,Z,Y);text=($,Z,Y)=>{return!this.#K&&!this.#J&&!Z&&!Y&&!this.finalized?new Response($):this.#X($,Z,D9(MO,Y))};json=($,Z,Y)=>{return this.#X(JSON.stringify($),Z,D9("application/json",Y))};html=($,Z,Y)=>{let Q=(z)=>this.#X(z,Z,D9("text/html; charset=UTF-8",Y));return typeof $==="object"?P9($,SK.Stringify,!1,{}).then(Q):Q($)};redirect=($,Z)=>{let Y=String($);return this.header("Location",!/[^\x00-\xFF]/.test(Y)?Y:encodeURI(Y)),this.newResponse(null,Z??302)};notFound=()=>{return this.#V??=()=>P8(),this.#V(this)}};var v="ALL",fK="all",bK=["get","post","put","delete","options","patch"],P7="Can not add a route since the matcher is already built.",D7=class extends Error{};var T9="__COMPOSED_HANDLER";var CO=($)=>{return $.text("404 Not Found",404)},yK=($,Z)=>{if("getResponse"in $){let Y=$.getResponse();return Z.newResponse(Y.body,Y)}return console.error($),Z.text("Internal Server Error",500)},_K=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...bK,fK].forEach((J)=>{this[J]=(X,...K)=>{if(typeof X==="string")this.#$=X;else this.#J(J,this.#$,X);return K.forEach((G)=>{this.#J(J,this.#$,G)}),this}}),this.on=(J,X,...K)=>{for(let G of[X].flat()){this.#$=G;for(let V of[J].flat())K.map((U)=>{this.#J(V.toUpperCase(),this.#$,U)})}return this},this.use=(J,...X)=>{if(typeof J==="string")this.#$=J;else this.#$="*",X.unshift(J);return X.forEach((K)=>{this.#J(v,this.#$,K)}),this};let{strict:Q,...z}=Z;Object.assign(this,z),this.getPath=Q??!0?Z.getPath??j9:AK}#Z(){let Z=new $({router:this.router,getPath:this.getPath});return Z.errorHandler=this.errorHandler,Z.#Y=this.#Y,Z.routes=this.routes,Z}#Y=CO;errorHandler=yK;route(Z,Y){let Q=this.basePath(Z);return Y.routes.map((z)=>{let J;if(Y.errorHandler===yK)J=z.handler;else J=async(X,K)=>(await E9([],Y.errorHandler)(X,()=>z.handler(X,K))).res,J[T9]=z.handler;Q.#J(z.method,z.path,J)}),this}basePath(Z){let Y=this.#Z();return Y._basePath=U$(this._basePath,Z),Y}onError=(Z)=>{return this.errorHandler=Z,this};notFound=(Z)=>{return this.#Y=Z,this};mount(Z,Y,Q){let z,J;if(Q)if(typeof Q==="function")J=Q;else if(J=Q.optionHandler,Q.replaceRequest===!1)z=(G)=>G;else z=Q.replaceRequest;let X=J?(G)=>{let V=J(G);return Array.isArray(V)?V:[V]}:(G)=>{let V=void 0;try{V=G.executionCtx}catch{}return[G.env,V]};z||=(()=>{let G=U$(this._basePath,Z),V=G==="/"?0:G.length;return(U)=>{let q=new URL(U.url);return q.pathname=q.pathname.slice(V)||"/",new Request(q,U)}})();let K=async(G,V)=>{let U=await Y(z(G.req.raw),...X(G));if(U)return U;await V()};return this.#J(v,U$(Z,"*"),K),this}#J(Z,Y,Q){Z=Z.toUpperCase(),Y=U$(this._basePath,Y);let z={basePath:this._basePath,path:Y,method:Z,handler:Q};this.router.add(Z,Y,[Q,z]),this.routes.push(z)}#z(Z,Y){if(Z instanceof Error)return this.errorHandler(Z,Y);throw Z}#Q(Z,Y,Q,z){if(z==="HEAD")return(async()=>new Response(null,await this.#Q(Z,Y,Q,"GET")))();let J=this.getPath(Z,{env:Q}),X=this.router.match(z,J),K=new kK(Z,{path:J,matchResult:X,env:Q,executionCtx:Y,notFoundHandler:this.#Y});if(X[0].length===1){let V;try{V=X[0][0][0][0](K,async()=>{K.res=await this.#Y(K)})}catch(U){return this.#z(U,K)}return V instanceof Promise?V.then((U)=>U||(K.finalized?K.res:this.#Y(K))).catch((U)=>this.#z(U,K)):V??this.#Y(K)}let G=E9(X[0],this.errorHandler,this.#Y);return(async()=>{try{let V=await G(K);if(!V.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return V.res}catch(V){return this.#z(V,K)}})()}fetch=(Z,...Y)=>{return this.#Q(Z,Y[1],Y[0],Z.method)};request=(Z,Y,Q,z)=>{if(Z instanceof Request)return this.fetch(Y?new Request(Z,Y):Z,Q,z);return Z=Z.toString(),this.fetch(new Request(/^https?:\/\//.test(Z)?Z:`http://localhost${U$("/",Z)}`,Y),Q,z)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#Q(Z.request,Z,void 0,Z.request.method))})}};var D8=[];function T7($,Z){let Y=this.buildAllMatchers(),Q=(z,J)=>{let X=Y[z]||Y[v],K=X[2][J];if(K)return K;let G=J.match(X[0]);if(!G)return[[],D8];let V=G.indexOf("",1);return[X[1][V],G]};return this.match=Q,Q($,Z)}var I7="[^/]+",T8=".*",I8="(?:|/.*)",q$=Symbol(),EO=new Set(".\\+*[^]$()");function RO($,Z){if($.length===1)return Z.length===1?$<Z?-1:1:-1;if(Z.length===1)return 1;if($===T8||$===I8)return 1;else if(Z===T8||Z===I8)return-1;if($===I7)return 1;else if(Z===I7)return-1;return $.length===Z.length?$<Z?-1:1:Z.length-$.length}var xK=class ${#$;#Z;#Y=Object.create(null);insert(Z,Y,Q,z,J){if(Z.length===0){if(this.#$!==void 0)throw q$;if(J)return;this.#$=Y;return}let[X,...K]=Z,G=X==="*"?K.length===0?["","",T8]:["","",I7]:X==="/*"?["","",I8]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),V;if(G){let U=G[1],q=G[2]||I7;if(U&&G[2]){if(q===".*")throw q$;if(q=q.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(q))throw q$}if(V=this.#Y[q],!V){if(Object.keys(this.#Y).some((H)=>H!==T8&&H!==I8))throw q$;if(J)return;if(V=this.#Y[q]=new $,U!=="")V.#Z=z.varIndex++}if(!J&&U!=="")Q.push([U,V.#Z])}else if(V=this.#Y[X],!V){if(Object.keys(this.#Y).some((U)=>U.length>1&&U!==T8&&U!==I8))throw q$;if(J)return;V=this.#Y[X]=new $}V.insert(K,Y,Q,z,J)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(RO).map((Q)=>{let z=this.#Y[Q];return(typeof z.#Z==="number"?`(${Q})@${z.#Z}`:EO.has(Q)?`\\${Q}`:Q)+z.buildRegExpStr()});if(typeof this.#$==="number")Y.unshift(`#${this.#$}`);if(Y.length===0)return"";if(Y.length===1)return Y[0];return"(?:"+Y.join("|")+")"}};var vK=class{#$={varIndex:0};#Z=new xK;insert($,Z,Y){let Q=[],z=[];for(let X=0;;){let K=!1;if($=$.replace(/\{[^}]+\}/g,(G)=>{let V=`@\\${X}`;return z[X]=[V,G],X++,K=!0,V}),!K)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let X=z.length-1;X>=0;X--){let[K]=z[X];for(let G=J.length-1;G>=0;G--)if(J[G].indexOf(K)!==-1){J[G]=J[G].replace(K,z[X][1]);break}}return this.#Z.insert(J,Z,Q,this.#$,Y),Q}buildRegExp(){let $=this.#Z.buildRegExpStr();if($==="")return[/^$/,[],[]];let Z=0,Y=[],Q=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(z,J,X)=>{if(J!==void 0)return Y[++Z]=Number(J),"$()";if(X!==void 0)return Q[Number(X)]=++Z,"";return""}),[new RegExp(`^${$}`),Y,Q]}};var FO=[/^$/,[],Object.create(null)],hK=Object.create(null);function gK($){return hK[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function LO(){hK=Object.create(null)}function jO($){let Z=new vK,Y=[];if($.length===0)return FO;let Q=$.map((V)=>[!/\*|\/:/.test(V[0]),...V]).sort(([V,U],[q,H])=>V?1:q?-1:U.length-H.length),z=Object.create(null);for(let V=0,U=-1,q=Q.length;V<q;V++){let[H,B,O]=Q[V];if(H)z[B]=[O.map(([C])=>[C,Object.create(null)]),D8];else U++;let M;try{M=Z.insert(B,U,H)}catch(C){throw C===q$?new D7(B):C}if(H)continue;Y[U]=O.map(([C,F])=>{let k=Object.create(null);F-=1;for(;F>=0;F--){let[d,D]=M[F];k[d]=D}return[C,k]})}let[J,X,K]=Z.buildRegExp();for(let V=0,U=Y.length;V<U;V++)for(let q=0,H=Y[V].length;q<H;q++){let B=Y[V][q]?.[1];if(!B)continue;let O=Object.keys(B);for(let M=0,C=O.length;M<C;M++)B[O[M]]=K[B[O[M]]]}let G=[];for(let V in X)G[V]=Y[X[V]];return[J,G,z]}function i$($,Z){if(!$)return;for(let Y of Object.keys($).sort((Q,z)=>z.length-Q.length))if(gK(Y).test(Z))return[...$[Y]];return}var S7=class{name="RegExpRouter";#$;#Z;constructor(){this.#$={[v]:Object.create(null)},this.#Z={[v]:Object.create(null)}}add($,Z,Y){let Q=this.#$,z=this.#Z;if(!Q||!z)throw Error(P7);if(!Q[$])[Q,z].forEach((K)=>{K[$]=Object.create(null),Object.keys(K[v]).forEach((G)=>{K[$][G]=[...K[v][G]]})});if(Z==="/*")Z="*";let J=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let K=gK(Z);if($===v)Object.keys(Q).forEach((G)=>{Q[G][Z]||=i$(Q[G],Z)||i$(Q[v],Z)||[]});else Q[$][Z]||=i$(Q[$],Z)||i$(Q[v],Z)||[];Object.keys(Q).forEach((G)=>{if($===v||$===G)Object.keys(Q[G]).forEach((V)=>{K.test(V)&&Q[G][V].push([Y,J])})}),Object.keys(z).forEach((G)=>{if($===v||$===G)Object.keys(z[G]).forEach((V)=>K.test(V)&&z[G][V].push([Y,J]))});return}let X=A7(Z)||[Z];for(let K=0,G=X.length;K<G;K++){let V=X[K];Object.keys(z).forEach((U)=>{if($===v||$===U)z[U][V]||=[...i$(Q[U],V)||i$(Q[v],V)||[]],z[U][V].push([Y,J-G+K+1])})}}match=T7;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#Z).concat(Object.keys(this.#$)).forEach((Z)=>{$[Z]||=this.#Y(Z)}),this.#$=this.#Z=void 0,LO(),$}#Y($){let Z=[],Y=$===v;if([this.#$,this.#Z].forEach((Q)=>{let z=Q[$]?Object.keys(Q[$]).map((J)=>[J,Q[$][J]]):[];if(z.length!==0)Y||=!0,Z.push(...z);else if($!==v)Z.push(...Object.keys(Q[v]).map((J)=>[J,Q[v][J]]))}),!Y)return null;else return jO(Z)}};var AO=class{name="PreparedRegExpRouter";#$;#Z;constructor($,Z){this.#$=$,this.#Z=Z}#Y($,Z){let Y=this.#$[$];Y[1].forEach((Q)=>Q&&Q.push(Z)),Object.values(Y[2]).forEach((Q)=>Q[0].push(Z))}#J($,Z,Y,Q,z){let J=this.#$[$];if(!z)J[2][Z][0].push([Y,{}]);else Q.forEach((X)=>{if(typeof X==="number")J[1][X].push([Y,z]);else J[2][X||Z][0].push([Y,z])})}add($,Z,Y){if(!this.#$[$]){let z=this.#$[v],J={};for(let X in z[2])J[X]=[z[2][X][0].slice(),D8];this.#$[$]=[z[0],z[1].map((X)=>Array.isArray(X)?X.slice():0),J]}if(Z==="/*"||Z==="*"){let z=[Y,{}];if($===v)for(let J in this.#$)this.#Y(J,z);else this.#Y($,z);return}let Q=this.#Z[Z];if(!Q)throw Error(`Path ${Z} is not registered`);for(let[z,J]of Q)if($===v)for(let X in this.#$)this.#J(X,Z,Y,z,J);else this.#J($,Z,Y,z,J)}buildAllMatchers(){return this.#$}match=T7};var I9=class{name="SmartRouter";#$=[];#Z=[];constructor($){this.#$=$.routers}add($,Z,Y){if(!this.#Z)throw Error(P7);this.#Z.push([$,Z,Y])}match($,Z){if(!this.#Z)throw Error("Fatal error");let Y=this.#$,Q=this.#Z,z=Y.length,J=0,X;for(;J<z;J++){let K=Y[J];try{for(let G=0,V=Q.length;G<V;G++)K.add(...Q[G]);X=K.match($,Z)}catch(G){if(G instanceof D7)continue;throw G}this.match=K.match.bind(K),this.#$=[K],this.#Z=void 0;break}if(J===z)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,X}get activeRouter(){if(this.#Z||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var S8=Object.create(null),PO=($)=>{for(let Z in $)return!0;return!1},mK=class ${#$;#Z;#Y;#J=0;#z=S8;constructor(Z,Y,Q){if(this.#Z=Q||Object.create(null),this.#$=[],Z&&Y){let z=Object.create(null);z[Z]={handler:Y,possibleKeys:[],score:0},this.#$=[z]}this.#Y=[]}insert(Z,Y,Q){this.#J=++this.#J;let z=this,J=LK(Y),X=[];for(let K=0,G=J.length;K<G;K++){let V=J[K],U=J[K+1],q=jK(V,U),H=Array.isArray(q)?q[0]:V;if(H in z.#Z){if(z=z.#Z[H],q)X.push(q[1]);continue}if(z.#Z[H]=new $,q)z.#Y.push(q),X.push(q[1]);z=z.#Z[H]}return z.#$.push({[Z]:{handler:Q,possibleKeys:X.filter((K,G,V)=>V.indexOf(K)===G),score:this.#J}}),z}#Q(Z,Y,Q,z,J){for(let X=0,K=Y.#$.length;X<K;X++){let G=Y.#$[X],V=G[Q]||G[v],U={};if(V!==void 0){if(V.params=Object.create(null),Z.push(V),z!==S8||J&&J!==S8)for(let q=0,H=V.possibleKeys.length;q<H;q++){let B=V.possibleKeys[q],O=U[V.score];V.params[B]=J?.[B]&&!O?J[B]:z[B]??J?.[B],U[V.score]=!0}}}}search(Z,Y){let Q=[];this.#z=S8;let J=[this],X=F9(Y),K=[],G=X.length,V=null;for(let U=0;U<G;U++){let q=X[U],H=U===G-1,B=[];for(let M=0,C=J.length;M<C;M++){let F=J[M],k=F.#Z[q];if(k)if(k.#z=F.#z,H){if(k.#Z["*"])this.#Q(Q,k.#Z["*"],Z,F.#z);this.#Q(Q,k,Z,F.#z)}else B.push(k);for(let d=0,D=F.#Y.length;d<D;d++){let f=F.#Y[d],g=F.#z===S8?{}:{...F.#z};if(f==="*"){let V0=F.#Z["*"];if(V0)this.#Q(Q,V0,Z,F.#z),V0.#z=g,B.push(V0);continue}let[Y0,_,G0]=f;if(!q&&!(G0 instanceof RegExp))continue;let c=F.#Z[Y0];if(G0 instanceof RegExp){if(V===null){V=Array(G);let j0=Y[0]==="/"?1:0;for(let M0=0;M0<G;M0++)V[M0]=j0,j0+=X[M0].length+1}let V0=Y.substring(V[U]),h0=G0.exec(V0);if(h0){if(g[_]=h0[0],this.#Q(Q,c,Z,F.#z,g),PO(c.#Z)){c.#z=g;let j0=h0[0].match(/\//)?.length??0;(K[j0]||=[]).push(c)}continue}}if(G0===!0||G0.test(q))if(g[_]=q,H){if(this.#Q(Q,c,Z,g,F.#z),c.#Z["*"])this.#Q(Q,c.#Z["*"],Z,g,F.#z)}else c.#z=g,B.push(c)}}let O=K.shift();J=O?B.concat(O):B}if(Q.length>1)Q.sort((U,q)=>{return U.score-q.score});return[Q.map(({handler:U,params:q})=>[U,q])]}};var S9=class{name="TrieRouter";#$;constructor(){this.#$=new mK}add($,Z,Y){let Q=A7(Z);if(Q){for(let z=0,J=Q.length;z<J;z++)this.#$.insert($,Q[z],Y);return}this.#$.insert($,Z,Y)}match($,Z){return this.#$.search($,Z)}};var w9=class extends _K{constructor($={}){super($);this.router=$.router??new I9({routers:[new S7,new S9]})}};import{stat as wO}from"fs/promises";import{join as kO}from"path";var uK=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;var k9=($,Z=TO)=>{let Y=/\.([a-zA-Z0-9]+?)$/,Q=$.match(Y);if(!Q)return;let z=Z[Q[1].toLowerCase()];if(z&&z.startsWith("text"))z+="; charset=utf-8";return z};var DO={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},TO=DO;var pK=(...$)=>{let Z=$.filter((z)=>z!=="").join("/");Z=Z.replace(/(?<=\/)\/+/g,"");let Y=Z.split("/"),Q=[];for(let z of Y)if(z===".."&&Q.length>0&&Q.at(-1)!=="..")Q.pop();else if(z!==".")Q.push(z);return Q.join("/")||"."};var dK={br:".br",zstd:".zst",gzip:".gz"},IO=Object.keys(dK),SO="index.html",cK=($)=>{let Z=$.root??"./",Y=$.path,Q=$.join??pK;return async(z,J)=>{if(z.finalized)return J();let X;if($.path)X=$.path;else try{if(X=L9(z.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(X))throw Error()}catch{return await $.onNotFound?.(z.req.path,z),J()}let K=Q(Z,!Y&&$.rewriteRequestPath?$.rewriteRequestPath(X):X);if($.isDir&&await $.isDir(K))K=Q(K,SO);let G=$.getContent,V=await G(K,z);if(V instanceof Response)return z.newResponse(V.body,V);if(V){let U=$.mimes&&k9(K,$.mimes)||k9(K);if(z.header("Content-Type",U||"application/octet-stream"),$.precompressed&&(!U||uK.test(U))){let q=new Set(z.req.header("Accept-Encoding")?.split(",").map((H)=>H.trim()));for(let H of IO){if(!q.has(H))continue;let B=await G(K+dK[H],z);if(B){V=B,z.header("Content-Encoding",H),z.header("Vary","Accept-Encoding",{append:!0});break}}}return await $.onFound?.(K,z),z.body(V)}await $.onNotFound?.(K,z),await J();return}};var f9=($)=>{return async function(Y,Q){return cK({...$,getContent:async(X)=>{let K=Bun.file(X);return await K.exists()?K:null},join:kO,isDir:async(X)=>{let K;try{K=(await wO(X)).isDirectory()}catch{}return K}})(Y,Q)}};var b9="x-hono-disable-ssg",$k=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[b9]:"true"}})}catch{return null}})();var{write:_k}=Bun;var yO=class{#$;constructor($){this.#$=$,this.raw=$.raw,this.url=$.url?new URL($.url):null,this.protocol=$.protocol??null}send($,Z){this.#$.send($,Z??{})}raw;binaryType="arraybuffer";get readyState(){return this.#$.readyState}url;protocol;close($,Z){this.#$.close($,Z)}};var lK=($)=>{return(...Z)=>{if(typeof Z[0]==="function"){let[Y,Q]=Z;return async function(J,X){let K=await Y(J),G=await $(J,K,Q);if(G)return G;await X()}}else{let[Y,Q,z]=Z;return(async()=>{let J=await $(Y,Q,z);if(!J)throw Error("Failed to upgrade WebSocket");return J})()}}};var w7=($)=>("server"in $.env)?$.env.server:$.env;var _O=lK(($,Z)=>{let Y=w7($);if(!Y)throw TypeError("env has to include the 2nd argument of fetch.");if(Y.upgrade($.req.raw,{data:{events:Z,url:new URL($.req.url),protocol:$.req.url}}))return new Response(null);return});var oK=($)=>{let Y={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...$},Q=((J)=>{if(typeof J==="string")if(J==="*"){if(Y.credentials)return(X)=>X||null;return()=>J}else return(X)=>J===X?X:null;else if(typeof J==="function")return J;else return(X)=>J.includes(X)?X:null})(Y.origin),z=((J)=>{if(typeof J==="function")return J;else if(Array.isArray(J))return()=>J;else return()=>[]})(Y.allowMethods);return async function(X,K){function G(U,q){X.res.headers.set(U,q)}let V=await Q(X.req.header("origin")||"",X);if(V)G("Access-Control-Allow-Origin",V);if(Y.credentials)G("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)G("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(X.req.method==="OPTIONS"){if(Y.origin!=="*"||Y.credentials)G("Vary","Origin");if(Y.maxAge!=null)G("Access-Control-Max-Age",Y.maxAge.toString());let U=await z(X.req.header("origin")||"",X);if(U.length)G("Access-Control-Allow-Methods",U.join(","));let q=Y.allowHeaders;if(!q?.length){let H=X.req.header("Access-Control-Request-Headers");if(H)q=H.split(/\s*,\s*/)}if(q?.length)G("Access-Control-Allow-Headers",q.join(",")),X.res.headers.append("Vary","Access-Control-Request-Headers");return X.res.headers.delete("Content-Length"),X.res.headers.delete("Content-Type"),new Response(null,{headers:X.res.headers,status:204,statusText:"No Content"})}if(await K(),Y.origin!=="*"||Y.credentials)X.header("Vary","Origin",{append:!0})}};function xO(){let{process:$,Deno:Z}=globalThis;return!(typeof Z?.noColor==="boolean"?Z.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}async function iK(){let{navigator:$}=globalThis,Z="cloudflare:workers";return!($!==void 0&&$.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!xO())}var vO=($)=>{let[Z,Y]=[",","."];return $.map((z)=>z.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Z)).join(Y)},hO=($)=>{let Z=Date.now()-$;return vO([Z<1000?Z+"ms":Math.round(Z/1000)+"s"])},gO=async($)=>{if(await iK())switch($/100|0){case 5:return`\x1B[31m${$}\x1B[0m`;case 4:return`\x1B[33m${$}\x1B[0m`;case 3:return`\x1B[36m${$}\x1B[0m`;case 2:return`\x1B[32m${$}\x1B[0m`}return`${$}`};async function rK($,Z,Y,Q,z=0,J){let X=Z==="<--"?`${Z} ${Y} ${Q}`:`${Z} ${Y} ${Q} ${await gO(z)} ${J}`;$(X)}var nK=($=console.log)=>{return async function(Y,Q){let{method:z,url:J}=Y.req,X=J.slice(J.indexOf("/",8));await rK($,"<--",z,X);let K=Date.now();await Q(),await rK($,"-->",z,X,Y.res.status,hO(K))}};u0();class y9{provider;systemPrompt;enableTools;sessionManager;currentSessionName=null;messages=[];constructor($){if(this.provider=$.provider,this.systemPrompt=$.systemPrompt,this.enableTools=$.enableTools,this.sessionManager=$.sessionManager,$.onApprovalRequired&&this.provider.setApprovalCallback)this.provider.setApprovalCallback($.onApprovalRequired)}getSessions(){return this.sessionManager.listAll().map(($)=>({id:$.name,name:$.name,messageCount:$.messageCount,created:$.created,updated:$.updated,isActive:$.name===this.currentSessionName}))}loadSession($){let Z=this.sessionManager.getSession($);if(!Z)return[];return this.currentSessionName=$,this.messages=[...Z.messages],this.sessionManager.switchTo($),this.messages.map((Y)=>this.toUIMessage(Y))}resumeSession($){let Z=this.sessionManager.getSession($);if(!Z)return null;return this.currentSessionName=$,this.messages=[...Z.messages],this.sessionManager.switchTo($),{id:Z.name,name:Z.name,messageCount:Z.messages.length,created:Z.created,updated:Z.updated,isActive:!0}}newSession($){let Z=$||`chat-${Date.now()}`,Y=this.currentSessionName;this.currentSessionName=Z,this.messages=[];let Q=this.sessionManager.createSession(Z);return this.sessionManager.switchTo(Z),t.emit("session:changed",{previousSession:Y||void 0,currentSession:Z,timestamp:Date.now()}),{id:Q.name,name:Q.name,messageCount:Q.messages.length,created:Q.created,updated:Q.updated,isActive:!0}}deleteSessionById($){if(this.sessionManager.delete($),this.currentSessionName===$)this.currentSessionName=null,this.messages=[]}async*chat($){let Z=`msg_${Date.now()}`,Y={role:"user",content:$.message,images:$.images,timestamp:Date.now()};if(this.messages.push(Y),this.currentSessionName)this.sessionManager.addMessageTo(this.currentSessionName,Y);yield{type:"message_start",messageId:Z};let Q="",z=[],J=0,X=0;try{for await(let K of this.provider.chat(this.messages,this.systemPrompt,this.enableTools))switch(K.type){case"text":Q+=K.text,yield{type:"text",messageId:Z,data:K.text};break;case"tool_call":z.push({id:K.id,name:K.name,input:K.input,status:"running"}),yield{type:"tool_call",messageId:Z,data:{id:K.id,name:K.name,input:K.input}};break;case"tool_result":let G=z.find((U)=>U.id===K.id);if(G)G.result=K.result,G.status="complete";yield{type:"tool_result",messageId:Z,data:{id:K.id,name:K.name,result:K.result}};break;case"tool_blocked":let V=z.find((U)=>U.id===K.id);if(V)V.status="rejected";yield{type:"tool_blocked",messageId:Z,data:{id:K.id,name:K.name,reason:K.reason}};break;case"usage":J=K.inputTokens,X=K.outputTokens,yield{type:"usage",messageId:Z,data:{inputTokens:J,outputTokens:X}};break;case"done":{let U={role:"assistant",content:Q,toolCalls:z.map((q)=>({id:q.id,name:q.name,input:q.input,result:q.result||""})),usage:{inputTokens:J,outputTokens:X,costCents:this.calculateCost(J,X)},timestamp:Date.now()};if(this.messages.push(U),this.currentSessionName)this.sessionManager.addMessageTo(this.currentSessionName,U);yield{type:"done",messageId:Z};break}case"error":yield{type:"error",messageId:Z,data:K.error};break}}catch(K){yield{type:"error",messageId:Z,data:K instanceof Error?K.message:String(K)}}}calculateCost($,Z){let Y=$/1e6*300,Q=Z/1e6*1500;return Math.round((Y+Q)*100)/100}toUIMessage($){return{id:`msg_${$.timestamp}`,role:$.role,content:$.content,timestamp:$.timestamp,status:"complete",toolCalls:$.toolCalls?.map((Z)=>({id:Z.id,name:Z.name,input:Z.input,result:Z.result,status:"complete"})),usage:$.usage}}getMessages(){return this.messages.map(($)=>this.toUIMessage($))}clearMessages(){this.messages=[]}setSystemPrompt($){this.systemPrompt=$}setEnableTools($){this.enableTools=$}}var mO={theme:"system",fontSize:"medium",showToolCalls:!0,showCosts:!0,autoScroll:!0,enableSounds:!1};function w8($){let Z=new w9,Y=new Map;Z.use("*",nK()),Z.use("*",oK()),Z.use("/static/*",f9({root:"./src/ui/web"})),Z.get("/",(K)=>{return K.html(uO(K3()))}),Z.get("/api/health",(K)=>K.json({status:"ok"}));function Q(K,G){let V=new y9({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,onApprovalRequired:async(B,O,M)=>{return J(K,{type:"tool_approval_required",payload:{toolCallId:`tool_${Date.now()}`,name:B,input:O,riskLevel:M}}),!0}}),U={chatService:V,settings:{...mO}};Y.set(G,U);let q=$.sessionManager.getCurrentName(),H=V.resumeSession(q)||V.newSession();return J(K,{type:"connected",payload:{sessionId:H.id}}),X(K,V,U.settings),U}async function z(K,G,V,U){switch(U.type){case"chat":{let q=`msg_${Date.now()}`;J(K,{type:"message_start",payload:{messageId:q}});for await(let H of G.chat(U.payload))switch(H.type){case"text":J(K,{type:"text_delta",payload:{messageId:q,text:H.data}});break;case"tool_call":let B=H.data;J(K,{type:"tool_call",payload:{messageId:q,id:B.id,name:B.name,input:B.input,status:"running"}});break;case"tool_result":let O=H.data;J(K,{type:"tool_result",payload:{messageId:q,toolCallId:O.id,result:O.result}});break;case"tool_blocked":let M=H.data;J(K,{type:"tool_blocked",payload:{messageId:q,toolCallId:M.id,reason:M.reason}});break;case"usage":let C=H.data;J(K,{type:"usage",payload:{messageId:q,...C}});break;case"done":J(K,{type:"message_complete",payload:{messageId:q}});break;case"error":J(K,{type:"error",payload:{error:H.data}});break}break}case"new_session":{let q=G.newSession(U.payload?.name);J(K,{type:"connected",payload:{sessionId:q.id}}),X(K,G,V);break}case"load_session":{G.loadSession(U.payload.sessionId),X(K,G,V);break}case"delete_session":{G.deleteSessionById(U.payload.sessionId),J(K,{type:"sessions_updated",payload:G.getSessions()});break}case"update_settings":{Object.assign(V,U.payload),X(K,G,V);break}}}function J(K,G){K.send(JSON.stringify(G))}function X(K,G,V){let U=G.getSessions(),q=U.find((O)=>O.isActive)||null,H=G.getMessages(),B={currentSession:q,sessions:U,messages:H,isStreaming:!1,model:"claude-sonnet-4-20250514",systemPrompt:$.systemPrompt,totalCostCents:H.reduce((O,M)=>O+(M.usage?.costCents||0),0),settings:V};J(K,{type:"state",payload:B})}return{app:Z,start:()=>{console.log(`
763
+ ${S("ui.running_at",{url:`http://localhost:${$.port}`})}
764
+ `);let K=new Map;return Bun.serve({port:$.port,fetch(G,V){if(G.headers.get("upgrade")==="websocket"){if(V.upgrade(G))return;return new Response("WebSocket upgrade failed",{status:400})}return Z.fetch(G,V)},websocket:{open(G){let V=`client_${Date.now()}_${Math.random().toString(36).slice(2)}`,U=Q(G,V);K.set(G,{clientId:V,client:U})},async message(G,V){let U=K.get(G);if(!U)return;try{let q=JSON.parse(V.toString());await z(G,U.client.chatService,U.client.settings,q)}catch(q){J(G,{type:"error",payload:{error:q instanceof Error?q.message:"Unknown error"}})}},close(G){let V=K.get(G);if(V)Y.delete(V.clientId),K.delete(G)}}})}}}function uO($){let Z=(Y)=>$[Y]||Y;return`<!DOCTYPE html>
765
+ <html lang="en">
766
+ <head>
767
+ <meta charset="UTF-8">
768
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
769
+ <title>smolerclaw</title>
770
+ <style>
771
+ :root {
772
+ --bg-primary: #0d1117;
773
+ --bg-secondary: #161b22;
774
+ --bg-tertiary: #21262d;
775
+ --border-color: #30363d;
776
+ --text-primary: #e6edf3;
777
+ --text-secondary: #8b949e;
778
+ --accent: #e5484d;
779
+ --accent-hover: #ff6b6b;
780
+ --success: #3fb950;
781
+ --warning: #d29922;
782
+ --error: #f85149;
783
+ --user-bg: #c93c37;
784
+ --assistant-bg: #21262d;
785
+ --code-bg: #161b22;
786
+ --scrollbar-track: #21262d;
787
+ --scrollbar-thumb: #484f58;
788
+ --font-mono: 'SF Mono', 'Cascadia Code', 'Fira Code', Consolas, monospace;
789
+ --font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
790
+ --radius: 12px;
791
+ --radius-sm: 8px;
792
+ --shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
793
+ }
794
+
795
+ [data-theme="light"] {
796
+ --bg-primary: #ffffff;
797
+ --bg-secondary: #f6f8fa;
798
+ --bg-tertiary: #eaeef2;
799
+ --border-color: #d0d7de;
800
+ --text-primary: #1f2328;
801
+ --text-secondary: #656d76;
802
+ --user-bg: #cf2e2e;
803
+ --assistant-bg: #f6f8fa;
804
+ --code-bg: #f6f8fa;
805
+ --scrollbar-track: #f6f8fa;
806
+ --scrollbar-thumb: #d0d7de;
807
+ }
808
+
809
+ * {
810
+ margin: 0;
811
+ padding: 0;
812
+ box-sizing: border-box;
813
+ }
814
+
815
+ html, body {
816
+ height: 100%;
817
+ font-family: var(--font-sans);
818
+ background: var(--bg-primary);
819
+ color: var(--text-primary);
820
+ }
821
+
822
+ .app {
823
+ display: flex;
824
+ height: 100vh;
825
+ overflow: hidden;
826
+ }
827
+
828
+ /* Sidebar */
829
+ .sidebar {
830
+ width: 280px;
831
+ background: var(--bg-secondary);
832
+ border-right: 1px solid var(--border-color);
833
+ display: flex;
834
+ flex-direction: column;
835
+ flex-shrink: 0;
836
+ }
837
+
838
+ .sidebar-header {
839
+ padding: 20px;
840
+ border-bottom: 1px solid var(--border-color);
841
+ }
842
+
843
+ .logo {
844
+ display: flex;
845
+ align-items: center;
846
+ gap: 12px;
847
+ font-size: 18px;
848
+ font-weight: 600;
849
+ }
850
+
851
+ .logo-icon {
852
+ width: 32px;
853
+ height: 32px;
854
+ background: linear-gradient(135deg, var(--accent), #f97316);
855
+ border-radius: var(--radius-sm);
856
+ display: flex;
857
+ align-items: center;
858
+ justify-content: center;
859
+ font-size: 20px;
860
+ }
861
+
862
+ .new-chat-btn {
863
+ width: 100%;
864
+ margin-top: 16px;
865
+ padding: 12px 16px;
866
+ background: var(--accent);
867
+ color: white;
868
+ border: none;
869
+ border-radius: var(--radius-sm);
870
+ font-size: 14px;
871
+ font-weight: 500;
872
+ cursor: pointer;
873
+ transition: background 0.2s;
874
+ }
875
+
876
+ .new-chat-btn:hover {
877
+ background: var(--accent-hover);
878
+ }
879
+
880
+ .sessions-list {
881
+ flex: 1;
882
+ overflow-y: auto;
883
+ padding: 12px;
884
+ }
885
+
886
+ .session-item {
887
+ padding: 12px 16px;
888
+ border-radius: var(--radius-sm);
889
+ cursor: pointer;
890
+ margin-bottom: 4px;
891
+ transition: background 0.2s;
892
+ }
893
+
894
+ .session-item:hover {
895
+ background: var(--bg-tertiary);
896
+ }
897
+
898
+ .session-item.active {
899
+ background: var(--bg-tertiary);
900
+ border: 1px solid var(--border-color);
901
+ }
902
+
903
+ .session-name {
904
+ font-size: 14px;
905
+ font-weight: 500;
906
+ margin-bottom: 4px;
907
+ white-space: nowrap;
908
+ overflow: hidden;
909
+ text-overflow: ellipsis;
910
+ }
911
+
912
+ .session-meta {
913
+ font-size: 12px;
914
+ color: var(--text-secondary);
915
+ }
916
+
917
+ .sidebar-footer {
918
+ padding: 16px;
919
+ border-top: 1px solid var(--border-color);
920
+ }
921
+
922
+ .settings-btn {
923
+ width: 100%;
924
+ padding: 10px 16px;
925
+ background: transparent;
926
+ color: var(--text-secondary);
927
+ border: 1px solid var(--border-color);
928
+ border-radius: var(--radius-sm);
929
+ font-size: 14px;
930
+ cursor: pointer;
931
+ transition: all 0.2s;
932
+ }
933
+
934
+ .settings-btn:hover {
935
+ background: var(--bg-tertiary);
936
+ color: var(--text-primary);
937
+ }
938
+
939
+ /* Main Content */
940
+ .main {
941
+ flex: 1;
942
+ display: flex;
943
+ flex-direction: column;
944
+ min-width: 0;
945
+ }
946
+
947
+ .header {
948
+ padding: 16px 24px;
949
+ border-bottom: 1px solid var(--border-color);
950
+ display: flex;
951
+ align-items: center;
952
+ justify-content: space-between;
953
+ background: var(--bg-secondary);
954
+ }
955
+
956
+ .model-selector {
957
+ display: flex;
958
+ align-items: center;
959
+ gap: 8px;
960
+ padding: 8px 16px;
961
+ background: var(--bg-tertiary);
962
+ border: 1px solid var(--border-color);
963
+ border-radius: var(--radius-sm);
964
+ font-size: 14px;
965
+ cursor: pointer;
966
+ }
967
+
968
+ .model-badge {
969
+ padding: 2px 8px;
970
+ background: var(--accent);
971
+ color: white;
972
+ border-radius: 4px;
973
+ font-size: 12px;
974
+ font-weight: 500;
975
+ }
976
+
977
+ .header-actions {
978
+ display: flex;
979
+ gap: 8px;
980
+ }
981
+
982
+ .icon-btn {
983
+ width: 36px;
984
+ height: 36px;
985
+ display: flex;
986
+ align-items: center;
987
+ justify-content: center;
988
+ background: transparent;
989
+ border: 1px solid var(--border-color);
990
+ border-radius: var(--radius-sm);
991
+ cursor: pointer;
992
+ color: var(--text-secondary);
993
+ transition: all 0.2s;
994
+ }
995
+
996
+ .icon-btn:hover {
997
+ background: var(--bg-tertiary);
998
+ color: var(--text-primary);
999
+ }
1000
+
1001
+ /* Messages */
1002
+ .messages-container {
1003
+ flex: 1;
1004
+ overflow-y: auto;
1005
+ padding: 24px;
1006
+ }
1007
+
1008
+ .messages-container::-webkit-scrollbar {
1009
+ width: 8px;
1010
+ }
1011
+
1012
+ .messages-container::-webkit-scrollbar-track {
1013
+ background: var(--scrollbar-track);
1014
+ }
1015
+
1016
+ .messages-container::-webkit-scrollbar-thumb {
1017
+ background: var(--scrollbar-thumb);
1018
+ border-radius: 4px;
1019
+ }
1020
+
1021
+ .message {
1022
+ max-width: 800px;
1023
+ margin: 0 auto 24px;
1024
+ animation: fadeIn 0.3s ease;
1025
+ }
1026
+
1027
+ @keyframes fadeIn {
1028
+ from { opacity: 0; transform: translateY(10px); }
1029
+ to { opacity: 1; transform: translateY(0); }
1030
+ }
1031
+
1032
+ .message-header {
1033
+ display: flex;
1034
+ align-items: center;
1035
+ gap: 12px;
1036
+ margin-bottom: 12px;
1037
+ }
1038
+
1039
+ .avatar {
1040
+ width: 32px;
1041
+ height: 32px;
1042
+ border-radius: 50%;
1043
+ display: flex;
1044
+ align-items: center;
1045
+ justify-content: center;
1046
+ font-size: 16px;
1047
+ flex-shrink: 0;
1048
+ }
1049
+
1050
+ .avatar.user {
1051
+ background: var(--user-bg);
1052
+ color: white;
1053
+ }
1054
+
1055
+ .avatar.assistant {
1056
+ background: linear-gradient(135deg, var(--accent), #f97316);
1057
+ color: white;
1058
+ }
1059
+
1060
+ .message-author {
1061
+ font-weight: 600;
1062
+ font-size: 14px;
1063
+ }
1064
+
1065
+ .message-time {
1066
+ font-size: 12px;
1067
+ color: var(--text-secondary);
1068
+ }
1069
+
1070
+ .message-content {
1071
+ padding-left: 44px;
1072
+ }
1073
+
1074
+ .message-text {
1075
+ line-height: 1.6;
1076
+ white-space: pre-wrap;
1077
+ word-wrap: break-word;
1078
+ }
1079
+
1080
+ .message-text p {
1081
+ margin-bottom: 12px;
1082
+ }
1083
+
1084
+ .message-text p:last-child {
1085
+ margin-bottom: 0;
1086
+ }
1087
+
1088
+ .message-text code {
1089
+ font-family: var(--font-mono);
1090
+ background: var(--code-bg);
1091
+ padding: 2px 6px;
1092
+ border-radius: 4px;
1093
+ font-size: 13px;
1094
+ }
1095
+
1096
+ .message-text pre {
1097
+ background: var(--code-bg);
1098
+ border: 1px solid var(--border-color);
1099
+ border-radius: var(--radius-sm);
1100
+ padding: 16px;
1101
+ overflow-x: auto;
1102
+ margin: 12px 0;
1103
+ }
1104
+
1105
+ .message-text pre code {
1106
+ background: none;
1107
+ padding: 0;
1108
+ }
1109
+
1110
+ /* Tool calls */
1111
+ .tool-call {
1112
+ background: var(--bg-tertiary);
1113
+ border: 1px solid var(--border-color);
1114
+ border-radius: var(--radius-sm);
1115
+ margin: 12px 0;
1116
+ overflow: hidden;
1117
+ }
1118
+
1119
+ .tool-header {
1120
+ display: flex;
1121
+ align-items: center;
1122
+ justify-content: space-between;
1123
+ padding: 12px 16px;
1124
+ background: var(--bg-secondary);
1125
+ border-bottom: 1px solid var(--border-color);
1126
+ }
1127
+
1128
+ .tool-name {
1129
+ font-family: var(--font-mono);
1130
+ font-size: 13px;
1131
+ font-weight: 500;
1132
+ }
1133
+
1134
+ .tool-status {
1135
+ font-size: 12px;
1136
+ padding: 2px 8px;
1137
+ border-radius: 4px;
1138
+ }
1139
+
1140
+ .tool-status.running {
1141
+ background: var(--warning);
1142
+ color: white;
1143
+ }
1144
+
1145
+ .tool-status.complete {
1146
+ background: var(--success);
1147
+ color: white;
1148
+ }
1149
+
1150
+ .tool-status.error {
1151
+ background: var(--error);
1152
+ color: white;
1153
+ }
1154
+
1155
+ .tool-content {
1156
+ padding: 12px 16px;
1157
+ font-family: var(--font-mono);
1158
+ font-size: 12px;
1159
+ max-height: 200px;
1160
+ overflow-y: auto;
1161
+ }
1162
+
1163
+ /* Streaming indicator */
1164
+ .streaming-indicator {
1165
+ display: inline-flex;
1166
+ gap: 4px;
1167
+ margin-left: 8px;
1168
+ }
1169
+
1170
+ .streaming-indicator span {
1171
+ width: 6px;
1172
+ height: 6px;
1173
+ background: var(--accent);
1174
+ border-radius: 50%;
1175
+ animation: pulse 1.4s ease-in-out infinite;
1176
+ }
1177
+
1178
+ .streaming-indicator span:nth-child(2) { animation-delay: 0.2s; }
1179
+ .streaming-indicator span:nth-child(3) { animation-delay: 0.4s; }
1180
+
1181
+ @keyframes pulse {
1182
+ 0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
1183
+ 40% { transform: scale(1); opacity: 1; }
1184
+ }
1185
+
1186
+ /* Input */
1187
+ .input-container {
1188
+ padding: 16px 24px 24px;
1189
+ background: var(--bg-secondary);
1190
+ border-top: 1px solid var(--border-color);
1191
+ }
1192
+
1193
+ .input-wrapper {
1194
+ max-width: 800px;
1195
+ margin: 0 auto;
1196
+ }
1197
+
1198
+ .input-box {
1199
+ display: flex;
1200
+ align-items: flex-end;
1201
+ gap: 12px;
1202
+ background: var(--bg-primary);
1203
+ border: 1px solid var(--border-color);
1204
+ border-radius: var(--radius);
1205
+ padding: 12px 16px;
1206
+ transition: border-color 0.2s, box-shadow 0.2s;
1207
+ }
1208
+
1209
+ .input-box:focus-within {
1210
+ border-color: var(--accent);
1211
+ box-shadow: 0 0 0 3px rgba(229, 72, 77, 0.2);
1212
+ }
1213
+
1214
+ .input-box textarea {
1215
+ flex: 1;
1216
+ background: transparent;
1217
+ border: none;
1218
+ outline: none;
1219
+ color: var(--text-primary);
1220
+ font-family: var(--font-sans);
1221
+ font-size: 15px;
1222
+ line-height: 1.5;
1223
+ resize: none;
1224
+ min-height: 24px;
1225
+ max-height: 200px;
1226
+ }
1227
+
1228
+ .input-box textarea::placeholder {
1229
+ color: var(--text-secondary);
1230
+ }
1231
+
1232
+ .send-btn {
1233
+ width: 40px;
1234
+ height: 40px;
1235
+ display: flex;
1236
+ align-items: center;
1237
+ justify-content: center;
1238
+ background: var(--accent);
1239
+ border: none;
1240
+ border-radius: var(--radius-sm);
1241
+ cursor: pointer;
1242
+ color: white;
1243
+ transition: background 0.2s, transform 0.1s;
1244
+ }
1245
+
1246
+ .send-btn:hover:not(:disabled) {
1247
+ background: var(--accent-hover);
1248
+ }
1249
+
1250
+ .send-btn:active:not(:disabled) {
1251
+ transform: scale(0.95);
1252
+ }
1253
+
1254
+ .send-btn:disabled {
1255
+ opacity: 0.5;
1256
+ cursor: not-allowed;
1257
+ }
1258
+
1259
+ .input-hint {
1260
+ text-align: center;
1261
+ font-size: 12px;
1262
+ color: var(--text-secondary);
1263
+ margin-top: 8px;
1264
+ }
1265
+
1266
+ /* Welcome screen */
1267
+ .welcome {
1268
+ max-width: 600px;
1269
+ margin: auto;
1270
+ text-align: center;
1271
+ padding: 40px;
1272
+ }
1273
+
1274
+ .welcome-icon {
1275
+ font-size: 64px;
1276
+ margin-bottom: 24px;
1277
+ }
1278
+
1279
+ .welcome h1 {
1280
+ font-size: 28px;
1281
+ margin-bottom: 12px;
1282
+ }
1283
+
1284
+ .welcome p {
1285
+ color: var(--text-secondary);
1286
+ line-height: 1.6;
1287
+ margin-bottom: 32px;
1288
+ }
1289
+
1290
+ .suggestions {
1291
+ display: grid;
1292
+ grid-template-columns: repeat(2, 1fr);
1293
+ gap: 12px;
1294
+ }
1295
+
1296
+ .suggestion {
1297
+ padding: 16px;
1298
+ background: var(--bg-secondary);
1299
+ border: 1px solid var(--border-color);
1300
+ border-radius: var(--radius-sm);
1301
+ text-align: left;
1302
+ cursor: pointer;
1303
+ transition: all 0.2s;
1304
+ }
1305
+
1306
+ .suggestion:hover {
1307
+ background: var(--bg-tertiary);
1308
+ border-color: var(--accent);
1309
+ }
1310
+
1311
+ .suggestion-title {
1312
+ font-weight: 500;
1313
+ margin-bottom: 4px;
1314
+ }
1315
+
1316
+ .suggestion-desc {
1317
+ font-size: 13px;
1318
+ color: var(--text-secondary);
1319
+ }
1320
+
1321
+ /* Cost display */
1322
+ .cost-display {
1323
+ display: flex;
1324
+ align-items: center;
1325
+ gap: 8px;
1326
+ font-size: 12px;
1327
+ color: var(--text-secondary);
1328
+ }
1329
+
1330
+ .cost-value {
1331
+ font-family: var(--font-mono);
1332
+ color: var(--success);
1333
+ }
1334
+
1335
+ /* Empty state */
1336
+ .empty-sessions {
1337
+ padding: 40px 20px;
1338
+ text-align: center;
1339
+ color: var(--text-secondary);
1340
+ }
1341
+
1342
+ /* Responsive */
1343
+ @media (max-width: 768px) {
1344
+ .sidebar {
1345
+ display: none;
1346
+ }
1347
+
1348
+ .messages-container {
1349
+ padding: 16px;
1350
+ }
1351
+
1352
+ .message-content {
1353
+ padding-left: 0;
1354
+ }
1355
+
1356
+ .suggestions {
1357
+ grid-template-columns: 1fr;
1358
+ }
1359
+ }
1360
+ </style>
1361
+ </head>
1362
+ <body>
1363
+ <div class="app" id="app">
1364
+ <!-- Sidebar -->
1365
+ <aside class="sidebar">
1366
+ <div class="sidebar-header">
1367
+ <div class="logo">
1368
+ <div class="logo-icon">S</div>
1369
+ <span>smolerclaw</span>
1370
+ </div>
1371
+ <button class="new-chat-btn" onclick="newSession()">
1372
+ ${Z("web.new_chat")}
1373
+ </button>
1374
+ </div>
1375
+
1376
+ <div class="sessions-list" id="sessions-list">
1377
+ <div class="empty-sessions">${Z("web.no_sessions")}</div>
1378
+ </div>
1379
+
1380
+ <div class="sidebar-footer">
1381
+ <div class="cost-display">
1382
+ <span>${Z("web.total_cost")}</span>
1383
+ <span class="cost-value" id="total-cost">$0.00</span>
1384
+ </div>
1385
+ </div>
1386
+ </aside>
1387
+
1388
+ <!-- Main Content -->
1389
+ <main class="main">
1390
+ <header class="header">
1391
+ <div class="model-selector">
1392
+ <span class="model-badge">Claude</span>
1393
+ <span id="model-name">claude-sonnet-4</span>
1394
+ </div>
1395
+ <div class="header-actions">
1396
+ <button class="icon-btn" onclick="toggleTheme()" title="${Z("web.toggle_theme")}">
1397
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1398
+ <circle cx="12" cy="12" r="5"/>
1399
+ <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/>
1400
+ </svg>
1401
+ </button>
1402
+ <button class="icon-btn" onclick="clearChat()" title="${Z("web.clear_chat")}">
1403
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1404
+ <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2"/>
1405
+ </svg>
1406
+ </button>
1407
+ </div>
1408
+ </header>
1409
+
1410
+ <div class="messages-container" id="messages-container">
1411
+ <div class="welcome">
1412
+ <div class="welcome-icon">S</div>
1413
+ <h1>${Z("web.welcome_title")}</h1>
1414
+ <p>${Z("web.welcome_desc")}</p>
1415
+ <div class="suggestions">
1416
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_start_prompt'])">
1417
+ <div class="suggestion-title">${Z("web.suggestion_start_title")}</div>
1418
+ <div class="suggestion-desc">${Z("web.suggestion_start_desc")}</div>
1419
+ </div>
1420
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_tasks_prompt'])">
1421
+ <div class="suggestion-title">${Z("web.suggestion_tasks_title")}</div>
1422
+ <div class="suggestion-desc">${Z("web.suggestion_tasks_desc")}</div>
1423
+ </div>
1424
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_system_prompt'])">
1425
+ <div class="suggestion-title">${Z("web.suggestion_system_title")}</div>
1426
+ <div class="suggestion-desc">${Z("web.suggestion_system_desc")}</div>
1427
+ </div>
1428
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_briefing_prompt'])">
1429
+ <div class="suggestion-title">${Z("web.suggestion_briefing_title")}</div>
1430
+ <div class="suggestion-desc">${Z("web.suggestion_briefing_desc")}</div>
1431
+ </div>
1432
+ </div>
1433
+ </div>
1434
+ </div>
1435
+
1436
+ <div class="input-container">
1437
+ <div class="input-wrapper">
1438
+ <div class="input-box">
1439
+ <textarea
1440
+ id="input"
1441
+ placeholder="${Z("web.placeholder")}"
1442
+ rows="1"
1443
+ onkeydown="handleKeyDown(event)"
1444
+ oninput="autoResize(this)"
1445
+ ></textarea>
1446
+ <button class="send-btn" id="send-btn" onclick="sendMessage()">
1447
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1448
+ <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
1449
+ </svg>
1450
+ </button>
1451
+ </div>
1452
+ <div class="input-hint">${Z("web.input_hint")}</div>
1453
+ </div>
1454
+ </div>
1455
+ </main>
1456
+ </div>
1457
+
1458
+ <script>
1459
+ // i18n translations injected from server
1460
+ window.__i18n = ${JSON.stringify(Object.fromEntries(Object.entries($).filter(([Y])=>Y.startsWith("web."))))};
1461
+ const __t = (key) => window.__i18n[key] || key;
1462
+
1463
+ // State
1464
+ let ws = null;
1465
+ let state = {
1466
+ messages: [],
1467
+ sessions: [],
1468
+ currentSession: null,
1469
+ isStreaming: false,
1470
+ totalCostCents: 0,
1471
+ };
1472
+ let currentMessageId = null;
1473
+ let currentMessageContent = '';
1474
+
1475
+ // Theme
1476
+ function getTheme() {
1477
+ return localStorage.getItem('theme') || 'dark';
1478
+ }
1479
+
1480
+ function setTheme(theme) {
1481
+ localStorage.setItem('theme', theme);
1482
+ document.documentElement.dataset.theme = theme;
1483
+ }
1484
+
1485
+ function toggleTheme() {
1486
+ setTheme(getTheme() === 'dark' ? 'light' : 'dark');
1487
+ }
1488
+
1489
+ // Initialize
1490
+ setTheme(getTheme());
1491
+
1492
+ // WebSocket
1493
+ function connect() {
1494
+ const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1495
+ ws = new WebSocket(protocol + '//' + location.host + '/ws');
1496
+
1497
+ ws.onopen = () => {
1498
+ console.log(__t('web.connected'));
1499
+ };
1500
+
1501
+ ws.onmessage = (event) => {
1502
+ const msg = JSON.parse(event.data);
1503
+ handleServerMessage(msg);
1504
+ };
1505
+
1506
+ ws.onclose = () => {
1507
+ console.log(__t('web.disconnected'));
1508
+ setTimeout(connect, 1000);
1509
+ };
1510
+
1511
+ ws.onerror = (err) => {
1512
+ console.error('WebSocket error:', err);
1513
+ };
1514
+ }
1515
+
1516
+ function handleServerMessage(msg) {
1517
+ switch (msg.type) {
1518
+ case 'connected':
1519
+ console.log('Session:', msg.payload.sessionId);
1520
+ break;
1521
+
1522
+ case 'state':
1523
+ state = { ...state, ...msg.payload };
1524
+ renderSessions();
1525
+ renderMessages();
1526
+ updateCost();
1527
+ break;
1528
+
1529
+ case 'message_start':
1530
+ currentMessageId = msg.payload.messageId;
1531
+ currentMessageContent = '';
1532
+ state.isStreaming = true;
1533
+ addStreamingMessage();
1534
+ break;
1535
+
1536
+ case 'text_delta':
1537
+ currentMessageContent += msg.payload.text;
1538
+ updateStreamingMessage();
1539
+ break;
1540
+
1541
+ case 'tool_call':
1542
+ addToolCall(msg.payload);
1543
+ break;
1544
+
1545
+ case 'tool_result':
1546
+ updateToolResult(msg.payload);
1547
+ break;
1548
+
1549
+ case 'usage':
1550
+ state.totalCostCents += calculateCost(msg.payload.inputTokens, msg.payload.outputTokens);
1551
+ updateCost();
1552
+ break;
1553
+
1554
+ case 'message_complete':
1555
+ finalizeMessage();
1556
+ break;
1557
+
1558
+ case 'error':
1559
+ showError(msg.payload.error);
1560
+ break;
1561
+
1562
+ case 'sessions_updated':
1563
+ state.sessions = msg.payload;
1564
+ renderSessions();
1565
+ break;
1566
+ }
1567
+ }
1568
+
1569
+ function calculateCost(inputTokens, outputTokens) {
1570
+ const inputCost = (inputTokens / 1_000_000) * 300;
1571
+ const outputCost = (outputTokens / 1_000_000) * 1500;
1572
+ return Math.round((inputCost + outputCost) * 100) / 100;
1573
+ }
1574
+
1575
+ // UI Functions
1576
+ function renderSessions() {
1577
+ const container = document.getElementById('sessions-list');
1578
+ if (state.sessions.length === 0) {
1579
+ container.innerHTML = '<div class="empty-sessions">' + __t('web.no_sessions') + '</div>';
1580
+ return;
1581
+ }
1582
+
1583
+ container.innerHTML = state.sessions.map(s => \`
1584
+ <div class="session-item \${s.isActive ? 'active' : ''}" onclick="loadSession(\${JSON.stringify(s.id)})">
1585
+ <div class="session-name">\${escapeHtml(s.name)}</div>
1586
+ <div class="session-meta">\${s.messageCount} \${__t('web.messages_count').replace('{{count}}', '')}</div>
1587
+ </div>
1588
+ \`).join('');
1589
+ }
1590
+
1591
+ function renderMessages() {
1592
+ const container = document.getElementById('messages-container');
1593
+
1594
+ if (state.messages.length === 0) {
1595
+ container.innerHTML = getWelcomeHtml();
1596
+ return;
1597
+ }
1598
+
1599
+ container.innerHTML = state.messages.map(m => renderMessage(m)).join('');
1600
+ scrollToBottom();
1601
+ }
1602
+
1603
+ function renderMessage(msg) {
1604
+ const isUser = msg.role === 'user';
1605
+ const avatar = isUser ? '\uD83D\uDC64' : 'S';
1606
+ const author = isUser ? __t('web.you') : __t('web.assistant');
1607
+ const time = new Date(msg.timestamp).toLocaleTimeString();
1608
+
1609
+ let toolCallsHtml = '';
1610
+ if (msg.toolCalls && msg.toolCalls.length > 0) {
1611
+ toolCallsHtml = msg.toolCalls.map(tc => \`
1612
+ <div class="tool-call">
1613
+ <div class="tool-header">
1614
+ <span class="tool-name">\${escapeHtml(tc.name)}</span>
1615
+ <span class="tool-status \${tc.status}">\${tc.status}</span>
1616
+ </div>
1617
+ \${tc.result ? \`<div class="tool-content">\${escapeHtml(tc.result.substring(0, 500))}\${tc.result.length > 500 ? '...' : ''}</div>\` : ''}
1618
+ </div>
1619
+ \`).join('');
1620
+ }
1621
+
1622
+ return \`
1623
+ <div class="message">
1624
+ <div class="message-header">
1625
+ <div class="avatar \${isUser ? 'user' : 'assistant'}">\${avatar}</div>
1626
+ <span class="message-author">\${author}</span>
1627
+ <span class="message-time">\${time}</span>
1628
+ </div>
1629
+ <div class="message-content">
1630
+ <div class="message-text">\${formatMessage(msg.content)}</div>
1631
+ \${toolCallsHtml}
1632
+ </div>
1633
+ </div>
1634
+ \`;
1635
+ }
1636
+
1637
+ function addStreamingMessage() {
1638
+ const container = document.getElementById('messages-container');
1639
+
1640
+ // Remove welcome if present
1641
+ const welcome = container.querySelector('.welcome');
1642
+ if (welcome) welcome.remove();
1643
+
1644
+ // Add user message
1645
+ const userMsg = {
1646
+ id: 'user-' + currentMessageId,
1647
+ role: 'user',
1648
+ content: document.getElementById('input').value,
1649
+ timestamp: Date.now(),
1650
+ };
1651
+ state.messages.push(userMsg);
1652
+ container.insertAdjacentHTML('beforeend', renderMessage(userMsg));
1653
+
1654
+ // Add streaming assistant message
1655
+ const streamingHtml = \`
1656
+ <div class="message" id="streaming-message">
1657
+ <div class="message-header">
1658
+ <div class="avatar assistant">S</div>
1659
+ <span class="message-author">\${__t('web.assistant')}</span>
1660
+ <div class="streaming-indicator">
1661
+ <span></span><span></span><span></span>
1662
+ </div>
1663
+ </div>
1664
+ <div class="message-content">
1665
+ <div class="message-text" id="streaming-content"></div>
1666
+ <div id="streaming-tools"></div>
1667
+ </div>
1668
+ </div>
1669
+ \`;
1670
+ container.insertAdjacentHTML('beforeend', streamingHtml);
1671
+ scrollToBottom();
1672
+ }
1673
+
1674
+ function updateStreamingMessage() {
1675
+ const content = document.getElementById('streaming-content');
1676
+ if (content) {
1677
+ content.innerHTML = formatMessage(currentMessageContent);
1678
+ scrollToBottom();
1679
+ }
1680
+ }
1681
+
1682
+ function addToolCall(tc) {
1683
+ const tools = document.getElementById('streaming-tools');
1684
+ if (tools) {
1685
+ tools.insertAdjacentHTML('beforeend', \`
1686
+ <div class="tool-call" id="tool-\${tc.id}">
1687
+ <div class="tool-header">
1688
+ <span class="tool-name">\${escapeHtml(tc.name)}</span>
1689
+ <span class="tool-status running">\${__t('web.running')}</span>
1690
+ </div>
1691
+ </div>
1692
+ \`);
1693
+ scrollToBottom();
1694
+ }
1695
+ }
1696
+
1697
+ function updateToolResult(payload) {
1698
+ const tool = document.getElementById('tool-' + payload.toolCallId);
1699
+ if (tool) {
1700
+ tool.querySelector('.tool-status').className = 'tool-status complete';
1701
+ tool.querySelector('.tool-status').textContent = __t('web.complete');
1702
+ tool.insertAdjacentHTML('beforeend', \`
1703
+ <div class="tool-content">\${escapeHtml(payload.result.substring(0, 500))}\${payload.result.length > 500 ? '...' : ''}</div>
1704
+ \`);
1705
+ scrollToBottom();
1706
+ }
1707
+ }
1708
+
1709
+ function finalizeMessage() {
1710
+ const streaming = document.getElementById('streaming-message');
1711
+ if (streaming) {
1712
+ const indicator = streaming.querySelector('.streaming-indicator');
1713
+ if (indicator) indicator.remove();
1714
+
1715
+ const time = document.createElement('span');
1716
+ time.className = 'message-time';
1717
+ time.textContent = new Date().toLocaleTimeString();
1718
+ streaming.querySelector('.message-header').appendChild(time);
1719
+ }
1720
+
1721
+ state.messages.push({
1722
+ id: currentMessageId,
1723
+ role: 'assistant',
1724
+ content: currentMessageContent,
1725
+ timestamp: Date.now(),
1726
+ status: 'complete',
1727
+ });
1728
+
1729
+ state.isStreaming = false;
1730
+ currentMessageId = null;
1731
+ currentMessageContent = '';
1732
+ updateSendButton();
1733
+ }
1734
+
1735
+ function showError(error) {
1736
+ const streaming = document.getElementById('streaming-message');
1737
+ if (streaming) {
1738
+ streaming.querySelector('.streaming-indicator')?.remove();
1739
+ const content = streaming.querySelector('.message-content');
1740
+ content.innerHTML = \`<div style="color: var(--error)">\${escapeHtml(error)}</div>\`;
1741
+ }
1742
+ state.isStreaming = false;
1743
+ updateSendButton();
1744
+ }
1745
+
1746
+ function updateCost() {
1747
+ const costEl = document.getElementById('total-cost');
1748
+ costEl.textContent = '$' + (state.totalCostCents / 100).toFixed(4);
1749
+ }
1750
+
1751
+ function scrollToBottom() {
1752
+ const container = document.getElementById('messages-container');
1753
+ container.scrollTop = container.scrollHeight;
1754
+ }
1755
+
1756
+ // Input handling
1757
+ function handleKeyDown(event) {
1758
+ if (event.key === 'Enter' && !event.shiftKey) {
1759
+ event.preventDefault();
1760
+ sendMessage();
1761
+ }
1762
+ }
1763
+
1764
+ function autoResize(textarea) {
1765
+ textarea.style.height = 'auto';
1766
+ textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
1767
+ }
1768
+
1769
+ function sendMessage() {
1770
+ const input = document.getElementById('input');
1771
+ const message = input.value.trim();
1772
+
1773
+ if (!message || state.isStreaming) return;
1774
+
1775
+ ws.send(JSON.stringify({
1776
+ type: 'chat',
1777
+ payload: { message },
1778
+ }));
1779
+
1780
+ input.value = '';
1781
+ autoResize(input);
1782
+ updateSendButton();
1783
+ }
1784
+
1785
+ function sendSuggestion(text) {
1786
+ document.getElementById('input').value = text;
1787
+ sendMessage();
1788
+ }
1789
+
1790
+ function updateSendButton() {
1791
+ const btn = document.getElementById('send-btn');
1792
+ const input = document.getElementById('input');
1793
+ btn.disabled = state.isStreaming || !input.value.trim();
1794
+ }
1795
+
1796
+ // Session management
1797
+ function newSession() {
1798
+ ws.send(JSON.stringify({ type: 'new_session' }));
1799
+ }
1800
+
1801
+ function loadSession(sessionId) {
1802
+ ws.send(JSON.stringify({ type: 'load_session', payload: { sessionId } }));
1803
+ }
1804
+
1805
+ function clearChat() {
1806
+ if (confirm(__t('web.confirm_new_chat'))) {
1807
+ newSession();
1808
+ }
1809
+ }
1810
+
1811
+ // Utilities
1812
+ function escapeHtml(text) {
1813
+ const div = document.createElement('div');
1814
+ div.textContent = text;
1815
+ return div.innerHTML;
1816
+ }
1817
+
1818
+ function formatMessage(text) {
1819
+ if (!text) return '';
1820
+
1821
+ // Simple markdown-like formatting
1822
+ let html = escapeHtml(text);
1823
+
1824
+ // Code blocks
1825
+ html = html.replace(/\\\`\\\`\\\`([\\s\\S]*?)\\\`\\\`\\\`/g, '<pre><code>$1</code></pre>');
1826
+
1827
+ // Inline code
1828
+ html = html.replace(/\\\`([^\\\`]+)\\\`/g, '<code>$1</code>');
1829
+
1830
+ // Bold
1831
+ html = html.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');
1832
+
1833
+ // Italic
1834
+ html = html.replace(/\\*([^*]+)\\*/g, '<em>$1</em>');
1835
+
1836
+ // Line breaks
1837
+ html = html.replace(/\\n/g, '<br>');
1838
+
1839
+ return html;
1840
+ }
1841
+
1842
+ function getWelcomeHtml() {
1843
+ return \`
1844
+ <div class="welcome">
1845
+ <div class="welcome-icon">S</div>
1846
+ <h1>${Z("web.welcome_title")}</h1>
1847
+ <p>${Z("web.welcome_desc")}</p>
1848
+ <div class="suggestions">
1849
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_start_prompt'])">
1850
+ <div class="suggestion-title">${Z("web.suggestion_start_title")}</div>
1851
+ <div class="suggestion-desc">${Z("web.suggestion_start_desc")}</div>
1852
+ </div>
1853
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_tasks_prompt'])">
1854
+ <div class="suggestion-title">${Z("web.suggestion_tasks_title")}</div>
1855
+ <div class="suggestion-desc">${Z("web.suggestion_tasks_desc")}</div>
1856
+ </div>
1857
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_system_prompt'])">
1858
+ <div class="suggestion-title">${Z("web.suggestion_system_title")}</div>
1859
+ <div class="suggestion-desc">${Z("web.suggestion_system_desc")}</div>
1860
+ </div>
1861
+ <div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_briefing_prompt'])">
1862
+ <div class="suggestion-title">${Z("web.suggestion_briefing_title")}</div>
1863
+ <div class="suggestion-desc">${Z("web.suggestion_briefing_desc")}</div>
1864
+ </div>
1865
+ </div>
1866
+ </div>
1867
+ \`;
1868
+ }
1869
+
1870
+ // Start
1871
+ connect();
1872
+ document.getElementById('input').addEventListener('input', updateSendButton);
1873
+ </script>
1874
+ </body>
1875
+ </html>`}var pO=typeof globalThis<"u"&&"Electrobun"in globalThis;async function x9($){let Z=await aK(3847);w8({port:Z,provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager}).start();let Q=`http://localhost:${Z}`;if(pO)await dO(Q,$.devMode);else console.log(`
1876
+ ${S("desktop.not_available")}`),console.log(` ${S("desktop.opening_browser",{url:Q})}
1877
+ `),await _9(Q);return{port:Z,url:Q}}async function dO($,Z=!1){let Y=globalThis.Electrobun,Q=await Y.createBrowserWindow({title:"smolerclaw",url:$,width:1200,height:800,minWidth:800,minHeight:600,frame:!0,titleBarStyle:"hidden",vibrancy:"under-window",backgroundColor:"#0d1117",webPreferences:{devTools:Z}});return Q.on("closed",()=>{process.exit(0)}),cO(Y),Q}function cO($){$.ipc.on("menu:new-chat",()=>{$.ipc.send("app:new-chat")}),$.ipc.on("menu:settings",()=>{$.ipc.send("app:open-settings")}),$.ipc.on("menu:toggle-theme",()=>{$.ipc.send("app:toggle-theme")}),$.setApplicationMenu([{label:"smolerclaw",submenu:[{label:S("desktop.about"),role:"about"},{type:"separator"},{label:S("desktop.settings"),accelerator:"CmdOrCtrl+,",click:()=>$.ipc.send("menu:settings")},{type:"separator"},{label:S("desktop.quit"),accelerator:"CmdOrCtrl+Q",role:"quit"}]},{label:S("desktop.chat"),submenu:[{label:S("desktop.new_chat"),accelerator:"CmdOrCtrl+N",click:()=>$.ipc.send("menu:new-chat")},{type:"separator"},{label:S("desktop.clear_chat"),accelerator:"CmdOrCtrl+K",click:()=>$.ipc.send("menu:clear-chat")}]},{label:S("desktop.edit"),submenu:[{label:S("desktop.undo"),accelerator:"CmdOrCtrl+Z",role:"undo"},{label:S("desktop.redo"),accelerator:"Shift+CmdOrCtrl+Z",role:"redo"},{type:"separator"},{label:S("desktop.cut"),accelerator:"CmdOrCtrl+X",role:"cut"},{label:S("desktop.copy"),accelerator:"CmdOrCtrl+C",role:"copy"},{label:S("desktop.paste"),accelerator:"CmdOrCtrl+V",role:"paste"},{label:S("desktop.select_all"),accelerator:"CmdOrCtrl+A",role:"selectAll"}]},{label:S("desktop.view"),submenu:[{label:S("desktop.toggle_theme"),accelerator:"CmdOrCtrl+Shift+T",click:()=>$.ipc.send("menu:toggle-theme")},{type:"separator"},{label:S("desktop.actual_size"),accelerator:"CmdOrCtrl+0",role:"resetZoom"},{label:S("desktop.zoom_in"),accelerator:"CmdOrCtrl+=",role:"zoomIn"},{label:S("desktop.zoom_out"),accelerator:"CmdOrCtrl+-",role:"zoomOut"},{type:"separator"},{label:S("desktop.dev_tools"),accelerator:"Alt+CmdOrCtrl+I",role:"toggleDevTools"}]},{label:S("desktop.window"),submenu:[{label:S("desktop.minimize"),accelerator:"CmdOrCtrl+M",role:"minimize"},{label:S("desktop.zoom"),role:"zoom"},{type:"separator"},{label:S("desktop.close"),accelerator:"CmdOrCtrl+W",role:"close"}]},{label:S("desktop.help"),submenu:[{label:S("desktop.documentation"),click:()=>_9("https://github.com/ktfth/smolerclaw")},{label:S("desktop.report_issue"),click:()=>_9("https://github.com/ktfth/smolerclaw/issues")}]}])}async function _9($){let{exec:Z}=await import("child_process"),{platform:Y}=await import("os"),Q={darwin:`open "${$}"`,win32:`start "" "${$}"`,linux:`xdg-open "${$}"`},z=Q[Y()]||Q.linux;Z(z,(J)=>{if(J)console.error("Failed to open browser:",J)})}async function aK($){let Z=await import("net");return new Promise((Y)=>{let Q=Z.createServer();Q.unref(),Q.on("error",()=>{Y(aK($+1))}),Q.listen($,()=>{Q.close(()=>{Y($)})})})}function oO($){let Z=process.platform==="win32"?`start "" "${$}"`:process.platform==="darwin"?`open "${$}"`:`xdg-open "${$}"`;lO(Z,(Y)=>{if(Y)console.error(S("desktop.opening_browser",{url:$}),Y.message)})}async function sK($){let Z=$.port||3847;console.log(`
1878
+ ${S("ui.starting_web")}
1879
+ `),w8({port:Z,provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager}).start();let Q=`http://localhost:${Z}`;oO(Q),await new Promise(()=>{})}async function tK($){console.log(`
1880
+ ${S("ui.starting_desktop")}
1881
+ `);let{url:Z}=await x9({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,devMode:!0});console.log(` ${S("ui.running_at",{url:Z})}
1882
+ `),await new Promise(()=>{})}async function iO(){let $=g9(process.argv.slice(2));if($.help)m9(),process.exit(0);if($.version)console.log(`smolerclaw v${a$()}`),process.exit(0);let Z=WY();if(X3(Z.language),$.model)Z.model=n8($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=o7()}catch(H){console.error("smolerclaw:",H instanceof Error?H.message:H),process.exit(1)}let Q={auth:Y},z=t3(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:J,skills:X,systemPrompt:K,activeSystemPrompt:G,enableTools:V,plugins:U}=await VX(Z,$.session,$.noTools);if(M9(Z.dataDir,J),$.uiMode==="web"){await sK({provider:z,systemPrompt:K,enableTools:V,sessionManager:J,port:$.port});return}if($.uiMode==="desktop"){await tK({provider:z,systemPrompt:K,enableTools:V,sessionManager:J,port:$.port});return}let q=!process.stdin.isTTY;if($.print||q)await UX(z,J,K,V,$.prompt,q),process.exit(0);await EK(z,J,Z,Q,X,K,G,V,U,$.prompt)}iO().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});