smolerclaw 1.6.1 → 1.7.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 +266 -256
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,26 +1,26 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var WG=Object.defineProperty;var BG=($)=>$;function NG($,Z){this[$]=BG.bind(null,Z)}var p9=($,Z)=>{for(var Y in Z)WG($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:NG.bind(Z,Y)})};var B$=($,Z)=>()=>($&&(Z=$($=0)),Z);var OG=import.meta.require;import{existsSync as RG,appendFileSync as FG,mkdirSync as NO,writeFileSync as LG,unlinkSync as jG}from"fs";import{join as _7}from"path";import{tmpdir as PG,homedir as AG}from"os";import{randomBytes as DG}from"crypto";function d1($,Z,Y){if(!v8)return;let Q=new Date().toISOString(),z=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
3
+ var yG=Object.defineProperty;var _G=($)=>$;function xG($,Z){this[$]=_G.bind(null,Z)}var a9=($,Z)=>{for(var Y in Z)yG($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:xG.bind(Z,Y)})};var N$=($,Z)=>()=>($&&(Z=$($=0)),Z);var vG=import.meta.require;import{existsSync as mG,appendFileSync as pG,mkdirSync as mO,writeFileSync as dG,unlinkSync as cG}from"fs";import{join as g7}from"path";import{tmpdir as lG,homedir as oG}from"os";import{randomBytes as iG}from"crypto";function c1($,Z,Y){if(!g8)return;let Q=new Date().toISOString(),z=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
4
4
  `:`[${Q}] [${$}] ${Z}
5
- `;try{FG(SG,z)}catch{}}function r9($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function n9($){let Z=$.replace(/\//g,"\\");return r9(Z)}async function h8($){let Z=x8.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(RG($)){let z={exists:!0,path:$};return x8.set($.toLowerCase(),z),z}return{exists:!1,error:`File not found: ${$}`}}let Y=$.replace(/'/g,"''"),Q=[`$c = Get-Command '${Y}' -ErrorAction SilentlyContinue`,"if ($c) { $c.Source } else {",` $exeName = if ('${Y}' -like '*.exe') { '${Y}' } else { '${Y}.exe' }`," $appBase = 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\'"," $r = Get-ItemProperty ($appBase + $exeName) -ErrorAction SilentlyContinue"," if ($r -and $r.'(default)') { $r.'(default)' }","}"].join("; ");try{let z=await K0(Q,{timeout:5000});if(z.exitCode===0&&z.stdout.trim()){let X={exists:!0,path:z.stdout.trim()};return x8.set($.toLowerCase(),X),X}let J={exists:!1,error:`'${$}' not found in PATH or App Paths`};return x8.set($.toLowerCase(),J),J}catch(z){return{exists:!1,error:z instanceof Error?z.message:String(z)}}}async function K0($,Z={}){let{timeout:Y=x7,cwd:Q,debug:z=v8,sta:J=!1}=Z,X=performance.now(),K=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,G=["powershell",...i9];if(J)G.push("-STA");if(G.push("-Command",K),z)d1("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)d1("ERROR","Failed to spawn process",{error:B.stderr});return B}let q=!1,U=setTimeout(()=>{q=!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():""]),N=await V.exited;clearTimeout(U);let C=Math.round(performance.now()-X),M={stdout:N$(H),stderr:N$(B),exitCode:q?-1:N,duration:C,timedOut:q};if(z)d1(M.exitCode===0?"INFO":"WARN","Command completed",{exitCode:M.exitCode,duration:C,timedOut:q,stdoutLength:M.stdout.length,stderrLength:M.stderr.length});return M}catch(H){clearTimeout(U);let B={stdout:"",stderr:`Execution error: ${H instanceof Error?H.message:String(H)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:q};if(z)d1("ERROR","Execution failed",{error:B.stderr,timedOut:q});return B}}async function a9($,Z={}){let Q=`& ${n9($)}`;return K0(Q,Z)}async function s9($,Z={}){let{timeout:Y=x7,cwd:Q,debug:z=v8,sta:J=!1}=Z,X=performance.now(),K=DG(4).toString("hex"),G=_7(PG(),`smolerclaw-${K}.ps1`),V=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
6
- ${$}`;try{LG(G,V,"utf-8")}catch(N){return{stdout:"",stderr:`Failed to write temp script: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}if(z)d1("INFO","Executing PowerShell via temp file",{tempPath:G,scriptLength:$.length,timeout:Y,sta:J});let q=["powershell",...i9];if(J)q.push("-STA");q.push("-File",G);let U;try{U=Bun.spawn(q,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(N){return y7(G),{stdout:"",stderr:`Failed to spawn PowerShell: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let H=!1,B=setTimeout(()=>{H=!0;try{U.kill()}catch{}},Y);try{let[N,C]=await Promise.all([U.stdout instanceof ReadableStream?new Response(U.stdout).text():"",U.stderr instanceof ReadableStream?new Response(U.stderr).text():""]),M=await U.exited;clearTimeout(B),y7(G);let F=Math.round(performance.now()-X),w={stdout:N$(N),stderr:N$(C),exitCode:H?-1:M,duration:F,timedOut:H};if(z)d1(w.exitCode===0?"INFO":"WARN","File command completed",{exitCode:w.exitCode,duration:F,timedOut:H});return w}catch(N){return clearTimeout(B),y7(G),{stdout:"",stderr:`Execution error: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:H}}}function y7($){try{jG($)}catch{}}async function v7($,Z={}){let{timeout:Y=x7,cwd:Q,debug:z=v8}=Z,J=performance.now();if(z)d1("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,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(G),{stdout:N$(V),stderr:N$(q),exitCode:K?-1:U,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 h7($,Z={}){return K0($,{...Z,sta:!0})}async function a0($,Z,Y=[],Q={}){let z=["schtasks",`/${$}`,"/TN",Z,...Y],J=Q.timeout??1e4;return v7(z,{...Q,timeout:J})}async function g7($,Z,Y={}){let Q=r9($),z=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return K0(z,Y)}async function t9($,Z={}){let Y=n9($);return K0(`Invoke-Item ${Y}`,Z)}async function C1($,Z,Y={}){let Q=o9($),z=o9(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 K0(J,{...Y,timeout:X})}async function g8($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await K0(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function e9($=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 K0(Y,Z)}function N$($){let Z=$.replace(TG,"");if(Z.length>l9)return Z.slice(0,l9)+`
7
- ... (truncated, ${Z.length} total chars)`;return Z}function o9($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function $Y($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var x7=15000,l9=1e5,TG,IG,SG,i9,v8=!1,x8;var p0=B$(()=>{TG=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,IG=_7(AG(),".smolerclaw","logs"),SG=_7(IG,"windows-executor.log"),i9=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];x8=new Map});import{existsSync as wG}from"fs";function O$(){if(L)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&wG($))return[$,"-c"];return["bash","-c"]}function YY(){if(L)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function kG($){if(L)return(await h8($)).exists;try{return(await v7(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function QY(){if(u8!==null)return u8;return u8=await kG("rg"),u8}function u7($){let Z=$.replace(/\\/g,"/");return $2.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var L,ZY,jO,u8=null,$2;var n=B$(()=>{p0();L=process.platform==="win32",ZY=process.platform==="darwin",jO=process.platform==="linux";$2=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as fG}from"events";class zY{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new fG,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 M1($){if(!m7)m7=new zY($);return m7}function Q0($,Z){t.emit($,Z)}var m7=null,t;var d0=B$(()=>{t=M1()});import{existsSync as s0,mkdirSync as p7,readFileSync as p8,writeFileSync as Z2,renameSync as JY,statSync as bG}from"fs";import{join as A0,dirname as XY,relative as yG}from"path";import{createHash as _G,randomUUID as KY}from"crypto";function HY($,Z){if(t0=$,UY=Z,G0=A0($,".backup"),vG(),c7=!0,c1=s0(A0(G0,".git")),c1)d7=uG()}function Y2(){return c7}function A($,Z){let Y=XY($);if(!s0(Y))p7(Y,{recursive:!0});let Q=A0(Y,`.smolerclaw-${KY().slice(0,8)}.tmp`);Z2(Q,Z),JY(Q,$);let z=!1;if(c7){let X=gG($);if(X&&d8.includes(X))xG(X,Z),z=!0}let J={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:z,timestamp:Date.now()};t.emit("file:saved",J)}function WY($){return _G("sha256").update($).digest("hex")}function xG($,Z){let Y=WY(Z),Q=new Date().toISOString(),z=Buffer.byteLength(Z,"utf-8");E1=[...E1.filter((J)=>J.file!==$),{file:$,sha256:Y,size:z,updatedAt:Q}],hG()}function vG(){let $=A0(t0,VY);if(!s0($)){E1=[];return}try{let Z=JSON.parse(p8($,"utf-8"));if(Z.version!==GY){E1=[];return}E1=Z.checksums||[]}catch{E1=[]}}function hG(){if(!t0)return;let $=A0(t0,VY),Z={checksums:E1,version:GY},Y=A0(t0,`.vault-${KY().slice(0,8)}.tmp`);Z2(Y,JSON.stringify(Z,null,2)),JY(Y,$)}function gG($){try{let Z=yG(t0,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function c8(){let $=[],Z=0;for(let Y of d8){let Q=A0(t0,Y),z=s0(Q);if(!z){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let J=0,X="";try{let V=bG(Q);J=V.size,X=V.mtime.toISOString()}catch{}let K=E1.find((V)=>V.file===Y),G=null;if(K)try{let V=p8(Q,"utf-8");if(G=WY(V)===K.sha256,!G)Z++}catch{G=!1,Z++}$.push({file:Y,exists:z,checksumValid:G,size:J,lastModified:X})}return{files:$,lastBackup:d7,backupEnabled:c1,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function l8($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${d8.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
5
+ `;try{pG(aG,z)}catch{}}function YY($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function QY($){let Z=$.replace(/\//g,"\\");return YY(Z)}async function u8($){let Z=h8.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(mG($)){let z={exists:!0,path:$};return h8.set($.toLowerCase(),z),z}return{exists:!1,error:`File not found: ${$}`}}let Y=$.replace(/'/g,"''"),Q=[`$c = Get-Command '${Y}' -ErrorAction SilentlyContinue`,"if ($c) { $c.Source } else {",` $exeName = if ('${Y}' -like '*.exe') { '${Y}' } else { '${Y}.exe' }`," $appBase = 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\'"," $r = Get-ItemProperty ($appBase + $exeName) -ErrorAction SilentlyContinue"," if ($r -and $r.'(default)') { $r.'(default)' }","}"].join("; ");try{let z=await G0(Q,{timeout:5000});if(z.exitCode===0&&z.stdout.trim()){let X={exists:!0,path:z.stdout.trim()};return h8.set($.toLowerCase(),X),X}let J={exists:!1,error:`'${$}' not found in PATH or App Paths`};return h8.set($.toLowerCase(),J),J}catch(z){return{exists:!1,error:z instanceof Error?z.message:String(z)}}}async function G0($,Z={}){let{timeout:Y=u7,cwd:Q,debug:z=g8,sta:J=!1}=Z,X=performance.now(),K=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,G=["powershell",...ZY];if(J)G.push("-STA");if(G.push("-Command",K),z)c1("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)c1("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():""]),N=await V.exited;clearTimeout(q);let M=Math.round(performance.now()-X),C={stdout:O$(H),stderr:O$(B),exitCode:U?-1:N,duration:M,timedOut:U};if(z)c1(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)c1("ERROR","Execution failed",{error:B.stderr,timedOut:U});return B}}async function zY($,Z={}){let Q=`& ${QY($)}`;return G0(Q,Z)}async function JY($,Z={}){let{timeout:Y=u7,cwd:Q,debug:z=g8,sta:J=!1}=Z,X=performance.now(),K=iG(4).toString("hex"),G=g7(lG(),`smolerclaw-${K}.ps1`),V=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
6
+ ${$}`;try{dG(G,V,"utf-8")}catch(N){return{stdout:"",stderr:`Failed to write temp script: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}if(z)c1("INFO","Executing PowerShell via temp file",{tempPath:G,scriptLength:$.length,timeout:Y,sta:J});let U=["powershell",...ZY];if(J)U.push("-STA");U.push("-File",G);let q;try{q=Bun.spawn(U,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(N){return h7(G),{stdout:"",stderr:`Failed to spawn PowerShell: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let H=!1,B=setTimeout(()=>{H=!0;try{q.kill()}catch{}},Y);try{let[N,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),h7(G);let F=Math.round(performance.now()-X),k={stdout:O$(N),stderr:O$(M),exitCode:H?-1:C,duration:F,timedOut:H};if(z)c1(k.exitCode===0?"INFO":"WARN","File command completed",{exitCode:k.exitCode,duration:F,timedOut:H});return k}catch(N){return clearTimeout(B),h7(G),{stdout:"",stderr:`Execution error: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:H}}}function h7($){try{cG($)}catch{}}async function m7($,Z={}){let{timeout:Y=u7,cwd:Q,debug:z=g8}=Z,J=performance.now();if(z)c1("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:O$(V),stderr:O$(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 p7($,Z={}){return G0($,{...Z,sta:!0})}async function s0($,Z,Y=[],Q={}){let z=["schtasks",`/${$}`,"/TN",Z,...Y],J=Q.timeout??1e4;return m7(z,{...Q,timeout:J})}async function d7($,Z,Y={}){let Q=YY($),z=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return G0(z,Y)}async function XY($,Z={}){let Y=QY($);return G0(`Invoke-Item ${Y}`,Z)}async function C1($,Z,Y={}){let Q=$Y($),z=$Y(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 G0(J,{...Y,timeout:X})}async function m8($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await G0(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function KY($=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 G0(Y,Z)}function O$($){let Z=$.replace(nG,"");if(Z.length>e9)return Z.slice(0,e9)+`
7
+ ... (truncated, ${Z.length} total chars)`;return Z}function $Y($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function GY($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var u7=15000,e9=1e5,nG,rG,aG,ZY,g8=!1,h8;var d0=N$(()=>{nG=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,rG=g7(oG(),".smolerclaw","logs"),aG=g7(rG,"windows-executor.log"),ZY=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];h8=new Map});import{existsSync as sG}from"fs";function M$(){if(L)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&sG($))return[$,"-c"];return["bash","-c"]}function UY(){if(L)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function tG($){if(L)return(await u8($)).exists;try{return(await m7(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function qY(){if(p8!==null)return p8;return p8=await tG("rg"),p8}function c7($){let Z=$.replace(/\\/g,"/");return Z2.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var L,VY,rO,p8=null,Z2;var a=N$(()=>{d0();L=process.platform==="win32",VY=process.platform==="darwin",rO=process.platform==="linux";Z2=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as eG}from"events";class HY{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 E1($){if(!l7)l7=new HY($);return l7}function z0($,Z){e.emit($,Z)}var l7=null,e;var c0=N$(()=>{e=E1()});import{existsSync as t0,mkdirSync as o7,readFileSync as c8,writeFileSync as Y2,renameSync as WY,statSync as $V}from"fs";import{join as T0,dirname as BY,relative as ZV}from"path";import{createHash as YV,randomUUID as NY}from"crypto";function RY($,Z){if(e0=$,EY=Z,V0=T0($,".backup"),zV(),n7=!0,l1=t0(T0(V0,".git")),l1)i7=KV()}function Q2(){return n7}function P($,Z){let Y=BY($);if(!t0(Y))o7(Y,{recursive:!0});let Q=T0(Y,`.smolerclaw-${NY().slice(0,8)}.tmp`);Y2(Q,Z),WY(Q,$);let z=!1;if(n7){let X=XV($);if(X&&l8.includes(X))QV(X,Z),z=!0}let J={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:z,timestamp:Date.now()};e.emit("file:saved",J)}function FY($){return YV("sha256").update($).digest("hex")}function QV($,Z){let Y=FY(Z),Q=new Date().toISOString(),z=Buffer.byteLength(Z,"utf-8");R1=[...R1.filter((J)=>J.file!==$),{file:$,sha256:Y,size:z,updatedAt:Q}],JV()}function zV(){let $=T0(e0,MY);if(!t0($)){R1=[];return}try{let Z=JSON.parse(c8($,"utf-8"));if(Z.version!==OY){R1=[];return}R1=Z.checksums||[]}catch{R1=[]}}function JV(){if(!e0)return;let $=T0(e0,MY),Z={checksums:R1,version:OY},Y=T0(e0,`.vault-${NY().slice(0,8)}.tmp`);Y2(Y,JSON.stringify(Z,null,2)),WY(Y,$)}function XV($){try{let Z=ZV(e0,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function o8(){let $=[],Z=0;for(let Y of l8){let Q=T0(e0,Y),z=t0(Q);if(!z){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let J=0,X="";try{let V=$V(Q);J=V.size,X=V.mtime.toISOString()}catch{}let K=R1.find((V)=>V.file===Y),G=null;if(K)try{let V=c8(Q,"utf-8");if(G=FY(V)===K.sha256,!G)Z++}catch{G=!1,Z++}$.push({file:Y,exists:z,checksumValid:G,size:J,lastModified:X})}return{files:$,lastBackup:i7,backupEnabled:l1,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function i8($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${l8.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
8
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 o8(){if(!t0)return"Error: vault not initialized.";if(!s0(G0))p7(G0,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
10
- `);if(Z2(A0(G0,".gitignore"),$),!s0(A0(G0,".git"))){let Z=await R1(["git","init","-b",qY],G0);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await R1(["git","config","user.email","vault@smolerclaw.local"],G0),await R1(["git","config","user.name","smolerclaw-vault"],G0)}return c1=!0,"Shadow backup inicializado."}async function C$($){if(!c1)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let K of d8){let G=A0(t0,K);if(!s0(G))continue;let V=A0(G0,K),q=XY(V);if(!s0(q))p7(q,{recursive:!0});Z2(V,p8(G,"utf-8"))}let Y=A0(UY,"config.json");if(s0(Y))Z2(A0(G0,"config.json"),p8(Y,"utf-8"));if(await R1(["git","add","-A"],G0),!(await R1(["git","status","--porcelain"],G0)).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 R1(["git","commit","-m",z],G0);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}`}d7=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 i8(){if(!c1)return"Backup nao ativado.";if(!(await R1(["git","remote","-v"],G0)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await R1(["git","push","-u","origin",qY],G0);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function uG(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:G0,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function R1($,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 BY($=30){if(l7(),!c1)return;m8=setInterval(()=>{C$("auto-backup").catch(()=>{})},$*60*1000)}function l7(){if(m8)clearInterval(m8),m8=null}var GY=1,VY="vault-checksums.json",qY="smolerclaw-backup",d8,t0="",UY="",E1,G0="",c1=!1,d7=null,c7=!1,m8=null;var u=B$(()=>{d0();d8=["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"],E1=[]});var a6={};p9(a6,{searchInvestigations:()=>o6,openInvestigation:()=>u6,listInvestigations:()=>l6,initInvestigations:()=>g6,getInvestigation:()=>c6,generateReport:()=>i6,formatInvestigationList:()=>X5,formatInvestigationDetail:()=>r6,formatEvidenceDetail:()=>KU,collectEvidence:()=>m6,closeInvestigation:()=>d6,addFinding:()=>p6});import{existsSync as Kz,mkdirSync as YU,readFileSync as QU}from"fs";import{join as zU}from"path";import{randomUUID as JU}from"crypto";function J5(){A(Vz(),JSON.stringify(W0,null,2))}function XU(){let $=Vz();if(!Kz($)){W0=[];return}try{W0=JSON.parse(QU($,"utf-8"))}catch{W0=[]}}function g6($){if(Gz=$,!Kz($))YU($,{recursive:!0});XU()}function u6($,Z,Y,Q=[]){let z=new Date().toISOString(),J={id:n6(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((X)=>X.toLowerCase()),evidence:[],findings:[],created:z,updated:z};return W0=[...W0,J],J5(),J}function m6($,Z,Y,Q,z){let J=Q8($);if(!J)return null;let X=Q.trim();if(X.length>Xz)X=X.slice(0,Xz)+`
11
- ...(truncated, ${Q.length} total chars)`;let K={id:n6(),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 W0=W0.map((V)=>V.id===J.id?G:V),J5(),K}function p6($,Z,Y,Q,z=[]){let J=Q8($);if(!J)return null;let X=z.filter((V)=>J.evidence.some((q)=>q.id===V)),K={id:n6(),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 W0=W0.map((V)=>V.id===J.id?G:V),J5(),K}function d6($,Z,Y){let Q=Q8($);if(!Q)return null;let z={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return W0=W0.map((J)=>J.id===Q.id?z:J),J5(),z}function c6($){return Q8($)}function l6($,Z,Y=20){let Q=[...W0];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 o6($){let Z=$.toLowerCase();return W0.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 i6($){let Z=Q8($);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=Uz(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 X5($){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=qz(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}):
9
+ `)}async function n8(){if(!e0)return"Error: vault not initialized.";if(!t0(V0))o7(V0,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
10
+ `);if(Y2(T0(V0,".gitignore"),$),!t0(T0(V0,".git"))){let Z=await F1(["git","init","-b",CY],V0);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await F1(["git","config","user.email","vault@smolerclaw.local"],V0),await F1(["git","config","user.name","smolerclaw-vault"],V0)}return l1=!0,"Shadow backup inicializado."}async function C$($){if(!l1)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let K of l8){let G=T0(e0,K);if(!t0(G))continue;let V=T0(V0,K),U=BY(V);if(!t0(U))o7(U,{recursive:!0});Y2(V,c8(G,"utf-8"))}let Y=T0(EY,"config.json");if(t0(Y))Y2(T0(V0,"config.json"),c8(Y,"utf-8"));if(await F1(["git","add","-A"],V0),!(await F1(["git","status","--porcelain"],V0)).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 e.emit("task:completed",K),"Nenhuma mudanca para backup."}let z=$||`backup ${new Date().toISOString().slice(0,19)}`,J=await F1(["git","commit","-m",z],V0);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 e.emit("task:completed",K),`Backup commit falhou: ${J.stderr}`}i7=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 e.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 e.emit("task:completed",z),`Backup falhou: ${Q}`}}async function r8(){if(!l1)return"Backup nao ativado.";if(!(await F1(["git","remote","-v"],V0)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await F1(["git","push","-u","origin",CY],V0);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function KV(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:V0,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function F1($,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 LY($=30){if(r7(),!l1)return;d8=setInterval(()=>{C$("auto-backup").catch(()=>{})},$*60*1000)}function r7(){if(d8)clearInterval(d8),d8=null}var OY=1,MY="vault-checksums.json",CY="smolerclaw-backup",l8,e0="",EY="",R1,V0="",l1=!1,i7=null,n7=!1,d8=null;var u=N$(()=>{c0();l8=["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"],R1=[]});var YZ={};a9(YZ,{searchInvestigations:()=>t6,openInvestigation:()=>o6,listInvestigations:()=>s6,initInvestigations:()=>l6,getInvestigation:()=>a6,generateReport:()=>e6,formatInvestigationList:()=>G5,formatInvestigationDetail:()=>$Z,formatEvidenceDetail:()=>Iq,collectEvidence:()=>i6,closeInvestigation:()=>r6,addFinding:()=>n6});import{existsSync as Nz,mkdirSync as jq,readFileSync as Pq}from"fs";import{join as Aq}from"path";import{randomUUID as Tq}from"crypto";function K5(){P(Mz(),JSON.stringify(B0,null,2))}function Dq(){let $=Mz();if(!Nz($)){B0=[];return}try{B0=JSON.parse(Pq($,"utf-8"))}catch{B0=[]}}function l6($){if(Oz=$,!Nz($))jq($,{recursive:!0});Dq()}function o6($,Z,Y,Q=[]){let z=new Date().toISOString(),J={id:ZZ(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((X)=>X.toLowerCase()),evidence:[],findings:[],created:z,updated:z};return B0=[...B0,J],K5(),J}function i6($,Z,Y,Q,z){let J=z8($);if(!J)return null;let X=Q.trim();if(X.length>Bz)X=X.slice(0,Bz)+`
11
+ ...(truncated, ${Q.length} total chars)`;let K={id:ZZ(),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 B0=B0.map((V)=>V.id===J.id?G:V),K5(),K}function n6($,Z,Y,Q,z=[]){let J=z8($);if(!J)return null;let X=z.filter((V)=>J.evidence.some((U)=>U.id===V)),K={id:ZZ(),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 B0=B0.map((V)=>V.id===J.id?G:V),K5(),K}function r6($,Z,Y){let Q=z8($);if(!Q)return null;let z={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return B0=B0.map((J)=>J.id===Q.id?z:J),K5(),z}function a6($){return z8($)}function s6($,Z,Y=20){let Q=[...B0];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 t6($){let Z=$.toLowerCase();return B0.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 e6($){let Z=z8($);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=Ez(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 G5($){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=Cz(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 r6($){let Z=(z)=>new Date(z).toLocaleDateString("pt-BR"),Y=qz($.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(`
15
+ `)}`}function $Z($){let Z=(z)=>new Date(z).toLocaleDateString("pt-BR"),Y=Cz($.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
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(` ${Uz(z.severity)} ${z.title}`);if($.summary)Q.push(`
17
+ Conclusoes: ${$.findings.length}`);for(let z of $.findings)Q.push(` ${Ez(z.severity)} ${z.title}`);if($.summary)Q.push(`
18
18
  Resumo: ${$.summary}`);if($.recommendations)Q.push(`Recomendacoes: ${$.recommendations}`);return Q.join(`
19
- `)}function KU($){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 Iq($){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 Q8($){let Z=$.toLowerCase().trim(),Y=W0.find((z)=>z.id===Z);if(Y)return Y;return W0.filter((z)=>z.title.toLowerCase().includes(Z)).sort((z,J)=>new Date(J.updated).getTime()-new Date(z.updated).getTime())[0]||null}function qz($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function Uz($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function n6(){return JU().slice(0,8)}var Gz="",W0,Vz=()=>zU(Gz,"investigations.json"),Xz=50000;var z8=B$(()=>{u();W0=[]});var xJ={};p9(xJ,{openUrl:()=>U1,openFile:()=>X$,openApp:()=>q1,getSystemInfo:()=>K$,getRunningApps:()=>G8,getOutlookEvents:()=>i0,getKnownApps:()=>RZ,getDateTimeInfo:()=>G$});function EZ($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(pH.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function q1($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=MZ[Y];if(!Q){let z=Object.keys(MZ).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=EZ(Z,"argument");if(z)return z}if(!L)return"Error: this command is only available on Windows.";if(!Q.includes(":")){let z=await h8(Q);if(!z.exists)return`Error: ${Q} not found. ${z.error||""}`}try{let z=await g7(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 U1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=EZ($,"URL");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await g7($);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 X$($){let Z=EZ($,"file path");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await t9($);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 G8(){if(!L)return"Error: this command is only available on Windows.";try{let $=await e9(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 K$(){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 K0($.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 G$(){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 i0(){if(!L)return"Outlook integration only available on Windows.";let $=await dH();if($.success)return $.data;let Z=await cH();if(Z.success)return Z.data;return Z.data||$.data||"Calendario nao disponivel."}async function dH(){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 K0($,{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 cH(){try{let Z=await s9(`
21
+ `)}function z8($){let Z=$.toLowerCase().trim(),Y=B0.find((z)=>z.id===Z);if(Y)return Y;return B0.filter((z)=>z.title.toLowerCase().includes(Z)).sort((z,J)=>new Date(J.updated).getTime()-new Date(z.updated).getTime())[0]||null}function Cz($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function Ez($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function ZZ(){return Tq().slice(0,8)}var Oz="",B0,Mz=()=>Aq(Oz,"investigations.json"),Bz=50000;var J8=N$(()=>{u();B0=[]});var cJ={};a9(cJ,{openUrl:()=>H1,openFile:()=>K$,openApp:()=>q1,getSystemInfo:()=>G$,getRunningApps:()=>V8,getOutlookEvents:()=>n0,getKnownApps:()=>TZ,getDateTimeInfo:()=>V$});function AZ($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(VW.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function q1($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=PZ[Y];if(!Q){let z=Object.keys(PZ).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=AZ(Z,"argument");if(z)return z}if(!L)return"Error: this command is only available on Windows.";if(!Q.includes(":")){let z=await u8(Q);if(!z.exists)return`Error: ${Q} not found. ${z.error||""}`}try{let z=await d7(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 H1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=AZ($,"URL");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await d7($);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 K$($){let Z=AZ($,"file path");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await XY($);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 V8(){if(!L)return"Error: this command is only available on Windows.";try{let $=await KY(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 G$(){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 G0($.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 V$(){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 n0(){if(!L)return"Outlook integration only available on Windows.";let $=await UW();if($.success)return $.data;let Z=await qW();if(Z.success)return Z.data;return Z.data||$.data||"Calendario nao disponivel."}async function UW(){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 G0($,{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 qW(){try{let Z=await JY(`
24
24
  try {
25
25
  Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction Stop
26
26
 
@@ -88,7 +88,7 @@ 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 RZ(){return Object.keys(MZ)}var pH,MZ;var v1=B$(()=>{n();p0();pH=/[";`$\n\r|&<>{}()]/;MZ={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 CG}from"fs";import{join as MG,dirname as EG}from"path";function d9($){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)t$("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)t$("--session requires a value");break;case"--max-tokens":let J=Number($[++Q]);if(!J||J<=0)t$("--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"--port":let X=Number($[++Q]);if(!X||X<=0||X>65535)t$("--port requires a valid port number (1-65535)");Z.port=X;break;default:if(z.startsWith("-"))t$(`Unknown option: ${z}. Try --help`);Y.push(z)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function e$(){return"1.6.1"}function c9(){let $=e$();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 TZ(){return Object.keys(PZ)}var VW,PZ;var h1=N$(()=>{a();d0();VW=/[";`$\n\r|&<>{}()]/;PZ={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 hG}from"fs";import{join as gG,dirname as uG}from"path";function s9($){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)e$("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)e$("--session requires a value");break;case"--max-tokens":let J=Number($[++Q]);if(!J||J<=0)e$("--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"--port":let X=Number($[++Q]);if(!X||X<=0||X>65535)e$("--port requires a valid port number (1-65535)");Z.port=X;break;default:if(z.startsWith("-"))e$(`Unknown option: ${z}. Try --help`);Y.push(z)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function $2(){return"1.7.0"}function t9(){let $=$2();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
92
92
 
93
93
  Usage:
94
94
  smolerclaw [command] [options] [prompt]
@@ -123,16 +123,16 @@ Commands (inside TUI):
123
123
  /briefing Daily briefing /news News radar
124
124
  /task Create task /tasks List tasks
125
125
  /open Open Windows app /calendar Outlook calendar
126
- /export Export markdown /exit Quit`)}function t$($){console.error(`smolerclaw: ${$}`),process.exit(2)}n();u();import{existsSync as E$,mkdirSync as mG,readFileSync as NY,readdirSync as OY,copyFileSync as pG}from"fs";import{homedir as dG}from"os";import{join as E0}from"path";var Q2=dG(),F$=L?E0(process.env.APPDATA||E0(Q2,"AppData","Roaming"),"smolerclaw"):E0(Q2,".config","smolerclaw"),o7=L?E0(process.env.LOCALAPPDATA||E0(Q2,"AppData","Local"),"smolerclaw"):E0(Q2,".local","share","smolerclaw"),F1=E0(F$,"config.json"),M$={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:o7,toolApproval:"auto",language:"auto",maxSessionCost:0};function R$($){if(!E$($))mG($,{recursive:!0})}function CY(){if(R$(F$),R$(o7),R$(E0(o7,"sessions")),L)lG();if(!E$(F1))return A(F1,JSON.stringify(M$,null,2)),{...M$};let $;try{$=JSON.parse(NY(F1,"utf-8"))}catch{return A(F1,JSON.stringify(M$,null,2)),{...M$}}return cG({...M$,...$})}function cG($){let Z={...M$};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 r8($){R$(F$),A(F1,JSON.stringify($,null,2))}function n8(){return F1}function i7(){return F$}function lG(){let $=E0(Q2,".config","smolerclaw"),Z=E0($,"config.json");if(E$(Z)&&!E$(F1))try{let Y=NY(Z,"utf-8");R$(F$),A(F1,Y)}catch{}for(let Y of["plugins","materials"]){let Q=E0($,Y),z=E0(F$,Y);if(E$(Q)&&(!E$(z)||oG(z)))try{MY(Q,z)}catch{}}}function oG($){try{return OY($).length===0}catch{return!0}}function MY($,Z){R$(Z);let Y=OY($,{withFileTypes:!0});for(let Q of Y){let z=E0($,Q.name),J=E0(Z,Q.name);if(Q.isDirectory())MY(z,J);else if(Q.isFile())pG(z,J)}}import{existsSync as iG,readFileSync as rG}from"fs";import{homedir as nG}from"os";import{join as aG}from"path";var EY=aG(nG(),".claude",".credentials.json");function r7(){let $=sG();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 sG(){if(!iG(EY))return null;try{let Z=JSON.parse(rG(EY,"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 l1(){try{return r7()}catch{return null}}function RY($){return`sub:${$.subscriptionType||"pro"}`}var a8=[{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 s8($){let Z=a8.find((J)=>J.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=a8.find((J)=>J.alias===Y);if(Q)return Q.id;let z=a8.find((J)=>J.id.includes(Y)||J.name.toLowerCase().includes(Y));if(z)return z.id;return $}function FY($){let Z=["Available models:"];for(let Y of a8){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(`
127
- `)}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 O($,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 n7=function(){let{crypto:$}=globalThis;if($?.randomUUID)return n7=$.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 e0($){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 j extends Error{}class $0 extends j{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 o1({message:Y,cause:z2(Z)});let z=Z;if($===400)return new X2($,z,Y,Q);if($===401)return new K2($,z,Y,Q);if($===403)return new G2($,z,Y,Q);if($===404)return new V2($,z,Y,Q);if($===409)return new q2($,z,Y,Q);if($===422)return new U2($,z,Y,Q);if($===429)return new H2($,z,Y,Q);if($>=500)return new W2($,z,Y,Q);return new $0($,z,Y,Q)}}class H0 extends $0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class o1 extends $0{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class J2 extends o1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class X2 extends $0{}class K2 extends $0{}class G2 extends $0{}class V2 extends $0{}class q2 extends $0{}class U2 extends $0{}class H2 extends $0{}class W2 extends $0{}var eG=/^[a-z][a-z0-9+.-]*:/i,LY=($)=>{return eG.test($)},a7=($)=>(a7=Array.isArray,a7($)),s7=a7;function t8($){if(typeof $!=="object")return{};return $??{}}function t7($){if(!$)return!0;for(let Z in $)return!1;return!0}function jY($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var PY=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new j(`${$} must be an integer`);if(Z<0)throw new j(`${$} must be a positive integer`);return Z};var e8=($)=>{try{return JSON.parse($)}catch(Z){return}};var AY=($)=>new Promise((Z)=>setTimeout(Z,$));var L1="0.80.0";var SY=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function $V(){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 ZV=()=>{let $=$V();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L1,"X-Stainless-OS":TY(Deno.build.os),"X-Stainless-Arch":DY(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":L1,"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":L1,"X-Stainless-OS":TY(globalThis.process.platform??"unknown"),"X-Stainless-Arch":DY(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=YV();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L1,"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":L1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function YV(){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 DY=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},TY=($)=>{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"},IY,wY=()=>{return IY??(IY=ZV())};function kY(){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 e7(...$){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 $4($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return e7({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 B2($){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 fY($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var bY=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function yY($){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 j(`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 vY($){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 _Y;function N2($){let Z;return(_Y??(Z=new globalThis.TextEncoder,_Y=Z.encode.bind(Z)))($)}var xY;function $6($){let Z;return(xY??(Z=new globalThis.TextDecoder,xY=Z.decode.bind(Z)))($)}var D0,T0;class j1{constructor(){D0.set(this,void 0),T0.set(this,void 0),R(this,D0,new Uint8Array,"f"),R(this,T0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?N2($):$;R(this,D0,vY([O(this,D0,"f"),Z]),"f");let Y=[],Q;while((Q=JV(O(this,D0,"f"),O(this,T0,"f")))!=null){if(Q.carriage&&O(this,T0,"f")==null){R(this,T0,Q.index,"f");continue}if(O(this,T0,"f")!=null&&(Q.index!==O(this,T0,"f")+1||Q.carriage)){Y.push($6(O(this,D0,"f").subarray(0,O(this,T0,"f")-1))),R(this,D0,O(this,D0,"f").subarray(O(this,T0,"f")),"f"),R(this,T0,null,"f");continue}let z=O(this,T0,"f")!==null?Q.preceding-1:Q.preceding,J=$6(O(this,D0,"f").subarray(0,z));Y.push(J),R(this,D0,O(this,D0,"f").subarray(Q.index),"f"),R(this,T0,null,"f")}return Y}flush(){if(!O(this,D0,"f").length)return[];return this.decode(`
128
- `)}}D0=new WeakMap,T0=new WeakMap;j1.NEWLINE_CHARS=new Set([`
129
- `,"\r"]);j1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function JV($,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 hY($){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 Y4={off:0,error:200,warn:300,info:400,debug:500},Z6=($,Z,Y)=>{if(!$)return;if(jY(Y4,$))return $;z0(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(Y4))}`);return};function O2(){}function Z4($,Z,Y){if(!Z||Y4[$]>Y4[Y])return O2;else return Z[$].bind(Z)}var XV={error:O2,warn:O2,info:O2,debug:O2},gY=new WeakMap;function z0($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return XV;let Q=gY.get(Z);if(Q&&Q[0]===Y)return Q[1];let z={error:Z4("error",Z,Y),warn:Z4("warn",Z,Y),info:Z4("info",Z,Y),debug:Z4("debug",Z,Y)};return gY.set(Z,[Y,z]),z}var $1=($)=>{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 C2;class I0{constructor($,Z,Y){this.iterator=$,C2.set(this,void 0),this.controller=Z,R(this,C2,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,z=Y?z0(Y):console;async function*J(){if(Q)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of KV($,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,e8(K.data)??K.data,void 0,$.headers)}X=!0}catch(K){if(e0(K))return;throw K}finally{if(!X)Z.abort()}}return new I0(J,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*z(){let X=new j1,K=B2($);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 j("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(e0(K))return;throw K}finally{if(!X)Z.abort()}}return new I0(J,Z,Y)}[(C2=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 I0(()=>Q($),this.controller,O(this,C2,"f")),new I0(()=>Q(Z),this.controller,O(this,C2,"f"))]}toReadableStream(){let $=this,Z;return e7({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:z}=await Z.next();if(z)return Y.close();let J=N2(JSON.stringify(Q)+`
130
- `);Y.enqueue(J)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*KV($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new j("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 j("Attempted to iterate over a response with no body")}let Y=new uY,Q=new j1,z=B2($.body);for await(let J of GV(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*GV($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?N2(Y):Y,z=new Uint8Array(Z.length+Q.length);z.set(Z),z.set(Q,Z.length),Z=z;let J;while((J=hY(Z))!==-1)yield Z.slice(0,J),Z=Z.slice(J)}if(Z.length>0)yield Z}class uY{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(`
131
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],z}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=VV($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function VV($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function Q4($,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 I0.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 Y6(H,Y)}return await Y.text()})();return z0($).debug(`[${Q}] response parsed`,$1({retryOfRequestLogID:z,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-J})),X}function Y6($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var M2;class i1 extends Promise{constructor($,Z,Y=Q4){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,M2.set(this,void 0),R(this,M2,$,"f")}_thenUnwrap($){return new i1(O(this,M2,"f"),this.responsePromise,async(Z,Y)=>Y6($(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(O(this,M2,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}M2=new WeakMap;var z4;class Q6{constructor($,Z,Y,Q){z4.set(this,void 0),R(this,z4,$,"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 j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await O(this,z4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(z4=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class J4 extends i1{constructor($,Z,Y){super($,Z,async(Q,z)=>new Y(Q,z.response,await Q4(Q,z),z.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class u0 extends Q6{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:{...t8(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...t8(this.options.query),after_id:$}}}}class E2 extends Q6{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:{...t8(this.options.query),page:$}}}}var J6=()=>{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 r1($,Z,Y){return J6(),new File($,Z??"unknown_file",Y)}function R2($,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 X6=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var L$=async($,Z,Y=!0)=>{return{...$,body:await HV($.body,Z,Y)}},mY=new WeakMap;function UV($){let Z=typeof $==="function"?$:$.fetch,Y=mY.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 mY.set(Z,Q),Q}var HV=async($,Z,Y=!0)=>{if(!await UV(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])=>z6(Q,z,J,Y))),Q},WV=($)=>$ instanceof Blob&&("name"in $);var z6=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,r1([await Y.blob()],R2(Y,Q),z))}else if(X6(Y))$.append(Z,r1([await new Response($4(Y)).blob()],R2(Y,Q)));else if(WV(Y))$.append(Z,r1([Y],R2(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((z)=>z6($,Z+"[]",z,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([z,J])=>z6($,`${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 pY=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",BV=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&pY($),NV=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function X4($,Z,Y){if(J6(),$=await $,Z||(Z=R2($,!0)),BV($)){if($ instanceof File&&Z==null&&Y==null)return $;return r1([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(NV($)){let z=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),r1(await K6(z),Z,Y)}let Q=await K6($);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 r1(Q,Z,Y)}async function K6($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(pY($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(X6($))for await(let Y of $)Z.push(...await K6(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${OV($)}`)}return Z}function OV($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class o{constructor($){this._client=$}}var dY=Symbol.for("brand.privateNullableHeaders");function*MV($){if(!$)return;if(dY 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(s7($))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=s7(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 MV(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{[dY]:!0,values:Z,nulls:Y}};var F2=Symbol("anthropic.sdk.stainlessHelper");function K4($){return typeof $==="object"&&$!==null&&F2 in $}function G6($,Z){let Y=new Set;if($){for(let Q of $)if(K4(Q))Y.add(Q[F2])}if(Z)for(let Q of Z){if(K4(Q))Y.add(Q[F2]);if(Array.isArray(Q.content)){for(let z of Q.content)if(K4(z))Y.add(z[F2])}}return Array.from(Y)}function G4($,Z){let Y=G6($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function cY($){if(K4($))return{"x-stainless-helper":$[F2]};return{}}function oY($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var lY=Object.freeze(Object.create(null)),EV=($=oY)=>function(Y,...Q){if(Y.length===1)return Y[0];let z=!1,J=[],X=Y.reduce((q,U,H)=>{if(/[?#]/.test(U))z=!0;let B=Q[H],N=(z?encodeURIComponent:$)(""+B);if(H!==Q.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??lY)??lY)?.toString))N=B+"",J.push({start:q.length+U.length,length:N.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return q+U+(H===Q.length?"":N)},""),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((q,U)=>q.start-U.start),J.length>0){let q=0,U=J.reduce((H,B)=>{let N=" ".repeat(B.start-q),C="^".repeat(B.length);return q=B.start+B.length,H+N+C},"");throw new j(`Path parameters result in path with invalid segments:
126
+ /export Export markdown /exit Quit`)}function e$($){console.error(`smolerclaw: ${$}`),process.exit(2)}a();u();import{existsSync as R$,mkdirSync as GV,readFileSync as jY,readdirSync as PY,copyFileSync as VV}from"fs";import{homedir as UV}from"os";import{join as R0}from"path";var z2=UV(),L$=L?R0(process.env.APPDATA||R0(z2,"AppData","Roaming"),"smolerclaw"):R0(z2,".config","smolerclaw"),a7=L?R0(process.env.LOCALAPPDATA||R0(z2,"AppData","Local"),"smolerclaw"):R0(z2,".local","share","smolerclaw"),L1=R0(L$,"config.json"),E$={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:a7,toolApproval:"auto",language:"auto",maxSessionCost:0};function F$($){if(!R$($))GV($,{recursive:!0})}function AY(){if(F$(L$),F$(a7),F$(R0(a7,"sessions")),L)HV();if(!R$(L1))return P(L1,JSON.stringify(E$,null,2)),{...E$};let $;try{$=JSON.parse(jY(L1,"utf-8"))}catch{return P(L1,JSON.stringify(E$,null,2)),{...E$}}return qV({...E$,...$})}function qV($){let Z={...E$};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 a8($){F$(L$),P(L1,JSON.stringify($,null,2))}function s8(){return L1}function s7(){return L$}function HV(){let $=R0(z2,".config","smolerclaw"),Z=R0($,"config.json");if(R$(Z)&&!R$(L1))try{let Y=jY(Z,"utf-8");F$(L$),P(L1,Y)}catch{}for(let Y of["plugins","materials"]){let Q=R0($,Y),z=R0(L$,Y);if(R$(Q)&&(!R$(z)||WV(z)))try{TY(Q,z)}catch{}}}function WV($){try{return PY($).length===0}catch{return!0}}function TY($,Z){F$(Z);let Y=PY($,{withFileTypes:!0});for(let Q of Y){let z=R0($,Q.name),J=R0(Z,Q.name);if(Q.isDirectory())TY(z,J);else if(Q.isFile())VV(z,J)}}import{existsSync as BV,readFileSync as NV}from"fs";import{homedir as OV}from"os";import{join as MV}from"path";var DY=MV(OV(),".claude",".credentials.json");function t7(){let $=CV();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 CV(){if(!BV(DY))return null;try{let Z=JSON.parse(NV(DY,"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 o1(){try{return t7()}catch{return null}}function IY($){return`sub:${$.subscriptionType||"pro"}`}var t8=[{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 e8($){let Z=t8.find((J)=>J.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=t8.find((J)=>J.alias===Y);if(Q)return Q.id;let z=t8.find((J)=>J.id.includes(Y)||J.name.toLowerCase().includes(Y));if(z)return z.id;return $}function SY($){let Z=["Available models:"];for(let Y of t8){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(`
127
+ `)}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 O($,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 e7=function(){let{crypto:$}=globalThis;if($?.randomUUID)return e7=$.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 $1($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var J2=($)=>{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 j extends Error{}class Z0 extends j{constructor($,Z,Y,Q){super(`${Z0.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 i1({message:Y,cause:J2(Z)});let z=Z;if($===400)return new K2($,z,Y,Q);if($===401)return new G2($,z,Y,Q);if($===403)return new V2($,z,Y,Q);if($===404)return new U2($,z,Y,Q);if($===409)return new q2($,z,Y,Q);if($===422)return new H2($,z,Y,Q);if($===429)return new W2($,z,Y,Q);if($>=500)return new B2($,z,Y,Q);return new Z0($,z,Y,Q)}}class W0 extends Z0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class i1 extends Z0{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class X2 extends i1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class K2 extends Z0{}class G2 extends Z0{}class V2 extends Z0{}class U2 extends Z0{}class q2 extends Z0{}class H2 extends Z0{}class W2 extends Z0{}class B2 extends Z0{}var RV=/^[a-z][a-z0-9+.-]*:/i,wY=($)=>{return RV.test($)},$6=($)=>($6=Array.isArray,$6($)),Z6=$6;function $4($){if(typeof $!=="object")return{};return $??{}}function Y6($){if(!$)return!0;for(let Z in $)return!1;return!0}function kY($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var fY=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new j(`${$} must be an integer`);if(Z<0)throw new j(`${$} must be a positive integer`);return Z};var Z4=($)=>{try{return JSON.parse($)}catch(Z){return}};var bY=($)=>new Promise((Z)=>setTimeout(Z,$));var j1="0.80.0";var vY=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function FV(){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 LV=()=>{let $=FV();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j1,"X-Stainless-OS":_Y(Deno.build.os),"X-Stainless-Arch":yY(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":j1,"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":j1,"X-Stainless-OS":_Y(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yY(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=jV();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j1,"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":j1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function jV(){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 yY=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},_Y=($)=>{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"},xY,hY=()=>{return xY??(xY=LV())};function gY(){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 Q6(...$){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 Y4($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return Q6({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 N2($){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 uY($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var mY=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function pY($){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 j(`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 lY($){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 dY;function O2($){let Z;return(dY??(Z=new globalThis.TextEncoder,dY=Z.encode.bind(Z)))($)}var cY;function z6($){let Z;return(cY??(Z=new globalThis.TextDecoder,cY=Z.decode.bind(Z)))($)}var D0,I0;class P1{constructor(){D0.set(this,void 0),I0.set(this,void 0),R(this,D0,new Uint8Array,"f"),R(this,I0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?O2($):$;R(this,D0,lY([O(this,D0,"f"),Z]),"f");let Y=[],Q;while((Q=TV(O(this,D0,"f"),O(this,I0,"f")))!=null){if(Q.carriage&&O(this,I0,"f")==null){R(this,I0,Q.index,"f");continue}if(O(this,I0,"f")!=null&&(Q.index!==O(this,I0,"f")+1||Q.carriage)){Y.push(z6(O(this,D0,"f").subarray(0,O(this,I0,"f")-1))),R(this,D0,O(this,D0,"f").subarray(O(this,I0,"f")),"f"),R(this,I0,null,"f");continue}let z=O(this,I0,"f")!==null?Q.preceding-1:Q.preceding,J=z6(O(this,D0,"f").subarray(0,z));Y.push(J),R(this,D0,O(this,D0,"f").subarray(Q.index),"f"),R(this,I0,null,"f")}return Y}flush(){if(!O(this,D0,"f").length)return[];return this.decode(`
128
+ `)}}D0=new WeakMap,I0=new WeakMap;P1.NEWLINE_CHARS=new Set([`
129
+ `,"\r"]);P1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function TV($,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 oY($){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 z4={off:0,error:200,warn:300,info:400,debug:500},J6=($,Z,Y)=>{if(!$)return;if(kY(z4,$))return $;J0(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(z4))}`);return};function M2(){}function Q4($,Z,Y){if(!Z||z4[$]>z4[Y])return M2;else return Z[$].bind(Z)}var DV={error:M2,warn:M2,info:M2,debug:M2},iY=new WeakMap;function J0($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return DV;let Q=iY.get(Z);if(Q&&Q[0]===Y)return Q[1];let z={error:Q4("error",Z,Y),warn:Q4("warn",Z,Y),info:Q4("info",Z,Y),debug:Q4("debug",Z,Y)};return iY.set(Z,[Y,z]),z}var Z1=($)=>{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 C2;class S0{constructor($,Z,Y){this.iterator=$,C2.set(this,void 0),this.controller=Z,R(this,C2,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,z=Y?J0(Y):console;async function*J(){if(Q)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of IV($,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 Z0(void 0,Z4(K.data)??K.data,void 0,$.headers)}X=!0}catch(K){if($1(K))return;throw K}finally{if(!X)Z.abort()}}return new S0(J,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*z(){let X=new P1,K=N2($);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 j("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($1(K))return;throw K}finally{if(!X)Z.abort()}}return new S0(J,Z,Y)}[(C2=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 S0(()=>Q($),this.controller,O(this,C2,"f")),new S0(()=>Q(Z),this.controller,O(this,C2,"f"))]}toReadableStream(){let $=this,Z;return Q6({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:z}=await Z.next();if(z)return Y.close();let J=O2(JSON.stringify(Q)+`
130
+ `);Y.enqueue(J)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*IV($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new j("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 j("Attempted to iterate over a response with no body")}let Y=new nY,Q=new P1,z=N2($.body);for await(let J of SV(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*SV($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?O2(Y):Y,z=new Uint8Array(Z.length+Q.length);z.set(Z),z.set(Q,Z.length),Z=z;let J;while((J=oY(Z))!==-1)yield Z.slice(0,J),Z=Z.slice(J)}if(Z.length>0)yield Z}class nY{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(`
131
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],z}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=wV($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function wV($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function J4($,Z){let{response:Y,requestLogID:Q,retryOfRequestLogID:z,startTime:J}=Z,X=await(async()=>{if(Z.options.stream){if(J0($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return S0.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 X6(H,Y)}return await Y.text()})();return J0($).debug(`[${Q}] response parsed`,Z1({retryOfRequestLogID:z,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-J})),X}function X6($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var E2;class n1 extends Promise{constructor($,Z,Y=J4){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,E2.set(this,void 0),R(this,E2,$,"f")}_thenUnwrap($){return new n1(O(this,E2,"f"),this.responsePromise,async(Z,Y)=>X6($(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(O(this,E2,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}E2=new WeakMap;var X4;class K6{constructor($,Z,Y,Q){X4.set(this,void 0),R(this,X4,$,"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 j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await O(this,X4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(X4=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class K4 extends n1{constructor($,Z,Y){super($,Z,async(Q,z)=>new Y(Q,z.response,await J4(Q,z),z.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class m0 extends K6{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:{...$4(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...$4(this.options.query),after_id:$}}}}class R2 extends K6{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:{...$4(this.options.query),page:$}}}}var V6=()=>{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 r1($,Z,Y){return V6(),new File($,Z??"unknown_file",Y)}function F2($,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 U6=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var j$=async($,Z,Y=!0)=>{return{...$,body:await bV($.body,Z,Y)}},rY=new WeakMap;function fV($){let Z=typeof $==="function"?$:$.fetch,Y=rY.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 rY.set(Z,Q),Q}var bV=async($,Z,Y=!0)=>{if(!await fV(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])=>G6(Q,z,J,Y))),Q},yV=($)=>$ instanceof Blob&&("name"in $);var G6=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,r1([await Y.blob()],F2(Y,Q),z))}else if(U6(Y))$.append(Z,r1([await new Response(Y4(Y)).blob()],F2(Y,Q)));else if(yV(Y))$.append(Z,r1([Y],F2(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((z)=>G6($,Z+"[]",z,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([z,J])=>G6($,`${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 aY=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",_V=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&aY($),xV=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function G4($,Z,Y){if(V6(),$=await $,Z||(Z=F2($,!0)),_V($)){if($ instanceof File&&Z==null&&Y==null)return $;return r1([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(xV($)){let z=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),r1(await q6(z),Z,Y)}let Q=await q6($);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 r1(Q,Z,Y)}async function q6($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(aY($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(U6($))for await(let Y of $)Z.push(...await q6(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${vV($)}`)}return Z}function vV($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class i{constructor($){this._client=$}}var sY=Symbol.for("brand.privateNullableHeaders");function*gV($){if(!$)return;if(sY 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(Z6($))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=Z6(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 D=($)=>{let Z=new Headers,Y=new Set;for(let Q of $){let z=new Set;for(let[J,X]of gV(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{[sY]:!0,values:Z,nulls:Y}};var L2=Symbol("anthropic.sdk.stainlessHelper");function V4($){return typeof $==="object"&&$!==null&&L2 in $}function H6($,Z){let Y=new Set;if($){for(let Q of $)if(V4(Q))Y.add(Q[L2])}if(Z)for(let Q of Z){if(V4(Q))Y.add(Q[L2]);if(Array.isArray(Q.content)){for(let z of Q.content)if(V4(z))Y.add(z[L2])}}return Array.from(Y)}function U4($,Z){let Y=H6($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function tY($){if(V4($))return{"x-stainless-helper":$[L2]};return{}}function $Q($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var eY=Object.freeze(Object.create(null)),uV=($=$Q)=>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],N=(z?encodeURIComponent:$)(""+B);if(H!==Q.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??eY)??eY)?.toString))N=B+"",J.push({start:U.length+q.length,length:N.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?"":N)},""),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 N=" ".repeat(B.start-U),M="^".repeat(B.length);return U=B.start+B.length,H+N+M},"");throw new j(`Path parameters result in path with invalid segments:
132
132
  ${J.map((H)=>H.error).join(`
133
133
  `)}
134
134
  ${X}
135
- ${U}`)}return X},l=EV(oY);class L2 extends o{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",u0,{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(l`/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(l`/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(l`/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",L$({body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},cY(Q.file),Z?.headers])},this._client))}}class j2 extends o{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(l`/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",u0,{query:Q,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var V4={"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 iY($){return $?.output_format??$?.output_config?.format}function V6($,Z,Y){let Q=iY(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 q6($,Z,Y)}function q6($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=LV(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 LV($,Z){let Y=iY($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new j(`Failed to parse structured output: ${Q}`)}}var jV=($)=>{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},j$=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),j$($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),j$($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),j$($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),j$($);break;case"delimiter":return $=$.slice(0,$.length-1),j$($);break}return $},PV=($)=>{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 $},AV=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},q4=($)=>JSON.parse(AV(PV(j$(jV($)))));var b0,P1,P$,P2,U4,A2,D2,H4,T2,Z1,I2,W4,B4,n1,N4,O4,S2,U6,rY,C4,H6,W6,B6,nY,aY="__json_buf";function sY($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class w2{constructor($,Z){b0.add(this),this.messages=[],this.receivedMessages=[],P1.set(this,void 0),P$.set(this,null),this.controller=new AbortController,P2.set(this,void 0),U4.set(this,()=>{}),A2.set(this,()=>{}),D2.set(this,void 0),H4.set(this,()=>{}),T2.set(this,()=>{}),Z1.set(this,{}),I2.set(this,!1),W4.set(this,!1),B4.set(this,!1),n1.set(this,!1),N4.set(this,void 0),O4.set(this,void 0),S2.set(this,void 0),C4.set(this,(Y)=>{if(R(this,W4,!0,"f"),e0(Y))Y=new H0;if(Y instanceof H0)return R(this,B4,!0,"f"),this._emit("abort",Y);if(Y instanceof j)return this._emit("error",Y);if(Y instanceof Error){let Q=new j(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new j(String(Y)))}),R(this,P2,new Promise((Y,Q)=>{R(this,U4,Y,"f"),R(this,A2,Q,"f")}),"f"),R(this,D2,new Promise((Y,Q)=>{R(this,H4,Y,"f"),R(this,T2,Q,"f")}),"f"),O(this,P2,"f").catch(()=>{}),O(this,D2,"f").catch(()=>{}),R(this,P$,$,"f"),R(this,S2,Z?.logger??console,"f")}get response(){return O(this,N4,"f")}get request_id(){return O(this,O4,"f")}async withResponse(){R(this,n1,!0,"f");let $=await O(this,P2,"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 w2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new w2(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return R(z,P$,{...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")},O(this,C4,"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{O(this,b0,"m",H6).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)O(this,b0,"m",W6).call(this,K);if(X.controller.signal?.aborted)throw new H0;O(this,b0,"m",B6).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;R(this,N4,$,"f"),R(this,O4,$?.headers.get("request-id"),"f"),O(this,U4,"f").call(this,$),this._emit("connect")}get ended(){return O(this,I2,"f")}get errored(){return O(this,W4,"f")}get aborted(){return O(this,B4,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,Z1,"f")[$]||(O(this,Z1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,Z1,"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(O(this,Z1,"f")[$]||(O(this,Z1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,n1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,n1,!0,"f"),await O(this,D2,"f")}get currentMessage(){return O(this,P1,"f")}async finalMessage(){return await this.done(),O(this,b0,"m",U6).call(this)}async finalText(){return await this.done(),O(this,b0,"m",rY).call(this)}_emit($,...Z){if(O(this,I2,"f"))return;if($==="end")R(this,I2,!0,"f"),O(this,H4,"f").call(this);let Y=O(this,Z1,"f")[$];if(Y)O(this,Z1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,n1,"f")&&!Y?.length)Promise.reject(Q);O(this,A2,"f").call(this,Q),O(this,T2,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,n1,"f")&&!Y?.length)Promise.reject(Q);O(this,A2,"f").call(this,Q),O(this,T2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,b0,"m",U6).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{O(this,b0,"m",H6).call(this),this._connected(null);let z=I0.fromReadableStream($,this.controller);for await(let J of z)O(this,b0,"m",W6).call(this,J);if(z.controller.signal?.aborted)throw new H0;O(this,b0,"m",B6).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(P1=new WeakMap,P$=new WeakMap,P2=new WeakMap,U4=new WeakMap,A2=new WeakMap,D2=new WeakMap,H4=new WeakMap,T2=new WeakMap,Z1=new WeakMap,I2=new WeakMap,W4=new WeakMap,B4=new WeakMap,n1=new WeakMap,N4=new WeakMap,O4=new WeakMap,S2=new WeakMap,C4=new WeakMap,b0=new WeakSet,U6=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},rY=function(){if(this.receivedMessages.length===0)throw new j("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 j("stream ended without producing a content block with type=text");return Z.join(" ")},H6=function(){if(this.ended)return;R(this,P1,void 0,"f")},W6=function(Z){if(this.ended)return;let Y=O(this,b0,"m",nY).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(sY(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:tY(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(V6(Y,O(this,P$,"f"),{logger:O(this,S2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,P1,Y,"f");break}case"content_block_start":case"message_delta":break}},B6=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let Z=O(this,P1,"f");if(!Z)throw new j("request ended without sending any chunks");return R(this,P1,void 0,"f"),V6(Z,O(this,P$,"f"),{logger:O(this,S2,"f")})},nY=function(Z){let Y=O(this,P1,"f");if(Z.type==="message_start"){if(Y)throw new j(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new j(`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&&sY(Q)){let z=Q[aY]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,aY,{value:z,enumerable:!1,writable:!0}),z)try{J.input=q4(z)}catch(X){let K=new j(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${X}. JSON: ${z}`);O(this,C4,"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:tY(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 I0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function tY($){}class A$ 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 eY=1e5,$Q=`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:
135
+ ${q}`)}return X},o=uV($Q);class j2 extends i{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",m0,{query:Q,...Z,headers:D([{"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:D([{"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:D([{"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:D([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/files",j$({body:Q,...Z,headers:D([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},tY(Q.file),Z?.headers])},this._client))}}class P2 extends i{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/models/${$}?beta=true`,{...Y,headers:D([{...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",m0,{query:Q,...Z,headers:D([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var q4={"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 ZQ($){return $?.output_format??$?.output_config?.format}function W6($,Z,Y){let Q=ZQ(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 B6($,Z,Y)}function B6($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=dV(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 dV($,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 j(`Failed to parse structured output: ${Q}`)}}var cV=($)=>{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},P$=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),P$($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),P$($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),P$($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),P$($);break;case"delimiter":return $=$.slice(0,$.length-1),P$($);break}return $},lV=($)=>{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 $},oV=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},H4=($)=>JSON.parse(oV(lV(P$(cV($)))));var y0,A1,A$,A2,W4,T2,D2,B4,I2,Y1,S2,N4,O4,a1,M4,C4,w2,N6,YQ,E4,O6,M6,C6,QQ,zQ="__json_buf";function JQ($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class k2{constructor($,Z){y0.add(this),this.messages=[],this.receivedMessages=[],A1.set(this,void 0),A$.set(this,null),this.controller=new AbortController,A2.set(this,void 0),W4.set(this,()=>{}),T2.set(this,()=>{}),D2.set(this,void 0),B4.set(this,()=>{}),I2.set(this,()=>{}),Y1.set(this,{}),S2.set(this,!1),N4.set(this,!1),O4.set(this,!1),a1.set(this,!1),M4.set(this,void 0),C4.set(this,void 0),w2.set(this,void 0),E4.set(this,(Y)=>{if(R(this,N4,!0,"f"),$1(Y))Y=new W0;if(Y instanceof W0)return R(this,O4,!0,"f"),this._emit("abort",Y);if(Y instanceof j)return this._emit("error",Y);if(Y instanceof Error){let Q=new j(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new j(String(Y)))}),R(this,A2,new Promise((Y,Q)=>{R(this,W4,Y,"f"),R(this,T2,Q,"f")}),"f"),R(this,D2,new Promise((Y,Q)=>{R(this,B4,Y,"f"),R(this,I2,Q,"f")}),"f"),O(this,A2,"f").catch(()=>{}),O(this,D2,"f").catch(()=>{}),R(this,A$,$,"f"),R(this,w2,Z?.logger??console,"f")}get response(){return O(this,M4,"f")}get request_id(){return O(this,C4,"f")}async withResponse(){R(this,a1,!0,"f");let $=await O(this,A2,"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 k2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new k2(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return R(z,A$,{...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")},O(this,E4,"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{O(this,y0,"m",O6).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)O(this,y0,"m",M6).call(this,K);if(X.controller.signal?.aborted)throw new W0;O(this,y0,"m",C6).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;R(this,M4,$,"f"),R(this,C4,$?.headers.get("request-id"),"f"),O(this,W4,"f").call(this,$),this._emit("connect")}get ended(){return O(this,S2,"f")}get errored(){return O(this,N4,"f")}get aborted(){return O(this,O4,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,Y1,"f")[$]||(O(this,Y1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(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(O(this,Y1,"f")[$]||(O(this,Y1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,a1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,a1,!0,"f"),await O(this,D2,"f")}get currentMessage(){return O(this,A1,"f")}async finalMessage(){return await this.done(),O(this,y0,"m",N6).call(this)}async finalText(){return await this.done(),O(this,y0,"m",YQ).call(this)}_emit($,...Z){if(O(this,S2,"f"))return;if($==="end")R(this,S2,!0,"f"),O(this,B4,"f").call(this);let Y=O(this,Y1,"f")[$];if(Y)O(this,Y1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,a1,"f")&&!Y?.length)Promise.reject(Q);O(this,T2,"f").call(this,Q),O(this,I2,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,a1,"f")&&!Y?.length)Promise.reject(Q);O(this,T2,"f").call(this,Q),O(this,I2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,y0,"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{O(this,y0,"m",O6).call(this),this._connected(null);let z=S0.fromReadableStream($,this.controller);for await(let J of z)O(this,y0,"m",M6).call(this,J);if(z.controller.signal?.aborted)throw new W0;O(this,y0,"m",C6).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(A1=new WeakMap,A$=new WeakMap,A2=new WeakMap,W4=new WeakMap,T2=new WeakMap,D2=new WeakMap,B4=new WeakMap,I2=new WeakMap,Y1=new WeakMap,S2=new WeakMap,N4=new WeakMap,O4=new WeakMap,a1=new WeakMap,M4=new WeakMap,C4=new WeakMap,w2=new WeakMap,E4=new WeakMap,y0=new WeakSet,N6=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},YQ=function(){if(this.receivedMessages.length===0)throw new j("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 j("stream ended without producing a content block with type=text");return Z.join(" ")},O6=function(){if(this.ended)return;R(this,A1,void 0,"f")},M6=function(Z){if(this.ended)return;let Y=O(this,y0,"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}case"compaction_delta":{if(Q.type==="compaction"&&Q.content)this._emit("compaction",Q.content);break}default:XQ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(W6(Y,O(this,A$,"f"),{logger:O(this,w2,"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}},C6=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let Z=O(this,A1,"f");if(!Z)throw new j("request ended without sending any chunks");return R(this,A1,void 0,"f"),W6(Z,O(this,A$,"f"),{logger:O(this,w2,"f")})},QQ=function(Z){let Y=O(this,A1,"f");if(Z.type==="message_start"){if(Y)throw new j(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new j(`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&&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)try{J.input=H4(z)}catch(X){let K=new j(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${X}. JSON: ${z}`);O(this,E4,"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: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 S0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function XQ($){}class T$ 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 KQ=1e5,GQ=`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:
136
136
  1. Task Overview
137
137
  The user's core request and success criteria
138
138
  Any clarifications or constraints they specified
@@ -154,44 +154,47 @@ User preferences or style requirements
154
154
  Domain-specific details that aren't obvious
155
155
  Any promises made to the user
156
156
  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.
157
- Wrap your summary in <summary></summary> tags.`;var k2,D$,a1,Z0,f2,S0,Y1,A1,b2,ZQ,N6;function YQ(){let $,Z;return{promise:new Promise((Q,z)=>{$=Q,Z=z}),resolve:$,reject:Z}}class y2{constructor($,Z,Y){k2.add(this),this.client=$,D$.set(this,!1),a1.set(this,!1),Z0.set(this,void 0),f2.set(this,void 0),S0.set(this,void 0),Y1.set(this,void 0),A1.set(this,void 0),b2.set(this,0),R(this,Z0,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let z=["BetaToolRunner",...G6(Z.tools,Z.messages)].join(", ");R(this,f2,{...Y,headers:T([{"x-stainless-helper":z},Y?.headers])},"f"),R(this,A1,YQ(),"f")}async*[(D$=new WeakMap,a1=new WeakMap,Z0=new WeakMap,f2=new WeakMap,S0=new WeakMap,Y1=new WeakMap,A1=new WeakMap,b2=new WeakMap,k2=new WeakSet,ZQ=async function(){let Z=O(this,Z0,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(O(this,S0,"f")!==void 0)try{let G=await O(this,S0,"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??eY;if(Y<Q)return!1;let z=Z.model??O(this,Z0,"f").params.model,J=Z.summaryPrompt??$Q,X=O(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((q)=>q.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:O(this,Z0,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(K.content[0]?.type!=="text")throw new j("Expected text response for compaction");return O(this,Z0,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(O(this,D$,"f"))throw new j("Cannot iterate over a consumed stream");R(this,D$,!0,"f"),R(this,a1,!0,"f"),R(this,Y1,void 0,"f");try{while(!0){let Z;try{if(O(this,Z0,"f").params.max_iterations&&O(this,b2,"f")>=O(this,Z0,"f").params.max_iterations)break;R(this,a1,!1,"f"),R(this,Y1,void 0,"f"),R(this,b2,($=O(this,b2,"f"),$++,$),"f"),R(this,S0,void 0,"f");let{max_iterations:Y,compactionControl:Q,...z}=O(this,Z0,"f").params;if(z.stream)Z=this.client.beta.messages.stream({...z},O(this,f2,"f")),R(this,S0,Z.finalMessage(),"f"),O(this,S0,"f").catch(()=>{}),yield Z;else R(this,S0,this.client.beta.messages.create({...z,stream:!1},O(this,f2,"f")),"f"),yield O(this,S0,"f");if(!await O(this,k2,"m",ZQ).call(this)){if(!O(this,a1,"f")){let{role:K,content:G}=await O(this,S0,"f");O(this,Z0,"f").params.messages.push({role:K,content:G})}let X=await O(this,k2,"m",N6).call(this,O(this,Z0,"f").params.messages.at(-1));if(X)O(this,Z0,"f").params.messages.push(X);else if(!O(this,a1,"f"))break}}finally{if(Z)Z.abort()}}if(!O(this,S0,"f"))throw new j("ToolRunner concluded without a message from the server");O(this,A1,"f").resolve(await O(this,S0,"f"))}catch(Z){throw R(this,D$,!1,"f"),O(this,A1,"f").promise.catch(()=>{}),O(this,A1,"f").reject(Z),R(this,A1,YQ(),"f"),Z}}setMessagesParams($){if(typeof $==="function")O(this,Z0,"f").params=$(O(this,Z0,"f").params);else O(this,Z0,"f").params=$;R(this,a1,!0,"f"),R(this,Y1,void 0,"f")}async generateToolResponse(){let $=await O(this,S0,"f")??this.params.messages.at(-1);if(!$)return null;return O(this,k2,"m",N6).call(this,$)}done(){return O(this,A1,"f").promise}async runUntilDone(){if(!O(this,D$,"f"))for await(let $ of this);return this.done()}get params(){return O(this,Z0,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}N6=async function(Z){if(O(this,Y1,"f")!==void 0)return O(this,Y1,"f");return R(this,Y1,DV(O(this,Z0,"f").params,Z),"f"),O(this,Y1,"f")};async function DV($,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 A$?X.content:`Error: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}))}}class T${constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new j1;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 j("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 j("Attempted to iterate over a response with no body")}return new T$(B2($.body),Z)}}class _2 extends o{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(l`/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",u0,{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(l`/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(l`/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 j(`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)=>T$.fromResponse(X.response,X.controller))}}var QQ={"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"},IV=["claude-opus-4-6"];class D1 extends o{constructor(){super(...arguments);this.batches=new _2(this._client)}create($,Z){let Y=zQ($),{betas:Q,...z}=Y;if(z.model in QQ)console.warn(`The model '${z.model}' is deprecated and will reach end-of-life on ${QQ[z.model]}
158
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(z.model in IV&&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=V4[z.model]??void 0;J=this._client.calculateNonstreamingTimeout(z.max_tokens,K)}let X=G4(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)=>q6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return w2.createMessage(this,$,Z)}countTokens($,Z){let Y=zQ($),{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 y2(this._client,$,Z)}}function zQ($){if(!$.output_format)return $;if($.output_config?.format)throw new j("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}}}D1.Batches=_2;D1.BetaToolRunner=y2;D1.ToolError=A$;class x2 extends o{create($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.post(l`/v1/skills/${$}/versions?beta=true`,L$({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(l`/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(l`/v1/skills/${$}/versions?beta=true`,E2,{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(l`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class I$ extends o{constructor(){super(...arguments);this.versions=new x2(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",L$({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(l`/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",E2,{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(l`/v1/skills/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}I$.Versions=x2;class c0 extends o{constructor(){super(...arguments);this.models=new j2(this._client),this.messages=new D1(this._client),this.files=new L2(this._client),this.skills=new I$(this._client)}}c0.Models=j2;c0.Messages=D1;c0.Files=L2;c0.Skills=I$;class S$ extends o{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 JQ($){return $?.output_config?.format}function O6($,Z,Y){let Q=JQ(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 C6($,Z,Y)}function C6($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=fV(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 fV($,Z){let Y=JQ($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new j(`Failed to parse structured output: ${Q}`)}}var y0,T1,w$,v2,M4,h2,g2,E4,u2,Q1,m2,R4,F4,s1,L4,j4,p2,M6,XQ,E6,R6,F6,L6,KQ,GQ="__json_buf";function VQ($){return $.type==="tool_use"||$.type==="server_tool_use"}class d2{constructor($,Z){y0.add(this),this.messages=[],this.receivedMessages=[],T1.set(this,void 0),w$.set(this,null),this.controller=new AbortController,v2.set(this,void 0),M4.set(this,()=>{}),h2.set(this,()=>{}),g2.set(this,void 0),E4.set(this,()=>{}),u2.set(this,()=>{}),Q1.set(this,{}),m2.set(this,!1),R4.set(this,!1),F4.set(this,!1),s1.set(this,!1),L4.set(this,void 0),j4.set(this,void 0),p2.set(this,void 0),E6.set(this,(Y)=>{if(R(this,R4,!0,"f"),e0(Y))Y=new H0;if(Y instanceof H0)return R(this,F4,!0,"f"),this._emit("abort",Y);if(Y instanceof j)return this._emit("error",Y);if(Y instanceof Error){let Q=new j(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new j(String(Y)))}),R(this,v2,new Promise((Y,Q)=>{R(this,M4,Y,"f"),R(this,h2,Q,"f")}),"f"),R(this,g2,new Promise((Y,Q)=>{R(this,E4,Y,"f"),R(this,u2,Q,"f")}),"f"),O(this,v2,"f").catch(()=>{}),O(this,g2,"f").catch(()=>{}),R(this,w$,$,"f"),R(this,p2,Z?.logger??console,"f")}get response(){return O(this,L4,"f")}get request_id(){return O(this,j4,"f")}async withResponse(){R(this,s1,!0,"f");let $=await O(this,v2,"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 d2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new d2(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return R(z,w$,{...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")},O(this,E6,"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{O(this,y0,"m",R6).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)O(this,y0,"m",F6).call(this,K);if(X.controller.signal?.aborted)throw new H0;O(this,y0,"m",L6).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;R(this,L4,$,"f"),R(this,j4,$?.headers.get("request-id"),"f"),O(this,M4,"f").call(this,$),this._emit("connect")}get ended(){return O(this,m2,"f")}get errored(){return O(this,R4,"f")}get aborted(){return O(this,F4,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,Q1,"f")[$]||(O(this,Q1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,Q1,"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(O(this,Q1,"f")[$]||(O(this,Q1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,s1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,s1,!0,"f"),await O(this,g2,"f")}get currentMessage(){return O(this,T1,"f")}async finalMessage(){return await this.done(),O(this,y0,"m",M6).call(this)}async finalText(){return await this.done(),O(this,y0,"m",XQ).call(this)}_emit($,...Z){if(O(this,m2,"f"))return;if($==="end")R(this,m2,!0,"f"),O(this,E4,"f").call(this);let Y=O(this,Q1,"f")[$];if(Y)O(this,Q1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,s1,"f")&&!Y?.length)Promise.reject(Q);O(this,h2,"f").call(this,Q),O(this,u2,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,s1,"f")&&!Y?.length)Promise.reject(Q);O(this,h2,"f").call(this,Q),O(this,u2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,y0,"m",M6).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{O(this,y0,"m",R6).call(this),this._connected(null);let z=I0.fromReadableStream($,this.controller);for await(let J of z)O(this,y0,"m",F6).call(this,J);if(z.controller.signal?.aborted)throw new H0;O(this,y0,"m",L6).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(T1=new WeakMap,w$=new WeakMap,v2=new WeakMap,M4=new WeakMap,h2=new WeakMap,g2=new WeakMap,E4=new WeakMap,u2=new WeakMap,Q1=new WeakMap,m2=new WeakMap,R4=new WeakMap,F4=new WeakMap,s1=new WeakMap,L4=new WeakMap,j4=new WeakMap,p2=new WeakMap,E6=new WeakMap,y0=new WeakSet,M6=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},XQ=function(){if(this.receivedMessages.length===0)throw new j("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 j("stream ended without producing a content block with type=text");return Z.join(" ")},R6=function(){if(this.ended)return;R(this,T1,void 0,"f")},F6=function(Z){if(this.ended)return;let Y=O(this,y0,"m",KQ).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(VQ(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:qQ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(O6(Y,O(this,w$,"f"),{logger:O(this,p2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,T1,Y,"f");break}case"content_block_start":case"message_delta":break}},L6=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let Z=O(this,T1,"f");if(!Z)throw new j("request ended without sending any chunks");return R(this,T1,void 0,"f"),O6(Z,O(this,w$,"f"),{logger:O(this,p2,"f")})},KQ=function(Z){let Y=O(this,T1,"f");if(Z.type==="message_start"){if(Y)throw new j(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new j(`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&&VQ(Q)){let z=Q[GQ]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,GQ,{value:z,enumerable:!1,writable:!0}),z)J.input=q4(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:qQ(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 I0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function qQ($){}class c2 extends o{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(l`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",u0,{query:$,...Z})}delete($,Z){return this._client.delete(l`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(l`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new j(`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)=>T$.fromResponse(z.response,z.controller))}}class t1 extends o{constructor(){super(...arguments);this.batches=new c2(this._client)}create($,Z){if($.model in UQ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${UQ[$.model]}
159
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in yV&&$.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=V4[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,z)}let Q=G4($.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)=>C6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return d2.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var UQ={"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"},yV=["claude-opus-4-6"];t1.Batches=c2;class k$ extends o{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(l`/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",u0,{query:Q,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var l2=($)=>{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 j6,P6,P4,HQ,WQ="\\n\\nHuman:",BQ="\\n\\nAssistant:";class i{constructor({baseURL:$=l2("ANTHROPIC_BASE_URL"),apiKey:Z=l2("ANTHROPIC_API_KEY")??null,authToken:Y=l2("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){j6.add(this),P4.set(this,void 0);let z={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!z.dangerouslyAllowBrowser&&SY())throw new j(`It looks like you're running in a browser-like environment.
157
+ Wrap your summary in <summary></summary> tags.`;var f2,D$,s1,Y0,b2,w0,Q1,T1,y2,VQ,E6;function UQ(){let $,Z;return{promise:new Promise((Q,z)=>{$=Q,Z=z}),resolve:$,reject:Z}}class _2{constructor($,Z,Y){f2.add(this),this.client=$,D$.set(this,!1),s1.set(this,!1),Y0.set(this,void 0),b2.set(this,void 0),w0.set(this,void 0),Q1.set(this,void 0),T1.set(this,void 0),y2.set(this,0),R(this,Y0,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let z=["BetaToolRunner",...H6(Z.tools,Z.messages)].join(", ");R(this,b2,{...Y,headers:D([{"x-stainless-helper":z},Y?.headers])},"f"),R(this,T1,UQ(),"f")}async*[(D$=new WeakMap,s1=new WeakMap,Y0=new WeakMap,b2=new WeakMap,w0=new WeakMap,Q1=new WeakMap,T1=new WeakMap,y2=new WeakMap,f2=new WeakSet,VQ=async function(){let Z=O(this,Y0,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(O(this,w0,"f")!==void 0)try{let G=await O(this,w0,"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??KQ;if(Y<Q)return!1;let z=Z.model??O(this,Y0,"f").params.model,J=Z.summaryPrompt??GQ,X=O(this,Y0,"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:O(this,Y0,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(K.content[0]?.type!=="text")throw new j("Expected text response for compaction");return O(this,Y0,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(O(this,D$,"f"))throw new j("Cannot iterate over a consumed stream");R(this,D$,!0,"f"),R(this,s1,!0,"f"),R(this,Q1,void 0,"f");try{while(!0){let Z;try{if(O(this,Y0,"f").params.max_iterations&&O(this,y2,"f")>=O(this,Y0,"f").params.max_iterations)break;R(this,s1,!1,"f"),R(this,Q1,void 0,"f"),R(this,y2,($=O(this,y2,"f"),$++,$),"f"),R(this,w0,void 0,"f");let{max_iterations:Y,compactionControl:Q,...z}=O(this,Y0,"f").params;if(z.stream)Z=this.client.beta.messages.stream({...z},O(this,b2,"f")),R(this,w0,Z.finalMessage(),"f"),O(this,w0,"f").catch(()=>{}),yield Z;else R(this,w0,this.client.beta.messages.create({...z,stream:!1},O(this,b2,"f")),"f"),yield O(this,w0,"f");if(!await O(this,f2,"m",VQ).call(this)){if(!O(this,s1,"f")){let{role:K,content:G}=await O(this,w0,"f");O(this,Y0,"f").params.messages.push({role:K,content:G})}let X=await O(this,f2,"m",E6).call(this,O(this,Y0,"f").params.messages.at(-1));if(X)O(this,Y0,"f").params.messages.push(X);else if(!O(this,s1,"f"))break}}finally{if(Z)Z.abort()}}if(!O(this,w0,"f"))throw new j("ToolRunner concluded without a message from the server");O(this,T1,"f").resolve(await O(this,w0,"f"))}catch(Z){throw R(this,D$,!1,"f"),O(this,T1,"f").promise.catch(()=>{}),O(this,T1,"f").reject(Z),R(this,T1,UQ(),"f"),Z}}setMessagesParams($){if(typeof $==="function")O(this,Y0,"f").params=$(O(this,Y0,"f").params);else O(this,Y0,"f").params=$;R(this,s1,!0,"f"),R(this,Q1,void 0,"f")}async generateToolResponse(){let $=await O(this,w0,"f")??this.params.messages.at(-1);if(!$)return null;return O(this,f2,"m",E6).call(this,$)}done(){return O(this,T1,"f").promise}async runUntilDone(){if(!O(this,D$,"f"))for await(let $ of this);return this.done()}get params(){return O(this,Y0,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}E6=async function(Z){if(O(this,Q1,"f")!==void 0)return O(this,Q1,"f");return R(this,Q1,iV(O(this,Y0,"f").params,Z),"f"),O(this,Q1,"f")};async function iV($,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 T$?X.content:`Error: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}))}}class I${constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new P1;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 j("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 j("Attempted to iterate over a response with no body")}return new I$(N2($.body),Z)}}class x2 extends i{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Z,headers:D([{"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:D([{"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",m0,{query:Q,...Z,headers:D([{"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:D([{"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:D([{"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 j(`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:D([{"anthropic-beta":[...z??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,X)=>I$.fromResponse(X.response,X.controller))}}var qQ={"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"},rV=["claude-opus-4-6"];class D1 extends i{constructor(){super(...arguments);this.batches=new x2(this._client)}create($,Z){let Y=HQ($),{betas:Q,...z}=Y;if(z.model in qQ)console.warn(`The model '${z.model}' is deprecated and will reach end-of-life on ${qQ[z.model]}
158
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(z.model in rV&&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=q4[z.model]??void 0;J=this._client.calculateNonstreamingTimeout(z.max_tokens,K)}let X=U4(z.tools,z.messages);return this._client.post("/v1/messages?beta=true",{body:z,timeout:J??600000,...Z,headers:D([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:D([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>B6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return k2.createMessage(this,$,Z)}countTokens($,Z){let Y=HQ($),{betas:Q,...z}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:z,...Z,headers:D([{"anthropic-beta":[...Q??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new _2(this._client,$,Z)}}function HQ($){if(!$.output_format)return $;if($.output_config?.format)throw new j("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}}}D1.Batches=x2;D1.BetaToolRunner=_2;D1.ToolError=T$;class v2 extends i{create($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.post(o`/v1/skills/${$}/versions?beta=true`,j$({body:z,...Y,headers:D([{"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:D([{"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`,R2,{query:z,...Y,headers:D([{"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:D([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class S$ extends i{constructor(){super(...arguments);this.versions=new v2(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",j$({body:Q,...Z,headers:D([{"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:D([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/skills?beta=true",R2,{query:Q,...Z,headers:D([{"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:D([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}S$.Versions=v2;class l0 extends i{constructor(){super(...arguments);this.models=new P2(this._client),this.messages=new D1(this._client),this.files=new j2(this._client),this.skills=new S$(this._client)}}l0.Models=P2;l0.Messages=D1;l0.Files=j2;l0.Skills=S$;class w$ extends i{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Z,headers:D([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function WQ($){return $?.output_config?.format}function R6($,Z,Y){let Q=WQ(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 F6($,Z,Y)}function F6($,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=WQ($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new j(`Failed to parse structured output: ${Q}`)}}var _0,I1,k$,h2,R4,g2,u2,F4,m2,z1,p2,L4,j4,t1,P4,A4,d2,L6,BQ,j6,P6,A6,T6,NQ,OQ="__json_buf";function MQ($){return $.type==="tool_use"||$.type==="server_tool_use"}class c2{constructor($,Z){_0.add(this),this.messages=[],this.receivedMessages=[],I1.set(this,void 0),k$.set(this,null),this.controller=new AbortController,h2.set(this,void 0),R4.set(this,()=>{}),g2.set(this,()=>{}),u2.set(this,void 0),F4.set(this,()=>{}),m2.set(this,()=>{}),z1.set(this,{}),p2.set(this,!1),L4.set(this,!1),j4.set(this,!1),t1.set(this,!1),P4.set(this,void 0),A4.set(this,void 0),d2.set(this,void 0),j6.set(this,(Y)=>{if(R(this,L4,!0,"f"),$1(Y))Y=new W0;if(Y instanceof W0)return R(this,j4,!0,"f"),this._emit("abort",Y);if(Y instanceof j)return this._emit("error",Y);if(Y instanceof Error){let Q=new j(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new j(String(Y)))}),R(this,h2,new Promise((Y,Q)=>{R(this,R4,Y,"f"),R(this,g2,Q,"f")}),"f"),R(this,u2,new Promise((Y,Q)=>{R(this,F4,Y,"f"),R(this,m2,Q,"f")}),"f"),O(this,h2,"f").catch(()=>{}),O(this,u2,"f").catch(()=>{}),R(this,k$,$,"f"),R(this,d2,Z?.logger??console,"f")}get response(){return O(this,P4,"f")}get request_id(){return O(this,A4,"f")}async withResponse(){R(this,t1,!0,"f");let $=await O(this,h2,"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 c2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new c2(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return R(z,k$,{...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")},O(this,j6,"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{O(this,_0,"m",P6).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)O(this,_0,"m",A6).call(this,K);if(X.controller.signal?.aborted)throw new W0;O(this,_0,"m",T6).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;R(this,P4,$,"f"),R(this,A4,$?.headers.get("request-id"),"f"),O(this,R4,"f").call(this,$),this._emit("connect")}get ended(){return O(this,p2,"f")}get errored(){return O(this,L4,"f")}get aborted(){return O(this,j4,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,z1,"f")[$]||(O(this,z1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,z1,"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(O(this,z1,"f")[$]||(O(this,z1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(R(this,t1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){R(this,t1,!0,"f"),await O(this,u2,"f")}get currentMessage(){return O(this,I1,"f")}async finalMessage(){return await this.done(),O(this,_0,"m",L6).call(this)}async finalText(){return await this.done(),O(this,_0,"m",BQ).call(this)}_emit($,...Z){if(O(this,p2,"f"))return;if($==="end")R(this,p2,!0,"f"),O(this,F4,"f").call(this);let Y=O(this,z1,"f")[$];if(Y)O(this,z1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,t1,"f")&&!Y?.length)Promise.reject(Q);O(this,g2,"f").call(this,Q),O(this,m2,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,t1,"f")&&!Y?.length)Promise.reject(Q);O(this,g2,"f").call(this,Q),O(this,m2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,_0,"m",L6).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{O(this,_0,"m",P6).call(this),this._connected(null);let z=S0.fromReadableStream($,this.controller);for await(let J of z)O(this,_0,"m",A6).call(this,J);if(z.controller.signal?.aborted)throw new W0;O(this,_0,"m",T6).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(I1=new WeakMap,k$=new WeakMap,h2=new WeakMap,R4=new WeakMap,g2=new WeakMap,u2=new WeakMap,F4=new WeakMap,m2=new WeakMap,z1=new WeakMap,p2=new WeakMap,L4=new WeakMap,j4=new WeakMap,t1=new WeakMap,P4=new WeakMap,A4=new WeakMap,d2=new WeakMap,j6=new WeakMap,_0=new WeakSet,L6=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},BQ=function(){if(this.receivedMessages.length===0)throw new j("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 j("stream ended without producing a content block with type=text");return Z.join(" ")},P6=function(){if(this.ended)return;R(this,I1,void 0,"f")},A6=function(Z){if(this.ended)return;let Y=O(this,_0,"m",NQ).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(MQ(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:CQ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(R6(Y,O(this,k$,"f"),{logger:O(this,d2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{R(this,I1,Y,"f");break}case"content_block_start":case"message_delta":break}},T6=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let Z=O(this,I1,"f");if(!Z)throw new j("request ended without sending any chunks");return R(this,I1,void 0,"f"),R6(Z,O(this,k$,"f"),{logger:O(this,d2,"f")})},NQ=function(Z){let Y=O(this,I1,"f");if(Z.type==="message_start"){if(Y)throw new j(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new j(`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&&MQ(Q)){let z=Q[OQ]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,OQ,{value:z,enumerable:!1,writable:!0}),z)J.input=H4(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:CQ(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 S0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function CQ($){}class l2 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",m0,{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 j(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:D([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,z)=>I$.fromResponse(z.response,z.controller))}}class e1 extends i{constructor(){super(...arguments);this.batches=new l2(this._client)}create($,Z){if($.model in EQ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${EQ[$.model]}
159
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in ZU&&$.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=q4[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,z)}let Q=U4($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:D([Q,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>F6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return c2.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var EQ={"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"},ZU=["claude-opus-4-6"];e1.Batches=l2;class f$ extends i{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(o`/v1/models/${$}`,{...Y,headers:D([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models",m0,{query:Q,...Z,headers:D([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var o2=($)=>{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 D6,I6,T4,RQ,FQ="\\n\\nHuman:",LQ="\\n\\nAssistant:";class n{constructor({baseURL:$=o2("ANTHROPIC_BASE_URL"),apiKey:Z=o2("ANTHROPIC_API_KEY")??null,authToken:Y=o2("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){D6.add(this),T4.set(this,void 0);let z={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!z.dangerouslyAllowBrowser&&vY())throw new j(`It looks like you're running in a browser-like environment.
160
160
 
161
161
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
162
162
  If you understand the risks and have appropriate mitigations in place,
163
163
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
164
164
 
165
165
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
166
- `);this.baseURL=z.baseURL,this.timeout=z.timeout??P6.DEFAULT_TIMEOUT,this.logger=z.logger??console;let J="warn";this.logLevel=J,this.logLevel=Z6(z.logLevel,"ClientOptions.logLevel",this)??Z6(l2("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=z.fetchOptions,this.maxRetries=z.maxRetries??2,this.fetch=z.fetch??kY(),R(this,P4,bY,"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 yY($)}getUserAgent(){return`${this.constructor.name}/JS ${L1}`}defaultIdempotencyKey(){return`stainless-node-retry-${n7()}`}makeStatusError($,Z,Y,Q){return $0.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!O(this,j6,"m",HQ).call(this)&&Y||this.baseURL,z=LY($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),X=Object.fromEntries(z.searchParams);if(!t7(J)||!t7(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 j("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 i1(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}`,q=Date.now();if(z0(this).debug(`[${G}] sending request`,$1({retryOfRequestLogID:Y,method:Q.method,url:X,options:Q,headers:J.headers})),Q.signal?.aborted)throw new H0;let U=new AbortController,H=await this.fetchWithTimeout(X,J,K,U).catch(z2),B=Date.now();if(H instanceof globalThis.Error){let M=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new H0;let F=e0(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"} - ${M}`),z0(this).debug(`[${G}] connection ${F?"timed out":"failed"} (${M})`,$1({retryOfRequestLogID:Y,url:X,durationMs:B-q,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)`,$1({retryOfRequestLogID:Y,url:X,durationMs:B-q,message:H.message})),F)throw new J2;throw new o1({cause:H})}let N=[...H.headers.entries()].filter(([M])=>M==="request-id").map(([M,F])=>", "+M+": "+JSON.stringify(F)).join(""),C=`[${G}${V}${N}] ${J.method} ${X} ${H.ok?"succeeded":"failed"} with status ${H.status} in ${B-q}ms`;if(!H.ok){let M=await this.shouldRetry(H);if(Z&&M){let h=`retrying, ${Z} attempts remaining`;return await fY(H.body),z0(this).info(`${C} - ${h}`),z0(this).debug(`[${G}] response error (${h})`,$1({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,durationMs:B-q})),this.retryRequest(Q,Z,Y??G,H.headers)}let F=M?"error; no more retries left":"error; not retryable";z0(this).info(`${C} - ${F}`);let w=await H.text().catch((h)=>z2(h).message),d=e8(w),D=d?void 0:w;throw z0(this).debug(`[${G}] response error (${F})`,$1({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,message:D,durationMs:Date.now()-q})),this.makeStatusError(H.status,d,D,H.headers)}return z0(this).info(C),z0(this).debug(`[${G}] response start`,$1({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,durationMs:B-q})),{response:H,options:Q,controller:U,requestLogID:G,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 J4(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,q={signal:Q.signal,...V?{duplex:"half"}:{},method:"GET",...X};if(J)q.method=J.toUpperCase();try{return await this.fetch.call(void 0,$,q)}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 AY(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 j("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)PY("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:G,body:V}=this.buildBody({options:Y}),q=await this.buildHeaders({options:$,method:Q,bodyHeaders:G,retryCount:Z});return{req:{method:Q,headers:q,...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))}:{},...wY(),...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:$4($)};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 O(this,P4,"f").call(this,{body:$,headers:Y})}}P6=i,P4=new WeakMap,j6=new WeakSet,HQ=function(){return this.baseURL!=="https://api.anthropic.com"};i.Anthropic=P6;i.HUMAN_PROMPT=WQ;i.AI_PROMPT=BQ;i.DEFAULT_TIMEOUT=600000;i.AnthropicError=j;i.APIError=$0;i.APIConnectionError=o1;i.APIConnectionTimeoutError=J2;i.APIUserAbortError=H0;i.NotFoundError=V2;i.ConflictError=q2;i.RateLimitError=H2;i.BadRequestError=X2;i.AuthenticationError=K2;i.InternalServerError=W2;i.PermissionDeniedError=G2;i.UnprocessableEntityError=U2;i.toFile=X4;class l0 extends i{constructor(){super(...arguments);this.completions=new S$(this),this.messages=new t1(this),this.models=new k$(this),this.beta=new c0(this)}}l0.Completions=S$;l0.Messages=t1;l0.Models=k$;l0.Beta=c0;import{existsSync as xV,readFileSync as vV,writeFileSync as hV}from"fs";import{basename as A6}from"path";var NQ=50;class D6{entries=[];saveState($){let Z=xV($),Y=Z?vV($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>NQ)this.entries=this.entries.slice(-NQ)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${A6($.path)} was a new file. Remove it manually if needed.`;hV($.path,$.content);let Z=$.content.split(`
167
- `).length;return`Undo: restored ${A6($.path)} (${Z} lines, from ${OQ($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${A6($.path)} (${OQ($.timestamp)})`}}function OQ($){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`}n();var b=[{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 o2=[{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:[]}}],A4=[{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:[]}}],D4=[{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"]}}],T4=o2.find(($)=>$.name==="get_news");import{resolve as _5,sep as gJ}from"path";import{writeFileSync as YW}from"fs";u();import{existsSync as gV,readFileSync as uV}from"fs";import{join as mV}from"path";var f$=[{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}],I4="",C0=[],w0=new Set,RQ=()=>mV(I4,"news-feeds.json");function S4(){if(!I4)return;let $={custom:C0,disabled:[...w0]};A(RQ(),JSON.stringify($,null,2))}function pV(){if(!I4)return;let $=RQ();if(!gV($)){C0=[],w0=new Set;return}try{let Z=JSON.parse(uV($,"utf-8"));C0=Z.custom||[],w0=new Set(Z.disabled||[])}catch{C0=[],w0=new Set}}function FQ($){I4=$,pV()}function I6(){return[...f$.filter((Z)=>!w0.has(Z.url)),...C0]}function w4($,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([...f$,...C0].some((G)=>G.url===J))return"Error: essa URL ja esta cadastrada.";let K={name:Q,url:J,category:z};return C0=[...C0,K],S4(),K}function k4($){let Z=$.toLowerCase().trim(),Y=C0.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return C0=[...C0.slice(0,Y),...C0.slice(Y+1)],S4(),!0}function f4($){let Z=$.toLowerCase().trim(),Y=f$.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(w0.has(Y.url))return!1;return w0=new Set([...w0,Y.url]),S4(),!0}function b4($){let Z=$.toLowerCase().trim(),Y=f$.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!w0.has(Y.url))return!1;return w0=new Set([...w0].filter((Q)=>Q!==Y.url)),S4(),!0}function y4(){let $=["Fontes de noticias:"];$.push(`
168
- --- Built-in ---`);for(let Z of f$){let Y=w0.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(C0.length>0){$.push(`
166
+ `);this.baseURL=z.baseURL,this.timeout=z.timeout??I6.DEFAULT_TIMEOUT,this.logger=z.logger??console;let J="warn";this.logLevel=J,this.logLevel=J6(z.logLevel,"ClientOptions.logLevel",this)??J6(o2("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=z.fetchOptions,this.maxRetries=z.maxRetries??2,this.fetch=z.fetch??gY(),R(this,T4,mY,"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 D([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return D([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return D([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return pY($)}getUserAgent(){return`${this.constructor.name}/JS ${j1}`}defaultIdempotencyKey(){return`stainless-node-retry-${e7()}`}makeStatusError($,Z,Y,Q){return Z0.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!O(this,D6,"m",RQ).call(this)&&Y||this.baseURL,z=wY($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),X=Object.fromEntries(z.searchParams);if(!Y6(J)||!Y6(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 j("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 n1(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(J0(this).debug(`[${G}] sending request`,Z1({retryOfRequestLogID:Y,method:Q.method,url:X,options:Q,headers:J.headers})),Q.signal?.aborted)throw new W0;let q=new AbortController,H=await this.fetchWithTimeout(X,J,K,q).catch(J2),B=Date.now();if(H instanceof globalThis.Error){let C=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new W0;let F=$1(H)||/timed? ?out/i.test(String(H)+("cause"in H?String(H.cause):""));if(Z)return J0(this).info(`[${G}] connection ${F?"timed out":"failed"} - ${C}`),J0(this).debug(`[${G}] connection ${F?"timed out":"failed"} (${C})`,Z1({retryOfRequestLogID:Y,url:X,durationMs:B-U,message:H.message})),this.retryRequest(Q,Z,Y??G);if(J0(this).info(`[${G}] connection ${F?"timed out":"failed"} - error; no more retries left`),J0(this).debug(`[${G}] connection ${F?"timed out":"failed"} (error; no more retries left)`,Z1({retryOfRequestLogID:Y,url:X,durationMs:B-U,message:H.message})),F)throw new X2;throw new i1({cause:H})}let N=[...H.headers.entries()].filter(([C])=>C==="request-id").map(([C,F])=>", "+C+": "+JSON.stringify(F)).join(""),M=`[${G}${V}${N}] ${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 uY(H.body),J0(this).info(`${M} - ${g}`),J0(this).debug(`[${G}] response error (${g})`,Z1({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";J0(this).info(`${M} - ${F}`);let k=await H.text().catch((g)=>J2(g).message),c=Z4(k),T=c?void 0:k;throw J0(this).debug(`[${G}] response error (${F})`,Z1({retryOfRequestLogID:Y,url:H.url,status:H.status,headers:H.headers,message:T,durationMs:Date.now()-U})),this.makeStatusError(H.status,c,T,H.headers)}return J0(this).info(M),J0(this).debug(`[${G}] response start`,Z1({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 K4(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 bY(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 j("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)fY("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=D([z,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...hY(),...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=D([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:Y4($)};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 O(this,T4,"f").call(this,{body:$,headers:Y})}}I6=n,T4=new WeakMap,D6=new WeakSet,RQ=function(){return this.baseURL!=="https://api.anthropic.com"};n.Anthropic=I6;n.HUMAN_PROMPT=FQ;n.AI_PROMPT=LQ;n.DEFAULT_TIMEOUT=600000;n.AnthropicError=j;n.APIError=Z0;n.APIConnectionError=i1;n.APIConnectionTimeoutError=X2;n.APIUserAbortError=W0;n.NotFoundError=U2;n.ConflictError=q2;n.RateLimitError=W2;n.BadRequestError=K2;n.AuthenticationError=G2;n.InternalServerError=B2;n.PermissionDeniedError=V2;n.UnprocessableEntityError=H2;n.toFile=G4;class o0 extends n{constructor(){super(...arguments);this.completions=new w$(this),this.messages=new e1(this),this.models=new f$(this),this.beta=new l0(this)}}o0.Completions=w$;o0.Messages=e1;o0.Models=f$;o0.Beta=l0;import{existsSync as QU,readFileSync as zU,writeFileSync as JU}from"fs";import{basename as S6}from"path";var jQ=50;class w6{entries=[];saveState($){let Z=QU($),Y=Z?zU($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>jQ)this.entries=this.entries.slice(-jQ)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${S6($.path)} was a new file. Remove it manually if needed.`;JU($.path,$.content);let Z=$.content.split(`
167
+ `).length;return`Undo: restored ${S6($.path)} (${Z} lines, from ${PQ($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${S6($.path)} (${PQ($.timestamp)})`}}function PQ($){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`}a();var b=[{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 i2=[{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:[]}}],D4=[{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:[]}}],I4=[{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"]}}],S4=i2.find(($)=>$.name==="get_news");import{resolve as g5,sep as X3}from"path";import{writeFileSync as IW}from"fs";u();import{existsSync as XU,readFileSync as KU}from"fs";import{join as GU}from"path";var b$=[{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}],w4="",C0=[],k0=new Set,IQ=()=>GU(w4,"news-feeds.json");function k4(){if(!w4)return;let $={custom:C0,disabled:[...k0]};P(IQ(),JSON.stringify($,null,2))}function VU(){if(!w4)return;let $=IQ();if(!XU($)){C0=[],k0=new Set;return}try{let Z=JSON.parse(KU($,"utf-8"));C0=Z.custom||[],k0=new Set(Z.disabled||[])}catch{C0=[],k0=new Set}}function SQ($){w4=$,VU()}function f6(){return[...b$.filter((Z)=>!k0.has(Z.url)),...C0]}function f4($,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([...b$,...C0].some((G)=>G.url===J))return"Error: essa URL ja esta cadastrada.";let K={name:Q,url:J,category:z};return C0=[...C0,K],k4(),K}function b4($){let Z=$.toLowerCase().trim(),Y=C0.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return C0=[...C0.slice(0,Y),...C0.slice(Y+1)],k4(),!0}function y4($){let Z=$.toLowerCase().trim(),Y=b$.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(k0.has(Y.url))return!1;return k0=new Set([...k0,Y.url]),k4(),!0}function _4($){let Z=$.toLowerCase().trim(),Y=b$.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!k0.has(Y.url))return!1;return k0=new Set([...k0].filter((Q)=>Q!==Y.url)),k4(),!0}function x4(){let $=["Fontes de noticias:"];$.push(`
168
+ --- Built-in ---`);for(let Z of b$){let Y=k0.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(C0.length>0){$.push(`
169
169
  --- Custom ---`);for(let Z of C0)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
170
- Total: ${I6().length} ativas (${f$.length} built-in, ${C0.length} custom, ${w0.size} desativadas)`),$.join(`
171
- `)}var CQ=2097152,T6=10,dV=1e4;function cV($,Z,Y){let Q=[],z=/<item[\s>]([\s\S]*?)<\/item>/gi,J;while((J=z.exec($))!==null){let X=J[1],K=MQ(X,Z,Y);if(K)Q.push(K);if(Q.length>=T6)break}if(Q.length===0){let X=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((J=X.exec($))!==null){let K=J[1],G=MQ(K,Z,Y);if(G)Q.push(G);if(Q.length>=T6)break}}return Q}function MQ($,Z,Y){let Q=i2($,"title");if(!Q)return null;let z=i2($,"link")||nV($),J=lV(z),X=i2($,"pubDate")||i2($,"published")||i2($,"updated"),K;if(X){let G=new Date(X);K=isNaN(G.getTime())?void 0:G}return{title:n2(Q),link:J,source:Z,category:Y,pubDate:K}}function lV($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function oV($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i2($,Z){let Y=oV(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 iV($,Z){let Y=rV($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function rV($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return r2(z[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return r2(Q[1]);return"utf-8"}function r2($){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 nV($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var aV={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 n2($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>aV[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 S6($,Z=5){let Y=Math.max(1,Math.min(Z,T6));if($&&$.length===0)return{items:[],errors:[]};let Q=I6(),z=$?Q.filter((G)=>$.includes(G.category)):Q,J=await Promise.allSettled(z.map((G)=>tV(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}: ${sV(V.reason)}`)}return X.sort((G,V)=>{let q=G.pubDate?.getTime()||0;return(V.pubDate?.getTime()||0)-q}),{items:X,errors:K}}async function I1($,Z=5){if($&&$.length===0)return $q();let{items:Y,errors:Q}=await S6($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
172
- Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return eV(Y,Q)}function sV($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function tV($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),dV);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)>CQ)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>CQ)return X.cancel(),[];K.push(B)}let V=Buffer.concat(K),q=iV(V,z.headers.get("content-type"));return cV(q,$.name,$.category).slice(0,Z)}catch(z){throw clearTimeout(Q),z}}function eV($,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],q=G.slice(0,8).map((U)=>{let H=U.pubDate?U.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${H?`[${H}]`:""} ${U.title} (${U.source})`});z.push(`--- ${V} ---
173
- ${q.join(`
170
+ Total: ${f6().length} ativas (${b$.length} built-in, ${C0.length} custom, ${k0.size} desativadas)`),$.join(`
171
+ `)}var AQ=2097152,k6=10,UU=1e4;function qU($,Z,Y){let Q=[],z=/<item[\s>]([\s\S]*?)<\/item>/gi,J;while((J=z.exec($))!==null){let X=J[1],K=TQ(X,Z,Y);if(K)Q.push(K);if(Q.length>=k6)break}if(Q.length===0){let X=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((J=X.exec($))!==null){let K=J[1],G=TQ(K,Z,Y);if(G)Q.push(G);if(Q.length>=k6)break}}return Q}function TQ($,Z,Y){let Q=n2($,"title");if(!Q)return null;let z=n2($,"link")||OU($),J=HU(z),X=n2($,"pubDate")||n2($,"published")||n2($,"updated"),K;if(X){let G=new Date(X);K=isNaN(G.getTime())?void 0:G}return{title:a2(Q),link:J,source:Z,category:Y,pubDate:K}}function HU($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function WU($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n2($,Z){let Y=WU(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 BU($,Z){let Y=NU($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function NU($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return r2(z[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return r2(Q[1]);return"utf-8"}function r2($){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 OU($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var MU={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 a2($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>MU[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 b6($,Z=5){let Y=Math.max(1,Math.min(Z,k6));if($&&$.length===0)return{items:[],errors:[]};let Q=f6(),z=$?Q.filter((G)=>$.includes(G.category)):Q,J=await Promise.allSettled(z.map((G)=>EU(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}: ${CU(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 S1($,Z=5){if($&&$.length===0)return FU();let{items:Y,errors:Q}=await b6($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
172
+ Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return RU(Y,Q)}function CU($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function EU($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),UU);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)>AQ)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>AQ)return X.cancel(),[];K.push(B)}let V=Buffer.concat(K),U=BU(V,z.headers.get("content-type"));return qU(U,$.name,$.category).slice(0,Z)}catch(z){throw clearTimeout(Q),z}}function RU($,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} ---
173
+ ${U.join(`
174
174
  `)}`)}let X=z.join(`
175
175
 
176
176
  `);if(Z.length>0)X+=`
177
177
 
178
- (Fontes indisponiveis: ${Z.join(", ")})`;return X}function $q(){let $=I6();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
179
- Uso: /news [categoria]`}var Zq=15000,EQ=5242880;async function LQ($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),Zq);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)>EQ)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>EQ)return J.cancel(),"Error: pagina muito grande";X.push(B)}let G=Buffer.concat(X),V=Q.headers.get("content-type"),q=Yq(G,V);return zq(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 Yq($,Z){let Y=Qq($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function Qq($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return r2(J[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return r2(Q[1]);let z=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(z)return r2(z[1]);return"utf-8"}function zq($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?n2(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=n2(G[1]).trim();if(V.length>50)X.push(V)}Q=X.join(`
178
+ (Fontes indisponiveis: ${Z.join(", ")})`;return X}function FU(){let $=f6();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
179
+ Uso: /news [categoria]`}var LU=15000,DQ=5242880;async function wQ($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),LU);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)>DQ)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>DQ)return J.cancel(),"Error: pagina muito grande";X.push(B)}let G=Buffer.concat(X),V=Q.headers.get("content-type"),U=jU(G,V);return AU(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 jU($,Z){let Y=PU($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function PU($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return r2(J[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return r2(Q[1]);let z=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(z)return r2(z[1]);return"utf-8"}function AU($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?a2(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=a2(G[1]).trim();if(V.length>50)X.push(V)}Q=X.join(`
180
180
 
181
- `)}else Q=Jq(Q);let J=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:J}}function Jq($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let z=n2(Q[1]).trim();if(z.length>20)Z.push(z)}if(Z.length===0){let z=n2($).trim();if(z.length>50)return z}return Z.join(`
181
+ `)}else Q=TU(Q);let J=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:J}}function TU($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let z=a2(Q[1]).trim();if(z.length>20)Z.push(z)}if(Z.length===0){let z=a2($).trim();if(z.length>50)return z}return Z.join(`
182
182
 
183
- `)}n();u();p0();import{existsSync as jQ,mkdirSync as Xq,readFileSync as Kq}from"fs";import{join as Gq}from"path";import{randomUUID as Vq}from"crypto";var PQ="",a=[],b$=null,AQ=null,DQ=()=>Gq(PQ,"tasks.json");function _4(){A(DQ(),JSON.stringify(a,null,2))}function qq(){let $=DQ();if(!jQ($)){a=[];return}try{a=JSON.parse(Kq($,"utf-8"))}catch{a=[]}}function k6($,Z){if(PQ=$,AQ=Z,!jQ($))Xq($,{recursive:!0});if(qq(),b$)clearInterval(b$);b$=setInterval(Uq,30000),Bq().catch(()=>{})}function TQ(){if(b$)clearInterval(b$),b$=null}function x4($,Z){let Y={id:Nq(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(a=[...a,Y],_4(),Z&&L)w6(Y).catch(()=>{});return Y}function v4($){let Z=$.toLowerCase(),Y=a.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(a=a.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),_4(),Y.dueAt&&L)SQ(Y.id).catch(()=>{});return a.find((Q)=>Q.id===Y.id)||null}function IQ($){let Z=$.toLowerCase(),Y=a.findIndex((z)=>z.id===$||z.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=a[Y];if(a=[...a.slice(0,Y),...a.slice(Y+1)],_4(),Q.dueAt&&L)SQ(Q.id).catch(()=>{});return!0}function z1($=!1){return $?[...a]:a.filter((Z)=>!Z.done)}function e1($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",z=Y.dueAt?` (${Oq(Y.dueAt)})`:"";return` ${Q} ${Y.title}${z} [${Y.id}]`});return`Tarefas (${$.length}):
183
+ `)}a();u();d0();import{existsSync as kQ,mkdirSync as DU,readFileSync as IU}from"fs";import{join as SU}from"path";import{randomUUID as wU}from"crypto";var fQ="",s=[],y$=null,bQ=null,yQ=()=>SU(fQ,"tasks.json");function v4(){P(yQ(),JSON.stringify(s,null,2))}function kU(){let $=yQ();if(!kQ($)){s=[];return}try{s=JSON.parse(IU($,"utf-8"))}catch{s=[]}}function _6($,Z){if(fQ=$,bQ=Z,!kQ($))DU($,{recursive:!0});if(kU(),y$)clearInterval(y$);y$=setInterval(fU,30000),_U().catch(()=>{})}function _Q(){if(y$)clearInterval(y$),y$=null}function h4($,Z){let Y={id:xU(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(s=[...s,Y],v4(),Z&&L)y6(Y).catch(()=>{});return Y}function g4($){let Z=$.toLowerCase(),Y=s.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(s=s.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),v4(),Y.dueAt&&L)vQ(Y.id).catch(()=>{});return s.find((Q)=>Q.id===Y.id)||null}function xQ($){let Z=$.toLowerCase(),Y=s.findIndex((z)=>z.id===$||z.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=s[Y];if(s=[...s.slice(0,Y),...s.slice(Y+1)],v4(),Q.dueAt&&L)vQ(Q.id).catch(()=>{});return!0}function J1($=!1){return $?[...s]:s.filter((Z)=>!Z.done)}function $$($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",z=Y.dueAt?` (${vU(Y.dueAt)})`:"";return` ${Q} ${Y.title}${z} [${Y.id}]`});return`Tarefas (${$.length}):
184
184
  ${Z.join(`
185
- `)}`}function y$($){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 Uq(){let $=new Date,Z=!1;for(let Y of a){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)a=a.map((J)=>J.id===Y.id?{...J,notified:!0}:J),Z=!0,Wq(Y),AQ?.(Y)}if(Z)_4()}function Hq($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function Wq($){if(!L)return;try{await C1("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var f6="smolerclaw-reminder-";async function w6($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${f6}${$.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"">${$Y(Hq($.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 a0("Create",Y,["/SC","ONCE","/SD",Q,"/ST",z,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${X}"`,"/F"])}catch{}}async function SQ($){let Z=`${f6}${$}`;try{await a0("Delete",Z,["/F"])}catch{}}async function Bq(){if(!L)return;let $=Date.now();for(let Z of a){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await a0("Query",`${f6}${Z.id}`)).exitCode!==0)await w6(Z)}catch{await w6(Z)}}}function Nq(){return Vq().slice(0,8)}function Oq($){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}`}u();import{existsSync as wQ,mkdirSync as Cq,readFileSync as Mq}from"fs";import{join as Eq}from"path";import{randomUUID as Rq}from"crypto";var kQ="",R0=[],fQ=()=>Eq(kQ,"memos.json");function bQ(){A(fQ(),JSON.stringify(R0,null,2))}function Fq(){let $=fQ();if(!wQ($)){R0=[];return}try{R0=JSON.parse(Mq($,"utf-8"))}catch{R0=[]}}function yQ($){if(kQ=$,!wQ($))Cq($,{recursive:!0});Fq()}function h4($,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:jq(),content:$.trim(),tags:z,createdAt:Y,updatedAt:Y};return R0=[...R0,J],bQ(),J}function _Q($){let Z=R0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return R0=[...R0.slice(0,Z),...R0.slice(Z+1)],bQ(),!0}function g4($){let Z=$.toLowerCase().trim();if(!Z)return[...R0];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return R0.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 a2($=20){return[...R0].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function Lq(){let $=new Map;for(let Z of R0)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 $$($){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}):
186
- ${Z.join(`
187
- `)}`}function xQ(){let $=Lq();if($.length===0)return"Nenhuma tag.";return`Tags:
185
+ `)}`}function _$($){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 fU(){let $=new Date,Z=!1;for(let Y of s){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)s=s.map((J)=>J.id===Y.id?{...J,notified:!0}:J),Z=!0,yU(Y),bQ?.(Y)}if(Z)v4()}function bU($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function yU($){if(!L)return;try{await C1("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var x6="smolerclaw-reminder-";async function y6($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${x6}${$.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"">${GY(bU($.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 s0("Create",Y,["/SC","ONCE","/SD",Q,"/ST",z,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${X}"`,"/F"])}catch{}}async function vQ($){let Z=`${x6}${$}`;try{await s0("Delete",Z,["/F"])}catch{}}async function _U(){if(!L)return;let $=Date.now();for(let Z of s){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await s0("Query",`${x6}${Z.id}`)).exitCode!==0)await y6(Z)}catch{await y6(Z)}}}function xU(){return wU().slice(0,8)}function vU($){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}`}u();import{existsSync as hQ,mkdirSync as hU,readFileSync as gU}from"fs";import{join as uU}from"path";import{randomUUID as mU}from"crypto";var gQ="",F0=[],uQ=()=>uU(gQ,"memos.json");function mQ(){P(uQ(),JSON.stringify(F0,null,2))}function pU(){let $=uQ();if(!hQ($)){F0=[];return}try{F0=JSON.parse(gU($,"utf-8"))}catch{F0=[]}}function pQ($){if(gQ=$,!hQ($))hU($,{recursive:!0});pU()}function u4($,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:cU(),content:$.trim(),tags:z,createdAt:Y,updatedAt:Y};return F0=[...F0,J],mQ(),J}function dQ($){let Z=F0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return F0=[...F0.slice(0,Z),...F0.slice(Z+1)],mQ(),!0}function m4($){let Z=$.toLowerCase().trim();if(!Z)return[...F0];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return F0.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 s2($=20){return[...F0].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function dU(){let $=new Map;for(let Z of F0)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 Z$($){if($.length===0)return"Nenhum memo encontrado.";let Z=new Date,Y=v6(Z),Q=new Date(Z);Q.setDate(Q.getDate()-1);let z=v6(Q),J={},X=[];for(let G of $){let V=new Date(G.updatedAt),U=v6(V),q;if(U===Y)q=`Hoje (${h6(V)})`;else if(U===z)q=`Ontem (${h6(V)})`;else q=h6(V);if(!J[q])J[q]=[],X.push(q);let H=G.tags.length>0?` [${G.tags.map((N)=>`#${N}`).join(" ")}]`:"",B=G.content.length>80?G.content.slice(0,80).replace(/\n/g," ")+"...":G.content.replace(/\n/g," ");J[q].push(` ${B}${H} {${G.id}}`)}let K=X.map((G)=>` ${G}:
186
+ ${J[G].map((V)=>` ${V}`).join(`
187
+ `)}`);return`Memos (${$.length}):
188
+ ${K.join(`
189
+
190
+ `)}`}function cQ(){let $=dU();if($.length===0)return"Nenhuma tag.";return`Tags:
188
191
  ${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
189
- `)}`}function jq(){return Rq().slice(0,8)}n();async function u4($){if(L)return Pq($);return b6($)}async function Pq($){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(`
190
- `);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 b6($);return V||"Email aberto no Outlook."}catch{return b6($)}}async function b6($){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],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 m4($){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(`
191
- `)}n();u();p0();import{existsSync as d4,mkdirSync as uQ,readFileSync as Aq,writeFileSync as Dq,unlinkSync as Tq}from"fs";import{join as c4}from"path";import{randomUUID as Iq}from"crypto";var y6="",m=[],Sq=null,mQ=()=>c4(y6,"scheduler.json"),wq="Smolerclaw_";function pQ($,Z){if(y6=$,Sq=Z??null,!d4($))uQ($,{recursive:!0});if(yq(),L)bq().catch(()=>{})}async function l4($,Z,Y,Q,z,J){let X=_q(),K=`${wq}${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(L)await p4(G);return m=[...m,G],_$(),G}async function o4($){let Z=$.toLowerCase(),Y=m.findIndex((z)=>z.id===$||z.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=m[Y];if(L)await x6(Q.taskName,Q.id);return m=[...m.slice(0,Y),...m.slice(Y+1)],_$(),!0}async function i4($){let Z=e4($);if(!Z||Z.enabled)return null;if(L)await p4(Z);return m=m.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),_$(),m.find((Y)=>Y.id===Z.id)??null}async function r4($){let Z=e4($);if(!Z||!Z.enabled)return null;if(L)await x6(Z.taskName,void 0);return m=m.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),_$(),m.find((Y)=>Y.id===Z.id)??null}function s2($=!1){return $?[...m]:m.filter((Z)=>Z.enabled)}function dQ($){return e4($)}async function n4($){let Z=e4($);if(!Z)return"Agendamento nao encontrado.";if(L){let Y=await a0("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return m=m.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),_$(),`Agendamento "${Z.name}" executado.`}function t2($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",z=xq(Y),J=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${z} [${J}] (${Q})`});return`Agendamentos (${$.length}):
192
+ `)}`}function cU(){return mU().slice(0,8)}function v6($){let Z=$.getFullYear(),Y=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0");return`${Z}-${Y}-${Q}`}function h6($){return $.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}a();async function p4($){if(L)return lU($);return g6($)}async function lU($){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(`
193
+ `);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 g6($);return V||"Email aberto no Outlook."}catch{return g6($)}}async function g6($){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],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 d4($){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(`
194
+ `)}a();u();d0();import{existsSync as l4,mkdirSync as nQ,readFileSync as oU,writeFileSync as iU,unlinkSync as nU}from"fs";import{join as o4}from"path";import{randomUUID as rU}from"crypto";var u6="",p=[],aU=null,rQ=()=>o4(u6,"scheduler.json"),sU="Smolerclaw_";function aQ($,Z){if(u6=$,aU=Z??null,!l4($))nQ($,{recursive:!0});if(Zq(),L)$q().catch(()=>{})}async function i4($,Z,Y,Q,z,J){let X=Yq(),K=`${sU}${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(L)await c4(G);return p=[...p,G],x$(),G}async function n4($){let Z=$.toLowerCase(),Y=p.findIndex((z)=>z.id===$||z.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=p[Y];if(L)await p6(Q.taskName,Q.id);return p=[...p.slice(0,Y),...p.slice(Y+1)],x$(),!0}async function r4($){let Z=Z5($);if(!Z||Z.enabled)return null;if(L)await c4(Z);return p=p.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),x$(),p.find((Y)=>Y.id===Z.id)??null}async function a4($){let Z=Z5($);if(!Z||!Z.enabled)return null;if(L)await p6(Z.taskName,void 0);return p=p.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),x$(),p.find((Y)=>Y.id===Z.id)??null}function t2($=!1){return $?[...p]:p.filter((Z)=>Z.enabled)}function sQ($){return Z5($)}async function s4($){let Z=Z5($);if(!Z)return"Agendamento nao encontrado.";if(L){let Y=await s0("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return p=p.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),x$(),`Agendamento "${Z.name}" executado.`}function e2($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",z=Qq(Y),J=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${z} [${J}] (${Q})`});return`Agendamentos (${$.length}):
192
195
  ${Z.join(`
193
- `)}`}function _6($){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: ${hQ($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${hQ($.lastRun)}`);return Z.join(`
194
- `)}function a4($){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 s4($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return gQ(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let J=new Date(Y);return J.setDate(J.getDate()+1),gQ(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 t4($){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 p4($){let Z=fq($),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 a0("Create",$.taskName,Y)}catch{}}async function x6($,Z){try{await a0("Delete",$,["/F"])}catch{}if(Z)kq(Z)}function cQ(){let $=c4(y6,"scripts");if(!d4($))uQ($,{recursive:!0});return $}function vQ($,Z,Y){let Q=cQ(),z=c4(Q,`toast_${$}.ps1`),J=`# Toast notification script for smolerclaw
196
+ `)}`}function m6($){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: ${oQ($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${oQ($.lastRun)}`);return Z.join(`
197
+ `)}function t4($){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 e4($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return iQ(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let J=new Date(Y);return J.setDate(J.getDate()+1),iQ(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 $5($){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 c4($){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 s0("Create",$.taskName,Y)}catch{}}async function p6($,Z){try{await s0("Delete",$,["/F"])}catch{}if(Z)tU(Z)}function tQ(){let $=o4(u6,"scripts");if(!l4($))nQ($,{recursive:!0});return $}function lQ($,Z,Y){let Q=tQ(),z=o4(Q,`toast_${$}.ps1`),J=`# Toast notification script for smolerclaw
195
198
  # Job ID: ${$}
196
199
  # Generated: ${new Date().toISOString()}
197
200
 
@@ -217,82 +220,82 @@ $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
217
220
  $xml.LoadXml($template)
218
221
  $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
219
222
  [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show($toast)
220
- `,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(J,"utf-8")]);return Dq(z,K),z}function kq($){let Z=c4(cQ(),`toast_${$}.ps1`);try{if(d4(Z))Tq(Z)}catch{}}function fq($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${vQ($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${vQ($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function bq(){if(!L)return;for(let $ of m){if(!$.enabled)continue;try{if((await a0("Query",$.taskName)).exitCode!==0)await p4($)}catch{await p4($)}}}function lQ(){}async function oQ(){let $=0;for(let Z of m){if(L)await x6(Z.taskName,Z.id);$++}return m=[],_$(),`${$} agendamento(s) removido(s).`}function yq(){let $=mQ();if(!d4($)){m=[];return}try{m=JSON.parse(Aq($,"utf-8"))}catch{m=[]}}function _$(){A(mQ(),JSON.stringify(m,null,2))}function _q(){return Iq().slice(0,8)}function e4($){let Z=$.toLowerCase();return m.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function xq($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${vq($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function vq($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function hQ($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function gQ($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}u();import{existsSync as rQ,mkdirSync as hq,readFileSync as gq}from"fs";import{join as uq}from"path";import{randomUUID as mq}from"crypto";var nQ="",S1=[],aQ=()=>uq(nQ,"finance.json");function pq(){A(aQ(),JSON.stringify(S1,null,2))}function dq(){let $=aQ();if(!rQ($)){S1=[];return}try{S1=JSON.parse(gq($,"utf-8"))}catch{S1=[]}}function sQ($){if(nQ=$,!rQ($))hq($,{recursive:!0});dq()}function e2($,Z,Y,Q){let z={id:cq(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return S1=[...S1,z],pq(),z}function $5($,Z){let Y=new Date,Q=$||Y.getFullYear(),z=Z!==void 0?Z:Y.getMonth(),J=S1.filter((U)=>{let H=new Date(U.date);return H.getFullYear()===Q&&H.getMonth()===z});if(J.length===0)return`Nenhuma transacao em ${iQ(z)}/${Q}.`;let X=J.filter((U)=>U.type==="entrada").reduce((U,H)=>U+H.amount,0),K=J.filter((U)=>U.type==="saida").reduce((U,H)=>U+H.amount,0),G=X-K,V=new Map;for(let U of J.filter((H)=>H.type==="saida"))V.set(U.category,(V.get(U.category)||0)+U.amount);let q=[`--- Resumo ${iQ(z)}/${Q} ---`,`Entradas: R$ ${X.toFixed(2)}`,`Saidas: R$ ${K.toFixed(2)}`,`Saldo: R$ ${G.toFixed(2)} ${G>=0?"":"(NEGATIVO)"}`];if(V.size>0){q.push(""),q.push("Saidas por categoria:");let U=[...V.entries()].sort((H,B)=>B[1]-H[1]);for(let[H,B]of U){let N=K>0?Math.round(B/K*100):0;q.push(` ${H.padEnd(15)} R$ ${B.toFixed(2)} (${N}%)`)}}return q.join(`
221
- `)}function v6($=10){let Z=[...S1].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:
223
+ `,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(J,"utf-8")]);return iU(z,K),z}function tU($){let Z=o4(tQ(),`toast_${$}.ps1`);try{if(l4(Z))nU(Z)}catch{}}function eU($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${lQ($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${lQ($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function $q(){if(!L)return;for(let $ of p){if(!$.enabled)continue;try{if((await s0("Query",$.taskName)).exitCode!==0)await c4($)}catch{await c4($)}}}function eQ(){}async function $z(){let $=0;for(let Z of p){if(L)await p6(Z.taskName,Z.id);$++}return p=[],x$(),`${$} agendamento(s) removido(s).`}function Zq(){let $=rQ();if(!l4($)){p=[];return}try{p=JSON.parse(oU($,"utf-8"))}catch{p=[]}}function x$(){P(rQ(),JSON.stringify(p,null,2))}function Yq(){return rU().slice(0,8)}function Z5($){let Z=$.toLowerCase();return p.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function Qq($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${zq($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function zq($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function oQ($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function iQ($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}u();import{existsSync as Yz,mkdirSync as Jq,readFileSync as Xq}from"fs";import{join as Kq}from"path";import{randomUUID as Gq}from"crypto";var Qz="",w1=[],zz=()=>Kq(Qz,"finance.json");function Vq(){P(zz(),JSON.stringify(w1,null,2))}function Uq(){let $=zz();if(!Yz($)){w1=[];return}try{w1=JSON.parse(Xq($,"utf-8"))}catch{w1=[]}}function Jz($){if(Qz=$,!Yz($))Jq($,{recursive:!0});Uq()}function $8($,Z,Y,Q){let z={id:qq(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return w1=[...w1,z],Vq(),z}function Y5($,Z){let Y=new Date,Q=$||Y.getFullYear(),z=Z!==void 0?Z:Y.getMonth(),J=w1.filter((q)=>{let H=new Date(q.date);return H.getFullYear()===Q&&H.getMonth()===z});if(J.length===0)return`Nenhuma transacao em ${Zz(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 ${Zz(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 N=K>0?Math.round(B/K*100):0;U.push(` ${H.padEnd(15)} R$ ${B.toFixed(2)} (${N}%)`)}}return U.join(`
224
+ `)}function d6($=10){let Z=[...w1].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:
222
225
  ${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(`
223
- `)}`}function cq(){return mq().slice(0,8)}function iQ($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}d0();var h6={debug:0,info:1,warn:2,error:3};function lq(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in h6)return $;if(process.env.DEBUG)return"debug";return"warn"}function oq($){return h6[$]>=h6[lq()]}function iq($,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 Z5($,Z,Y){if(!oq($))return;let Q=iq($,Z,Y);process.stderr.write(Q+`
224
- `)}var g={debug:($,Z)=>Z5("debug",$,Z),info:($,Z)=>Z5("info",$,Z),warn:($,Z)=>Z5("warn",$,Z),error:($,Z)=>Z5("error",$,Z)};var tQ={maxSingleAmount:1e4,dailyAlertThreshold:1000,duplicateWindowMs:300000,blockOnFailure:!1},w1={...tQ},Y5=[],Q5=[];function eQ($){w1={...tQ,...$},Y5=[],Q5=[]}function $8($,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>w1.maxSingleAmount){let V=`Valor alto: R$ ${Z.toFixed(2)} excede limite de R$ ${w1.maxSingleAmount.toFixed(2)}`;if(w1.blockOnFailure)J=V;else z.push(V)}let X=Date.now(),K=Y5.find((V)=>V.type===$&&V.amount===Math.abs(Z)&&V.category===Y.toLowerCase().trim()&&X-V.timestamp<w1.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=$z(),U=Q5.filter((H)=>H.type==="saida"&&H.date===V).reduce((H,B)=>H+B.amount,0)+Math.abs(Z);if(U>w1.dailyAlertThreshold)z.push(`Alerta: gasto diario projetado R$ ${U.toFixed(2)} excede limite de R$ ${w1.dailyAlertThreshold.toFixed(2)}`)}let G=J===null;return rq($,Z,Y,Q,G,z),{allowed:G,warnings:z,blocked:J}}function Z8($,Z,Y){let Q=Math.abs(Z),z=Date.now(),J={type:$,amount:Q,category:Y.toLowerCase().trim(),timestamp:z},X=z-w1.duplicateWindowMs*2;Y5=[...Y5.filter((G)=>G.timestamp>X),J];let K=$z();Q5=[...Q5.filter((G)=>G.date===K),{type:$,amount:Q,date:K}]}function Y8($){if($.blocked)return`BLOQUEADO: ${$.blocked}`;if($.warnings.length===0)return"";return $.warnings.map((Z)=>`AVISO: ${Z}`).join(`
225
- `)}function $z(){return new Date().toISOString().slice(0,10)}function rq($,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)g.debug("Finance guard warnings",{type:$,amount:Z,category:Y,warnings:J})}u();import{existsSync as Zz,mkdirSync as nq,readFileSync as aq}from"fs";import{join as sq}from"path";import{randomUUID as tq}from"crypto";var Yz="",k1=[],Qz=()=>sq(Yz,"decisions.json");function eq(){A(Qz(),JSON.stringify(k1,null,2))}function $U(){let $=Qz();if(!Zz($)){k1=[];return}try{k1=JSON.parse(aq($,"utf-8"))}catch{k1=[]}}function zz($){if(Yz=$,!Zz($))nq($,{recursive:!0});$U()}function Jz($,Z,Y,Q,z=[]){let J={id:ZU(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:z.map((X)=>X.toLowerCase()),date:new Date().toISOString()};return k1=[...k1,J],eq(),J}function Z$($){let Z=$.toLowerCase();return k1.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 z5($=15){return[...k1].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function x$($){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}):
226
+ `)}`}function qq(){return Gq().slice(0,8)}function Zz($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}c0();var c6={debug:0,info:1,warn:2,error:3};function Hq(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in c6)return $;if(process.env.DEBUG)return"debug";return"warn"}function Wq($){return c6[$]>=c6[Hq()]}function Bq($,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 Q5($,Z,Y){if(!Wq($))return;let Q=Bq($,Z,Y);process.stderr.write(Q+`
227
+ `)}var m={debug:($,Z)=>Q5("debug",$,Z),info:($,Z)=>Q5("info",$,Z),warn:($,Z)=>Q5("warn",$,Z),error:($,Z)=>Q5("error",$,Z)};var Xz={maxSingleAmount:1e4,dailyAlertThreshold:1000,duplicateWindowMs:300000,blockOnFailure:!1},k1={...Xz},z5=[],J5=[];function Kz($){k1={...Xz,...$},z5=[],J5=[]}function Z8($,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>k1.maxSingleAmount){let V=`Valor alto: R$ ${Z.toFixed(2)} excede limite de R$ ${k1.maxSingleAmount.toFixed(2)}`;if(k1.blockOnFailure)J=V;else z.push(V)}let X=Date.now(),K=z5.find((V)=>V.type===$&&V.amount===Math.abs(Z)&&V.category===Y.toLowerCase().trim()&&X-V.timestamp<k1.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=Gz(),q=J5.filter((H)=>H.type==="saida"&&H.date===V).reduce((H,B)=>H+B.amount,0)+Math.abs(Z);if(q>k1.dailyAlertThreshold)z.push(`Alerta: gasto diario projetado R$ ${q.toFixed(2)} excede limite de R$ ${k1.dailyAlertThreshold.toFixed(2)}`)}let G=J===null;return Nq($,Z,Y,Q,G,z),{allowed:G,warnings:z,blocked:J}}function Y8($,Z,Y){let Q=Math.abs(Z),z=Date.now(),J={type:$,amount:Q,category:Y.toLowerCase().trim(),timestamp:z},X=z-k1.duplicateWindowMs*2;z5=[...z5.filter((G)=>G.timestamp>X),J];let K=Gz();J5=[...J5.filter((G)=>G.date===K),{type:$,amount:Q,date:K}]}function Q8($){if($.blocked)return`BLOQUEADO: ${$.blocked}`;if($.warnings.length===0)return"";return $.warnings.map((Z)=>`AVISO: ${Z}`).join(`
228
+ `)}function Gz(){return new Date().toISOString().slice(0,10)}function Nq($,Z,Y,Q,z,J){let X=!z?"error":J.length>0?"warning":"info";if(z0("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})}u();import{existsSync as Vz,mkdirSync as Oq,readFileSync as Mq}from"fs";import{join as Cq}from"path";import{randomUUID as Eq}from"crypto";var Uz="",f1=[],qz=()=>Cq(Uz,"decisions.json");function Rq(){P(qz(),JSON.stringify(f1,null,2))}function Fq(){let $=qz();if(!Vz($)){f1=[];return}try{f1=JSON.parse(Mq($,"utf-8"))}catch{f1=[]}}function Hz($){if(Uz=$,!Vz($))Oq($,{recursive:!0});Fq()}function Wz($,Z,Y,Q,z=[]){let J={id:Lq(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:z.map((X)=>X.toLowerCase()),date:new Date().toISOString()};return f1=[...f1,J],Rq(),J}function Y$($){let Z=$.toLowerCase();return f1.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 X5($=15){return[...f1].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function v$($){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}):
226
229
  ${Z.join(`
227
- `)}`}function ZU(){return tq().slice(0,8)}z8();u();import{existsSync as Hz,mkdirSync as GU,readFileSync as VU}from"fs";import{join as qU}from"path";import{randomUUID as UU}from"crypto";var Wz="",f={people:[],interactions:[],delegations:[]},Bz=()=>qU(Wz,"people.json");function K5(){A(Bz(),JSON.stringify(f,null,2))}function HU(){let $=Bz();if(!Hz($)){f={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(VU($,"utf-8"));f={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{f={people:[],interactions:[],delegations:[]}}}function Nz($){if(Wz=$,!Hz($))GU($,{recursive:!0});HU()}function G5($,Z,Y,Q){let z={id:s6(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),createdAt:new Date().toISOString()};return f={...f,people:[...f.people,z]},K5(),z}function J1($){let Z=$.toLowerCase();return f.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function V5($){if($)return f.people.filter((Z)=>Z.group===$);return[...f.people]}function Oz($,Z,Y,Q){let z=J1($);if(!z)return null;let J={id:s6(),personId:z.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return f={...f,interactions:[...f.interactions,J]},K5(),J}function WU($,Z=10){let Y=J1($);if(!Y)return[];return[...f.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 v$(){let $=new Date,Z=[];for(let Y of f.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let z=f.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 q5($,Z,Y){let Q=J1($);if(!Q)return null;let z={id:s6(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return f={...f,delegations:[...f.delegations,z]},K5(),z}function Cz($,Z,Y){if(!f.delegations.find((z)=>z.id===$))return null;return f={...f,delegations:f.delegations.map((z)=>z.id===$?{...z,status:Z,notes:Y||z.notes}:z)},K5(),f.delegations.find((z)=>z.id===$)||null}function Y$($,Z=!0){let Y=[...f.delegations];if($){let z=J1($);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 Mz={equipe:"Equipe",familia:"Familia",contato:"Contato"};function U5($){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(`--- ${Mz[z]} ---
230
+ `)}`}function Lq(){return Eq().slice(0,8)}J8();u();import{existsSync as Rz,mkdirSync as Sq,readFileSync as wq}from"fs";import{join as kq}from"path";import{randomUUID as fq}from"crypto";var Fz="",y={people:[],interactions:[],delegations:[]},Lz=()=>kq(Fz,"people.json");function V5(){P(Lz(),JSON.stringify(y,null,2))}function bq(){let $=Lz();if(!Rz($)){y={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(wq($,"utf-8"));y={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{y={people:[],interactions:[],delegations:[]}}}function jz($){if(Fz=$,!Rz($))Sq($,{recursive:!0});bq()}function U5($,Z,Y,Q){let z={id:QZ(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),createdAt:new Date().toISOString()};return y={...y,people:[...y.people,z]},V5(),z}function X1($){let Z=$.toLowerCase();return y.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function q5($){if($)return y.people.filter((Z)=>Z.group===$);return[...y.people]}function Pz($,Z,Y,Q){let z=X1($);if(!z)return null;let J={id:QZ(),personId:z.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return y={...y,interactions:[...y.interactions,J]},V5(),J}function yq($,Z=10){let Y=X1($);if(!Y)return[];return[...y.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 h$(){let $=new Date,Z=[];for(let Y of y.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let z=y.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 H5($,Z,Y){let Q=X1($);if(!Q)return null;let z={id:QZ(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return y={...y,delegations:[...y.delegations,z]},V5(),z}function Az($,Z,Y){if(!y.delegations.find((z)=>z.id===$))return null;return y={...y,delegations:y.delegations.map((z)=>z.id===$?{...z,status:Z,notes:Y||z.notes}:z)},V5(),y.delegations.find((z)=>z.id===$)||null}function Q$($,Z=!0){let Y=[...y.delegations];if($){let z=X1($);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 Tz={equipe:"Equipe",familia:"Familia",contato:"Contato"};function W5($){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(`--- ${Tz[z]} ---
228
231
  ${X.join(`
229
232
  `)}`)}return Y.join(`
230
233
 
231
- `)}function H5($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${Mz[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=WU($.id,5);if(Y.length>0){Z.push(`
232
- 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=Y$($.id);if(Q.length>0){Z.push(`
233
- Tarefas delegadas:`);for(let z of Q){let J=z.status==="atrasado"?"!!":z.status==="em_andamento"?">>":" ",X=z.dueDate?` (${t6(z.dueDate)})`:"";Z.push(` ${J} ${z.task}${X} [${z.status}]`)}}return Z.join(`
234
- `)}function W5($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let z=f.people.find((K)=>K.id===Y.personId)?.name||"?",J=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",X=Y.dueDate?` (${t6(Y.dueDate)})`:"";return`${J}${z}: ${Y.task}${X} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
234
+ `)}function B5($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${Tz[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=yq($.id,5);if(Y.length>0){Z.push(`
235
+ 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=Q$($.id);if(Q.length>0){Z.push(`
236
+ Tarefas delegadas:`);for(let z of Q){let J=z.status==="atrasado"?"!!":z.status==="em_andamento"?">>":" ",X=z.dueDate?` (${zZ(z.dueDate)})`:"";Z.push(` ${J} ${z.task}${X} [${z.status}]`)}}return Z.join(`
237
+ `)}function N5($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let z=y.people.find((K)=>K.id===Y.personId)?.name||"?",J=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",X=Y.dueDate?` (${zZ(Y.dueDate)})`:"";return`${J}${z}: ${Y.task}${X} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
235
238
  ${Z.join(`
236
- `)}`}function B5($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${t6(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
239
+ `)}`}function O5($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${zZ(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
237
240
  ${Z.join(`
238
- `)}`}function Ez(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
239
- `);let Z=f.people.filter((V)=>V.group==="equipe").length,Y=f.people.filter((V)=>V.group==="familia").length,Q=f.people.filter((V)=>V.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let z=v$();if(z.length>0){$.push(`
240
- !! ${z.length} follow-up(s) pendente(s):`);for(let{person:V,interaction:q}of z.slice(0,5))$.push(` ${V.name}: ${q.summary}`)}let J=Y$(),X=J.filter((V)=>V.status==="atrasado"),K=J.filter((V)=>V.status==="pendente"||V.status==="em_andamento");if(X.length>0){$.push(`
241
- !! ${X.length} delegacao(oes) atrasada(s):`);for(let V of X.slice(0,5)){let q=f.people.find((U)=>U.id===V.personId);$.push(` ${q?.name}: ${V.task}`)}}if(K.length>0)$.push(`
242
- ${K.length} delegacao(oes) em andamento`);let G=[...f.interactions].sort((V,q)=>new Date(q.date).getTime()-new Date(V.date).getTime()).slice(0,3);if(G.length>0){$.push(`
243
- Ultimas interacoes:`);for(let V of G){let q=f.people.find((H)=>H.id===V.personId),U=new Date(V.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${U}] ${q?.name}: ${V.summary}`)}}return $.push(`
241
+ `)}`}function Dz(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
242
+ `);let Z=y.people.filter((V)=>V.group==="equipe").length,Y=y.people.filter((V)=>V.group==="familia").length,Q=y.people.filter((V)=>V.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let z=h$();if(z.length>0){$.push(`
243
+ !! ${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=Q$(),X=J.filter((V)=>V.status==="atrasado"),K=J.filter((V)=>V.status==="pendente"||V.status==="em_andamento");if(X.length>0){$.push(`
244
+ !! ${X.length} delegacao(oes) atrasada(s):`);for(let V of X.slice(0,5)){let U=y.people.find((q)=>q.id===V.personId);$.push(` ${U?.name}: ${V.task}`)}}if(K.length>0)$.push(`
245
+ ${K.length} delegacao(oes) em andamento`);let G=[...y.interactions].sort((V,U)=>new Date(U.date).getTime()-new Date(V.date).getTime()).slice(0,3);if(G.length>0){$.push(`
246
+ Ultimas interacoes:`);for(let V of G){let U=y.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(`
244
247
  ========================`),$.join(`
245
- `)}function s6(){return UU().slice(0,8)}function t6($){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"})}u();import{existsSync as Rz,mkdirSync as BU,readFileSync as NU}from"fs";import{join as OU}from"path";import{randomUUID as CU}from"crypto";var Fz="",s=[],Lz=()=>OU(Fz,"materials.json");function e6(){A(Lz(),JSON.stringify(s,null,2))}function MU(){let $=Lz();if(!Rz($)){s=[];return}try{s=JSON.parse(NU($,"utf-8"))}catch{s=[]}}function jz($){if(Fz=$,!Rz($))BU($,{recursive:!0});MU()}function N5($,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:EU(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:K,createdAt:z,updatedAt:z};return s=[...s,G],e6(),G}function Pz($,Z){let Y=s.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 s=s.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),e6(),s.find((V)=>V.id===$)||null}function O5($){let Z=s.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return s=[...s.slice(0,Z),...s.slice(Z+1)],e6(),!0}function Az($){return s.find((Z)=>Z.id===$)||null}function h$($){let Z=$.toLowerCase().trim();if(!Z)return[...s];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),z=Y||Q?Z.slice(1):Z;return s.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 g$($=30,Z){let Y=[...s];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 Dz(){let $=new Map;for(let Z of s)$.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 Tz(){if(s.length===0)return"";let $=Dz(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=s.filter((z)=>z.category===Y).sort((z,J)=>new Date(J.updatedAt).getTime()-new Date(z.updatedAt).getTime());Z.push(`
248
+ `)}function QZ(){return fq().slice(0,8)}function zZ($){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"})}u();import{existsSync as Iz,mkdirSync as _q,readFileSync as xq}from"fs";import{join as vq}from"path";import{randomUUID as hq}from"crypto";var Sz="",t=[],wz=()=>vq(Sz,"materials.json");function JZ(){P(wz(),JSON.stringify(t,null,2))}function gq(){let $=wz();if(!Iz($)){t=[];return}try{t=JSON.parse(xq($,"utf-8"))}catch{t=[]}}function kz($){if(Sz=$,!Iz($))_q($,{recursive:!0});gq()}function M5($,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:uq(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:K,createdAt:z,updatedAt:z};return t=[...t,G],JZ(),G}function fz($,Z){let Y=t.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 t=t.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),JZ(),t.find((V)=>V.id===$)||null}function C5($){let Z=t.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return t=[...t.slice(0,Z),...t.slice(Z+1)],JZ(),!0}function bz($){return t.find((Z)=>Z.id===$)||null}function g$($){let Z=$.toLowerCase().trim();if(!Z)return[...t];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),z=Y||Q?Z.slice(1):Z;return t.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 u$($=30,Z){let Y=[...t];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 yz(){let $=new Map;for(let Z of t)$.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 _z(){if(t.length===0)return"";let $=yz(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=t.filter((z)=>z.category===Y).sort((z,J)=>new Date(J.updatedAt).getTime()-new Date(z.updatedAt).getTime());Z.push(`
246
249
  [${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(`
247
- `)}function f1($){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}):
250
+ `)}function b1($){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}):
248
251
  ${Z.join(`
249
- `)}`}function Iz($){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}} ---
252
+ `)}`}function xz($){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}} ---
250
253
  Titulo: ${$.title}
251
254
  Categoria: ${$.category}
252
255
 
253
256
  ${$.content}
254
257
 
255
258
  ${Q}
256
- ${z}`}function Sz(){let $=Dz();if($.length===0)return"Nenhuma categoria.";return`Categorias:
259
+ ${z}`}function vz(){let $=yz();if($.length===0)return"Nenhuma categoria.";return`Categorias:
257
260
  ${$.map((Y)=>` @${Y.category} (${Y.count})`).join(`
258
- `)}`}function EU(){return CU().slice(0,8)}u();import{existsSync as _0,mkdirSync as RU,readFileSync as M5}from"fs";import{join as F0,basename as FU}from"path";import{randomUUID as LU}from"crypto";var u$="",v0=[],x0=[],o0=[],b1=null,wz=()=>F0(u$,"projects.json"),kz=()=>F0(u$,"work-sessions.json"),fz=()=>F0(u$,"opportunities.json"),bz=()=>F0(u$,"active-project.txt");function jU(){A(wz(),JSON.stringify(v0,null,2))}function ZZ(){A(kz(),JSON.stringify(x0,null,2))}function yz(){A(fz(),JSON.stringify(o0,null,2))}function PU(){A(bz(),b1||"")}function AU(){v0=$Z(wz,[]),x0=$Z(kz,[]),o0=$Z(fz,[]);let $=bz();if(_0($))try{b1=M5($,"utf-8").trim()||null}catch{b1=null}}function $Z($,Z){let Y=$();if(!_0(Y))return Z;try{return JSON.parse(M5(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 _z($){if(u$=$,!_0($))RU($,{recursive:!0});AU()}function YZ($,Z,Y="",Q=[],z=[]){let J={id:QZ(),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 v0=[...v0,J],jU(),J}function E5($){let Z=$.toLowerCase().trim();return v0.find((Y)=>Y.id===$)||v0.find((Y)=>Y.name.toLowerCase()===Z)||v0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function m$($=!1){return($?v0.filter((Y)=>Y.active):[...v0]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function p$($){let Z=E5($);if(!Z)return null;return b1=Z.id,PU(),Z}function y1(){if(!b1)return null;return v0.find(($)=>$.id===b1)||null}function R5($,Z=""){if(!v0.find((z)=>z.id===$))return null;DU($);let Q={id:QZ(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return x0=[...x0,Q],ZZ(),Q}function F5($,Z){let Y=x0.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 x0=x0.map((X)=>X.id===$?{...X,endedAt:Q.toISOString(),durationMinutes:J,notes:Z?`${X.notes}
259
- ${Z}`.trim():X.notes}:X),ZZ(),x0.find((X)=>X.id===$)||null}function DU($){let Z=new Date;x0=x0.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}),ZZ()}function _1($){return x0.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function TU($,Z,Y){let Q=Y||new Date;return x0.filter((z)=>{if(z.projectId!==$)return!1;let J=new Date(z.startedAt);return J>=Z&&J<=Q})}async function IU($,Z="1 day ago"){if(!_0(F0($,".git")))return null;try{let Y=await C5(["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(`
260
- `).filter(Boolean),z=[...new Set(Q.map((N)=>N.split("|||")[0]))],J=Q.map((N)=>N.split("|||")[1]||"").filter(Boolean),X=await C5(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),K=await C5(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),G=0,V=0,q=0;if(K.ok&&K.stdout.trim())for(let N of K.stdout.trim().split(`
261
- `)){let C=N.match(/(\d+)\s+files?\s+changed/),M=N.match(/(\d+)\s+insertions?/),F=N.match(/(\d+)\s+deletions?/);if(C)G+=parseInt(C[1]);if(M)V+=parseInt(M[1]);if(F)q+=parseInt(F[1])}let U=await C5(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),H=new Map;if(U.ok&&U.stdout.trim())for(let N of U.stdout.trim().split(`
262
- `).filter(Boolean))H.set(N,(H.get(N)||0)+1);let B=[...H.entries()].sort((N,C)=>C[1]-N[1]).slice(0,10).map(([N])=>N);return{commits:Q.length,authors:z,filesChanged:G,insertions:V,deletions:q,topFiles:B,messages:J}}catch{return null}}async function C5($,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 xz($,Z,Y,Q=[],z="media",J=null){let X=new Date().toISOString(),K={id:QZ(),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 o0=[...o0,K],yz(),K}function vz($,Z){if(!o0.find((Q)=>Q.id===$))return null;return o0=o0.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),yz(),o0.find((Q)=>Q.id===$)||null}function L5($,Z){let Y=[...o0];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 j5($,Z="today",Y="pt"){let Q=E5($);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 IU(Q.path,X),G=TU(Q.id,J),V=G.reduce((H,B)=>H+B.durationMinutes,0),q=0;try{let H=F0(u$,"tasks.json");if(_0(H))q=JSON.parse(M5(H,"utf-8")).filter((N)=>{if(!N.done)return!1;return new Date(N.createdAt)>=J}).length}catch{}let U=SU(Q,Z,K,G,V,q,Y);return{project:Q,period:Z,gitSummary:K,sessions:G,totalMinutes:V,completedTasks:q,markdown:U}}function SU($,Z,Y,Q,z,J,X){let K=X==="pt",G=[],V=new Date,q=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} (${q})`),G.push(`**${K?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)G.push(`**Tech:** ${$.techStack.join(", ")}`);G.push("");let U=Math.floor(z/60),H=z%60;if(G.push(`## ${K?"Tempo Trabalhado":"Time Tracked"}`),G.push(`- **${K?"Total":"Total"}:** ${U}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 N=new Date(B.startedAt).toLocaleTimeString(K?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),C=B.durationMinutes>0?`${B.durationMinutes}m`:K?"em andamento":"ongoing",M=B.notes?` \u2014 ${B.notes}`:"";G.push(`- ${N} (${C})${M}`)}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(`
263
- `)}function P5($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===b1?" [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}):
261
+ `)}`}function uq(){return hq().slice(0,8)}u();import{existsSync as x0,mkdirSync as mq,readFileSync as R5}from"fs";import{join as L0,basename as pq}from"path";import{randomUUID as dq}from"crypto";var m$="",h0=[],v0=[],i0=[],y1=null,hz=()=>L0(m$,"projects.json"),gz=()=>L0(m$,"work-sessions.json"),uz=()=>L0(m$,"opportunities.json"),mz=()=>L0(m$,"active-project.txt");function cq(){P(hz(),JSON.stringify(h0,null,2))}function KZ(){P(gz(),JSON.stringify(v0,null,2))}function pz(){P(uz(),JSON.stringify(i0,null,2))}function lq(){P(mz(),y1||"")}function oq(){h0=XZ(hz,[]),v0=XZ(gz,[]),i0=XZ(uz,[]);let $=mz();if(x0($))try{y1=R5($,"utf-8").trim()||null}catch{y1=null}}function XZ($,Z){let Y=$();if(!x0(Y))return Z;try{return JSON.parse(R5(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 dz($){if(m$=$,!x0($))mq($,{recursive:!0});oq()}function GZ($,Z,Y="",Q=[],z=[]){let J={id:VZ(),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 h0=[...h0,J],cq(),J}function F5($){let Z=$.toLowerCase().trim();return h0.find((Y)=>Y.id===$)||h0.find((Y)=>Y.name.toLowerCase()===Z)||h0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function p$($=!1){return($?h0.filter((Y)=>Y.active):[...h0]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function d$($){let Z=F5($);if(!Z)return null;return y1=Z.id,lq(),Z}function _1(){if(!y1)return null;return h0.find(($)=>$.id===y1)||null}function L5($,Z=""){if(!h0.find((z)=>z.id===$))return null;iq($);let Q={id:VZ(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return v0=[...v0,Q],KZ(),Q}function j5($,Z){let Y=v0.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 v0=v0.map((X)=>X.id===$?{...X,endedAt:Q.toISOString(),durationMinutes:J,notes:Z?`${X.notes}
262
+ ${Z}`.trim():X.notes}:X),KZ(),v0.find((X)=>X.id===$)||null}function iq($){let Z=new Date;v0=v0.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}),KZ()}function x1($){return v0.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function nq($,Z,Y){let Q=Y||new Date;return v0.filter((z)=>{if(z.projectId!==$)return!1;let J=new Date(z.startedAt);return J>=Z&&J<=Q})}async function rq($,Z="1 day ago"){if(!x0(L0($,".git")))return null;try{let Y=await E5(["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(`
263
+ `).filter(Boolean),z=[...new Set(Q.map((N)=>N.split("|||")[0]))],J=Q.map((N)=>N.split("|||")[1]||"").filter(Boolean),X=await E5(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),K=await E5(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),G=0,V=0,U=0;if(K.ok&&K.stdout.trim())for(let N of K.stdout.trim().split(`
264
+ `)){let M=N.match(/(\d+)\s+files?\s+changed/),C=N.match(/(\d+)\s+insertions?/),F=N.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 E5(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),H=new Map;if(q.ok&&q.stdout.trim())for(let N of q.stdout.trim().split(`
265
+ `).filter(Boolean))H.set(N,(H.get(N)||0)+1);let B=[...H.entries()].sort((N,M)=>M[1]-N[1]).slice(0,10).map(([N])=>N);return{commits:Q.length,authors:z,filesChanged:G,insertions:V,deletions:U,topFiles:B,messages:J}}catch{return null}}async function E5($,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 cz($,Z,Y,Q=[],z="media",J=null){let X=new Date().toISOString(),K={id:VZ(),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 i0=[...i0,K],pz(),K}function lz($,Z){if(!i0.find((Q)=>Q.id===$))return null;return i0=i0.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),pz(),i0.find((Q)=>Q.id===$)||null}function P5($,Z){let Y=[...i0];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 A5($,Z="today",Y="pt"){let Q=F5($);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 rq(Q.path,X),G=nq(Q.id,J),V=G.reduce((H,B)=>H+B.durationMinutes,0),U=0;try{let H=L0(m$,"tasks.json");if(x0(H))U=JSON.parse(R5(H,"utf-8")).filter((N)=>{if(!N.done)return!1;return new Date(N.createdAt)>=J}).length}catch{}let q=aq(Q,Z,K,G,V,U,Y);return{project:Q,period:Z,gitSummary:K,sessions:G,totalMinutes:V,completedTasks:U,markdown:q}}function aq($,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 N=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(`- ${N} (${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(`
266
+ `)}function T5($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===y1?" [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}):
264
267
  ${Z.join(`
265
- `)}`}function A5($){let Z=$.id===b1?" [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=_1($.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(`
266
- `)}function D5($){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}):
268
+ `)}`}function D5($){let Z=$.id===y1?" [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=x1($.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(`
269
+ `)}function I5($){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}):
267
270
  ${Z.join(`
268
- `)}`}function T5(){let $=y1();if(!$)return"";let Z=_1($.id),Y=o0.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(`
269
- `)}function I5($){let Z=v0.find((z)=>z.path===$);if(Z)return Z;if(!_0(F0($,".git")))return null;let Y=[];if(_0(F0($,"package.json")))try{let z=JSON.parse(M5(F0($,"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(_0(F0($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(_0(F0($,"Cargo.toml")))Y.push("rust");if(_0(F0($,"go.mod")))Y.push("go");if(_0(F0($,"requirements.txt"))||_0(F0($,"pyproject.toml")))Y.push("python");let Q=FU($);return YZ(Q,$,"",[],Y)}function QZ(){return LU().slice(0,8)}u();n();import{existsSync as XZ,mkdirSync as wU,readFileSync as uz}from"fs";import{join as mz,basename as kU}from"path";var pz=2,dz="pitwall-baselines.json",fU=0.1,bU=0.05,yU=5000000,_U=512000,hz=2048,xU=120000,k5="",J0=[];function cz($){if(k5=$,!XZ($))wU($,{recursive:!0});cU()}async function gz($,Z){let Q=[...O$(),$],z=process.cpuUsage(),J=Bun.nanoseconds(),X=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),K=setTimeout(()=>X.kill(),xU),G=X.pid,V=vU(G),[,q]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),U=await X.exited;clearTimeout(K);let H=Bun.nanoseconds(),B=process.cpuUsage(z),N=await V,C=q.length>hz?`...${q.slice(-hz)}`:q;return{durationNs:H-J,peakMemoryBytes:N,cpuUserUs:B.user,cpuSystemUs:B.system,exitCode:U,stderr:C.trim()}}async function KZ($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),z=Z.scriptKey||dU($);if(Z.warmup&&Q>1)await gz($,Y);let J=[];for(let q=0;q<Q;q++)J.push(await gz($,Y));let X=J[J.length-1],K=J.map((q)=>q.durationNs),G={durationNs:zZ(K),peakMemoryBytes:Math.max(...J.map((q)=>q.peakMemoryBytes)),cpuUserUs:zZ(J.map((q)=>q.cpuUserUs)),cpuSystemUs:zZ(J.map((q)=>q.cpuSystemUs))},V=Q>1?{min:Math.min(...K),max:Math.max(...K),median:G.durationNs,stddev:pU(K)}:null;return{scriptKey:z,command:$,metrics:G,spread:V,exitCode:X.exitCode,stderr:X.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function vU($){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),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(XZ(Z)){let Q=uz(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function lz($,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),f5(),K}let z={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return J0=[...J0,z],f5(),z}function hU($){return J0.find((Z)=>Z.scriptKey===$)||null}function oz(){return[...J0].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function GZ($){let Z=J0.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return J0=[...J0.slice(0,Z),...J0.slice(Z+1)],f5(),!0}function iz($,Z=[]){GZ($.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],f5(),Q}function VZ($){let Z=hU($.scriptKey),Y=[];if(Z)Y.push(S5("duration",Z.metrics.durationNs,$.metrics.durationNs,yU),S5("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,_U),S5("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),S5("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((J)=>J.severity==="regression"),z=mU($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:z}}function S5($,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>fU)X="regression";else if(J>bU)X="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(J*1e4)/100,absoluteDelta:z,severity:X}}function X1($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function JZ($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function w5($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function gU($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function uU($){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 mU($,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: ${X1($.metrics.durationNs)}`),z.push(` Memoria: ${JZ($.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${w5($.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${w5($.metrics.cpuSystemUs)}`),$.spread){z.push(""),z.push("--- Dispersao ---"),z.push(` Min: ${X1($.spread.min)}`),z.push(` Max: ${X1($.spread.max)}`),z.push(` Mediana: ${X1($.spread.median)}`),z.push(` Stddev: ${X1($.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(`
270
- `);z.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${rz(Z.updatedAt)}) ---`),z.push(` Duracao: ${X1(Z.metrics.durationNs)}`),z.push(` Memoria: ${JZ(Z.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${w5(Z.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${w5(Z.metrics.cpuSystemUs)}`),z.push(""),z.push("--- Comparacao ---");for(let J of Y){let X=J.deltaPercent>=0?"+":"",K=uU(J.metric);z.push(` ${gU(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(`
271
- `)}function rz($){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 nz($){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=rz(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${X1(Y.metrics.durationNs)} | Memoria: ${JZ(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: ${X1(Y.spread.min)} ~ ${X1(Y.spread.max)} (CV ${J}%)`)}Z.push("")}return Z.join(`
272
- `)}function zZ($){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 pU($){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 dU($){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 kU(Z[0])}function cU(){let $=mz(k5,dz);if(!XZ($)){J0=[];return}try{let Z=JSON.parse(uz($,"utf-8"));if(Z.version!==pz&&Z.version!==1){J0=[];return}J0=(Z.baselines||[]).map(lU)}catch{J0=[]}}function lU($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function f5(){if(!k5)return;let $=mz(k5,dz);A($,JSON.stringify({baselines:J0,version:pz},null,2))}n();import{readdirSync as oU,readFileSync as iU,lstatSync as rU}from"fs";import{join as nU,resolve as J8,relative as qZ,dirname as aU,extname as sU}from"path";var tU=[".ts",".tsx",".mts",".cts"],eU=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],$H=new Set($2),az=5000,ZH=5000,sz=new Map;function YH($){let Z=sz.get($);if(Z&&Date.now()-Z.ts<ZH)return Z.graph;return null}function QH($,Z){sz.set($,{graph:Z,ts:Date.now()})}var zH=[/^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 JH($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of zH){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 XH($){let Z=[];function Y(Q){if(Z.length>=az)return;let z;try{z=oU(Q)}catch{return}for(let J of z){if(Z.length>=az)return;if($H.has(J))continue;let X=nU(Q,J),K;try{K=rU(X)}catch{continue}if(K.isSymbolicLink())continue;if(K.isDirectory())Y(X);else if(K.isFile()&&tU.includes(sU(J)))Z.push(X)}}return Y($),Z}function KH($,Z,Y){let Q=aU(Z),z=J8(Q,$);if(Y.has(z))return z;for(let J of eU){let X=z+J;if(Y.has(X))return X}return null}function UZ($){let Z=J8($),Y=YH(Z);if(Y)return Y;let Q=XH(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=iU(G,"utf-8")}catch{continue}let q=JH(V),U=J.get(G);for(let H of q){let B=KH(H,G,z);if(B){U.add(B);let N=X.get(B)||new Set;N.add(G),X.set(B,N)}}}let K={imports:J,importedBy:X,files:Q,root:Z};return QH(Z,K),K}function HZ($,Z){let Y=J8(Z),Q=$.importedBy.get(Y)||new Set,z=[...Q],J=new Set([Y]),X=[],K=new Map,G=0;for(let N of Q)X.push({file:N,depth:1}),J.add(N),K.set(N,1);let V=[],q=0;while(q<X.length){let{file:N,depth:C}=X[q++];if(C>G)G=C;if(!Q.has(N))V.push(N);let M=$.importedBy.get(N)||new Set;for(let F of M)if(!J.has(F))J.add(F),K.set(F,C+1),X.push({file:F,depth:C+1})}let U=tz(Y,$.importedBy,new Set,0),H=(N)=>qZ($.root,N).replace(/\\/g,"/"),B=new Map;for(let[N,C]of K)B.set(H(N),C);return{target:H(Y),directDependents:z.map(H),transitiveDependents:V.map(H),depthMap:B,totalAffected:z.length+V.length,depth:G,tree:ez(U,$.root)}}function tz($,Z,Y,Q){Y.add($);let z=Z.get($)||new Set,J=[];for(let X of z)if(!Y.has(X))J.push(tz(X,Z,Y,Q+1));return{file:$,depth:Q,children:J}}function ez($,Z){return{file:qZ(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>ez(Y,Z))}}function $J($,Z){let Y=J8(Z),Q=HZ($,Z),z=(N)=>J8($.root,N),J=new Set([...Q.directDependents.map(z),...Q.transitiveDependents.map(z)]);J.add(Y);let X=new Map;for(let N of J)X.set(N,0);for(let N of J){let C=$.importedBy.get(N)||new Set;for(let M of C)if(J.has(M)&&M!==N)X.set(N,(X.get(N)||0)+1)}let K=[];for(let[N,C]of X)if(C===0&&N!==Y)K.push(N);let G=[],V=new Set,q=0;while(q<K.length){let N=K[q++];G.push(N),V.add(N);let C=$.imports.get(N)||new Set;for(let M of C)if(J.has(M)&&!V.has(M)&&M!==Y){let F=(X.get(M)||1)-1;if(X.set(M,F),F===0)K.push(M)}}for(let N of J)if(!V.has(N)&&N!==Y)G.push(N);let U=[Y,...G],H=(N)=>qZ($.root,N).replace(/\\/g,"/"),B=U.map((N)=>{let M=[...$.imports.get(N)||new Set].filter((d)=>J.has(d)).map(H),F=H(N),w=N===Y?0:Q.depthMap.get(F)||1;return{file:F,depth:w,dependsOn:M}});return{target:H(Y),order:B,totalFiles:B.length}}function ZJ($){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 ---"),YJ($.tree,Z,"",!0),Z.join(`
273
- `)}function YJ($,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++)YJ($.children[K],Z,X,K===$.children.length-1)}function QJ($){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(`
274
- `)}u();import{existsSync as WZ,mkdirSync as GH,readFileSync as JJ}from"fs";import{join as XJ}from"path";import{randomUUID as VH}from"crypto";var BZ=[{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"}],NZ="",K1=[],G1=[],KJ=()=>XJ(NZ,"engine-tradeoffs.json"),GJ=()=>XJ(NZ,"engine-incidents.json");function qH(){A(KJ(),JSON.stringify(K1,null,2))}function UH(){A(GJ(),JSON.stringify(G1,null,2))}function HH(){let $=KJ();if(!WZ($)){K1=[];return}try{K1=JSON.parse(JJ($,"utf-8"))}catch{K1=[]}}function WH(){let $=GJ();if(!WZ($)){G1=[];return}try{G1=JSON.parse(JJ($,"utf-8"))}catch{G1=[]}}function VJ($){if(NZ=$,!WZ($))GH($,{recursive:!0});HH(),WH()}function qJ($,Z,Y=BZ){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 z={};for(let q of Z){let U=0;for(let H of Y){let B=q.scores[H.name]??3;U+=B*H.weight}z[q.name]=Math.round(U*100)/100}let X=Object.entries(z).sort(([,q],[,U])=>U-q)[0]?.[0]||Z[0]?.name||"N/A",K=Z.find((q)=>q.name===X),G=BH($,Z,Y,z,X,K),V={id:RJ(),context:$,options:Z,criteria:Y,recommendation:X,weightedScores:z,adr:G,createdAt:new Date().toISOString()};return K1=[...K1,V],qH(),V}function BH($,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 U of $.constraints)G.push(`- ${U}`);G.push("")}if($.stakeholders.length>0){G.push("### Stakeholders"),G.push("");for(let U of $.stakeholders)G.push(`- ${U}`);G.push("")}G.push("## Options Considered"),G.push("");for(let U of Z){if(G.push(`### ${U.name}`),G.push(""),G.push(U.description),G.push(""),U.pros.length>0){G.push("**Pros:**");for(let H of U.pros)G.push(`- ${H}`);G.push("")}if(U.cons.length>0){G.push("**Cons:**");for(let H of U.cons)G.push(`- ${H}`);G.push("")}}G.push("## Evaluation Matrix"),G.push("");let V=["Criterion (Weight)",...Z.map((U)=>U.name)];G.push(`| ${V.join(" | ")} |`),G.push(`| ${V.map(()=>"---").join(" | ")} |`);for(let U of Y){let H=Math.round(U.weight*100),B=[`${U.name} (${H}%)`,...Z.map((N)=>{return`${N.scores[U.name]??3}/5`})];G.push(`| ${B.join(" | ")} |`)}let q=["**Weighted Total**",...Z.map((U)=>`**${Q[U.name]?.toFixed(2)??"0.00"}**`)];if(G.push(`| ${q.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 U of J.pros.slice(0,3))G.push(`- ${U}`);G.push("")}}if(G.push("## Consequences"),G.push(""),G.push("### Positive"),G.push(""),J&&J.pros.length>0)for(let U of J.pros)G.push(`- ${U}`);else G.push("- *To be determined based on implementation*");if(G.push(""),G.push("### Negative"),G.push(""),J&&J.cons.length>0)for(let U of J.cons)G.push(`- ${U}`);else G.push("- *To be determined based on implementation*");return G.push(""),G.push("---"),G.push(""),G.push("*Generated by Decision Engine*"),G.join(`
275
- `)}function zJ($){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 q of V)Q.add(q.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 NH($,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 UJ($,Z){let Y=Z?`${$}
276
- ${Z}`:$,Q=zJ(Y),z=[];for(let G of G1){let V=`${G.title} ${G.description} ${G.stacktrace||""} ${G.rootCause} ${G.solution}`,q=zJ(V),U=NH(Q,q);if(U>0.1){let H=Q.filter((C)=>q.includes(C)),B=[];for(let C of G.relatedDecisions){let M=Z$(C);if(M.length>0)B.push(M[0])}let N=[];if(G.solution)N.push(`Apply solution: ${G.solution}`);if(G.rootCause)N.push(`Investigate root cause: ${G.rootCause}`);for(let C of B)N.push(`Review decision: ${C.title}`);z.push({incident:G,similarity:U,matchedKeywords:H,relatedDecisions:B,suggestedActions:N})}}z.sort((G,V)=>V.similarity-G.similarity);let J=Z$($.slice(0,50)),X=h$($.slice(0,50)),K=OH($,z,J,X);return{query:$,matches:z.slice(0,5),materialsFound:X.slice(0,5),summary:K}}function OH($,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(`
277
- `)}function HJ($,Z,Y,Q,z,J=[],X=[]){let K={id:RJ(),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 G1=[...G1,K],UH(),K}function WJ($){let Z=$.toLowerCase();return G1.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 BJ($=10){return[...G1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function NJ($=10){return[...K1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function OJ($){let Z=$.toLowerCase();return K1.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 CJ($){return K1.find((Z)=>Z.id===$)||null}function MJ($){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
+ `)}`}function S5(){let $=_1();if(!$)return"";let Z=x1($.id),Y=i0.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(`
272
+ `)}function w5($){let Z=h0.find((z)=>z.path===$);if(Z)return Z;if(!x0(L0($,".git")))return null;let Y=[];if(x0(L0($,"package.json")))try{let z=JSON.parse(R5(L0($,"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(x0(L0($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(x0(L0($,"Cargo.toml")))Y.push("rust");if(x0(L0($,"go.mod")))Y.push("go");if(x0(L0($,"requirements.txt"))||x0(L0($,"pyproject.toml")))Y.push("python");let Q=pq($);return GZ(Q,$,"",[],Y)}function VZ(){return dq().slice(0,8)}u();a();import{existsSync as HZ,mkdirSync as sq,readFileSync as nz}from"fs";import{join as rz,basename as tq}from"path";var az=2,sz="pitwall-baselines.json",eq=0.1,$H=0.05,ZH=5000000,YH=512000,oz=2048,QH=120000,b5="",X0=[];function tz($){if(b5=$,!HZ($))sq($,{recursive:!0});qH()}async function iz($,Z){let Q=[...M$(),$],z=process.cpuUsage(),J=Bun.nanoseconds(),X=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),K=setTimeout(()=>X.kill(),QH),G=X.pid,V=zH(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),N=await V,M=U.length>oz?`...${U.slice(-oz)}`:U;return{durationNs:H-J,peakMemoryBytes:N,cpuUserUs:B.user,cpuSystemUs:B.system,exitCode:q,stderr:M.trim()}}async function WZ($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),z=Z.scriptKey||UH($);if(Z.warmup&&Q>1)await iz($,Y);let J=[];for(let U=0;U<Q;U++)J.push(await iz($,Y));let X=J[J.length-1],K=J.map((U)=>U.durationNs),G={durationNs:UZ(K),peakMemoryBytes:Math.max(...J.map((U)=>U.peakMemoryBytes)),cpuUserUs:UZ(J.map((U)=>U.cpuUserUs)),cpuSystemUs:UZ(J.map((U)=>U.cpuSystemUs))},V=Q>1?{min:Math.min(...K),max:Math.max(...K),median:G.durationNs,stddev:VH(K)}:null;return{scriptKey:z,command:$,metrics:G,spread:V,exitCode:X.exitCode,stderr:X.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function zH($){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),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(HZ(Z)){let Q=nz(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function ez($,Z=[]){let Y=X0.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 X0=X0.map((G)=>G.scriptKey===$.scriptKey?K:G),y5(),K}let z={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return X0=[...X0,z],y5(),z}function JH($){return X0.find((Z)=>Z.scriptKey===$)||null}function $J(){return[...X0].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function BZ($){let Z=X0.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return X0=[...X0.slice(0,Z),...X0.slice(Z+1)],y5(),!0}function ZJ($,Z=[]){BZ($.scriptKey);let Y=new Date().toISOString(),Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return X0=[...X0,Q],y5(),Q}function NZ($){let Z=JH($.scriptKey),Y=[];if(Z)Y.push(k5("duration",Z.metrics.durationNs,$.metrics.durationNs,ZH),k5("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,YH),k5("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),k5("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((J)=>J.severity==="regression"),z=GH($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:z}}function k5($,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>$H)X="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(J*1e4)/100,absoluteDelta:z,severity:X}}function K1($){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 f5($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function XH($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function KH($){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 GH($,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: ${K1($.metrics.durationNs)}`),z.push(` Memoria: ${qZ($.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${f5($.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${f5($.metrics.cpuSystemUs)}`),$.spread){z.push(""),z.push("--- Dispersao ---"),z.push(` Min: ${K1($.spread.min)}`),z.push(` Max: ${K1($.spread.max)}`),z.push(` Mediana: ${K1($.spread.median)}`),z.push(` Stddev: ${K1($.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(`
273
+ `);z.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${YJ(Z.updatedAt)}) ---`),z.push(` Duracao: ${K1(Z.metrics.durationNs)}`),z.push(` Memoria: ${qZ(Z.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${f5(Z.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${f5(Z.metrics.cpuSystemUs)}`),z.push(""),z.push("--- Comparacao ---");for(let J of Y){let X=J.deltaPercent>=0?"+":"",K=KH(J.metric);z.push(` ${XH(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(`
274
+ `)}function YJ($){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 QJ($){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=YJ(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${K1(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: ${K1(Y.spread.min)} ~ ${K1(Y.spread.max)} (CV ${J}%)`)}Z.push("")}return Z.join(`
275
+ `)}function UZ($){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 VH($){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 UH($){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 tq(Z[0])}function qH(){let $=rz(b5,sz);if(!HZ($)){X0=[];return}try{let Z=JSON.parse(nz($,"utf-8"));if(Z.version!==az&&Z.version!==1){X0=[];return}X0=(Z.baselines||[]).map(HH)}catch{X0=[]}}function HH($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function y5(){if(!b5)return;let $=rz(b5,sz);P($,JSON.stringify({baselines:X0,version:az},null,2))}a();import{readdirSync as WH,readFileSync as BH,lstatSync as NH}from"fs";import{join as OH,resolve as X8,relative as OZ,dirname as MH,extname as CH}from"path";var EH=[".ts",".tsx",".mts",".cts"],RH=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],FH=new Set(Z2),zJ=5000,LH=5000,JJ=new Map;function jH($){let Z=JJ.get($);if(Z&&Date.now()-Z.ts<LH)return Z.graph;return null}function PH($,Z){JJ.set($,{graph:Z,ts:Date.now()})}var AH=[/^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 TH($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of AH){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 DH($){let Z=[];function Y(Q){if(Z.length>=zJ)return;let z;try{z=WH(Q)}catch{return}for(let J of z){if(Z.length>=zJ)return;if(FH.has(J))continue;let X=OH(Q,J),K;try{K=NH(X)}catch{continue}if(K.isSymbolicLink())continue;if(K.isDirectory())Y(X);else if(K.isFile()&&EH.includes(CH(J)))Z.push(X)}}return Y($),Z}function IH($,Z,Y){let Q=MH(Z),z=X8(Q,$);if(Y.has(z))return z;for(let J of RH){let X=z+J;if(Y.has(X))return X}return null}function MZ($){let Z=X8($),Y=jH(Z);if(Y)return Y;let Q=DH(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=BH(G,"utf-8")}catch{continue}let U=TH(V),q=J.get(G);for(let H of U){let B=IH(H,G,z);if(B){q.add(B);let N=X.get(B)||new Set;N.add(G),X.set(B,N)}}}let K={imports:J,importedBy:X,files:Q,root:Z};return PH(Z,K),K}function CZ($,Z){let Y=X8(Z),Q=$.importedBy.get(Y)||new Set,z=[...Q],J=new Set([Y]),X=[],K=new Map,G=0;for(let N of Q)X.push({file:N,depth:1}),J.add(N),K.set(N,1);let V=[],U=0;while(U<X.length){let{file:N,depth:M}=X[U++];if(M>G)G=M;if(!Q.has(N))V.push(N);let C=$.importedBy.get(N)||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=XJ(Y,$.importedBy,new Set,0),H=(N)=>OZ($.root,N).replace(/\\/g,"/"),B=new Map;for(let[N,M]of K)B.set(H(N),M);return{target:H(Y),directDependents:z.map(H),transitiveDependents:V.map(H),depthMap:B,totalAffected:z.length+V.length,depth:G,tree:KJ(q,$.root)}}function XJ($,Z,Y,Q){Y.add($);let z=Z.get($)||new Set,J=[];for(let X of z)if(!Y.has(X))J.push(XJ(X,Z,Y,Q+1));return{file:$,depth:Q,children:J}}function KJ($,Z){return{file:OZ(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>KJ(Y,Z))}}function GJ($,Z){let Y=X8(Z),Q=CZ($,Z),z=(N)=>X8($.root,N),J=new Set([...Q.directDependents.map(z),...Q.transitiveDependents.map(z)]);J.add(Y);let X=new Map;for(let N of J)X.set(N,0);for(let N of J){let M=$.importedBy.get(N)||new Set;for(let C of M)if(J.has(C)&&C!==N)X.set(N,(X.get(N)||0)+1)}let K=[];for(let[N,M]of X)if(M===0&&N!==Y)K.push(N);let G=[],V=new Set,U=0;while(U<K.length){let N=K[U++];G.push(N),V.add(N);let M=$.imports.get(N)||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 N of J)if(!V.has(N)&&N!==Y)G.push(N);let q=[Y,...G],H=(N)=>OZ($.root,N).replace(/\\/g,"/"),B=q.map((N)=>{let C=[...$.imports.get(N)||new Set].filter((c)=>J.has(c)).map(H),F=H(N),k=N===Y?0:Q.depthMap.get(F)||1;return{file:F,depth:k,dependsOn:C}});return{target:H(Y),order:B,totalFiles:B.length}}function VJ($){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 ---"),UJ($.tree,Z,"",!0),Z.join(`
276
+ `)}function UJ($,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++)UJ($.children[K],Z,X,K===$.children.length-1)}function qJ($){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(`
277
+ `)}u();import{existsSync as EZ,mkdirSync as SH,readFileSync as WJ}from"fs";import{join as BJ}from"path";import{randomUUID as wH}from"crypto";var RZ=[{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"}],FZ="",G1=[],V1=[],NJ=()=>BJ(FZ,"engine-tradeoffs.json"),OJ=()=>BJ(FZ,"engine-incidents.json");function kH(){P(NJ(),JSON.stringify(G1,null,2))}function fH(){P(OJ(),JSON.stringify(V1,null,2))}function bH(){let $=NJ();if(!EZ($)){G1=[];return}try{G1=JSON.parse(WJ($,"utf-8"))}catch{G1=[]}}function yH(){let $=OJ();if(!EZ($)){V1=[];return}try{V1=JSON.parse(WJ($,"utf-8"))}catch{V1=[]}}function MJ($){if(FZ=$,!EZ($))SH($,{recursive:!0});bH(),yH()}function CJ($,Z,Y=RZ){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=_H($,Z,Y,z,X,K),V={id:IJ(),context:$,options:Z,criteria:Y,recommendation:X,weightedScores:z,adr:G,createdAt:new Date().toISOString()};return G1=[...G1,V],kH(),V}function _H($,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((N)=>{return`${N.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(`
278
+ `)}function HJ($){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 xH($,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 EJ($,Z){let Y=Z?`${$}
279
+ ${Z}`:$,Q=HJ(Y),z=[];for(let G of V1){let V=`${G.title} ${G.description} ${G.stacktrace||""} ${G.rootCause} ${G.solution}`,U=HJ(V),q=xH(Q,U);if(q>0.1){let H=Q.filter((M)=>U.includes(M)),B=[];for(let M of G.relatedDecisions){let C=Y$(M);if(C.length>0)B.push(C[0])}let N=[];if(G.solution)N.push(`Apply solution: ${G.solution}`);if(G.rootCause)N.push(`Investigate root cause: ${G.rootCause}`);for(let M of B)N.push(`Review decision: ${M.title}`);z.push({incident:G,similarity:q,matchedKeywords:H,relatedDecisions:B,suggestedActions:N})}}z.sort((G,V)=>V.similarity-G.similarity);let J=Y$($.slice(0,50)),X=g$($.slice(0,50)),K=vH($,z,J,X);return{query:$,matches:z.slice(0,5),materialsFound:X.slice(0,5),summary:K}}function vH($,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(`
280
+ `)}function RJ($,Z,Y,Q,z,J=[],X=[]){let K={id:IJ(),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 V1=[...V1,K],fH(),K}function FJ($){let Z=$.toLowerCase();return V1.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 LJ($=10){return[...V1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function jJ($=10){return[...G1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function PJ($){let Z=$.toLowerCase();return G1.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 AJ($){return G1.find((Z)=>Z.id===$)||null}function TJ($){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}):
278
281
  ${Z.join(`
279
- `)}`}function EJ($){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}):
282
+ `)}`}function DJ($){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}):
280
283
  ${Z.join(`
281
- `)}`}function RJ(){return VH().slice(0,8)}u();import{existsSync as K8,mkdirSync as FJ,readFileSync as OZ,readdirSync as CH,writeFileSync as LJ}from"fs";import{join as z$}from"path";import{homedir as MH}from"os";import{createHash as EH}from"crypto";var RH=20,jJ=3,FH=0.6,LH={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"]},jH={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."}},X8="",x1="",f0={events:[],sessionStart:Date.now()},Q$=new Map,V1=[],k0=[],d$=!1,PJ=null,AJ=()=>z$(X8,"usage-patterns.json"),DJ=()=>z$(X8,"insights.json");function TJ($,Z){if(X8=z$($,"docs-engine"),x1=z$(MH(),".config","smolerclaw","materials","manual"),PJ=Z||null,!K8(X8))FJ(X8,{recursive:!0});if(!K8(x1))FJ(x1,{recursive:!0});xH(),hH(),gH(),f0={events:[],sessionStart:Date.now()},d$=!0}function CZ($){if(!d$)return;let Z={...$,timestamp:Date.now()},Y=[...f0.events,Z].slice(-RH);f0={...f0,events:Y},PH(Z),setImmediate(()=>AH(Z))}function PH($){let Z=`${$.type}:${$.name}`,Y=Q$.get(Z);if(Y){let Q=Y.count+1,z=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;Q$.set(Z,{action:Z,count:Q,avgDurationMs:z,lastUsed:$.timestamp})}else Q$.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function AH($){let Z=f0.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:z}]of Object.entries(jH))if(Q.test(Z)){if(!V1.find((X)=>X.type==="inefficient_pattern"&&X.relatedActions.includes($.name)&&Date.now()-new Date(X.createdAt).getTime()<3600000)){let X={id:J$(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:z,relatedActions:f0.events.slice(-5).map((K)=>K.name),confidence:0.8,createdAt:new Date().toISOString()};IJ(X)}}}async function c$(){if(!d$)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=DH();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=TH();$.insightsGenerated+=Y.length;let Q=IH();$.insightsGenerated+=Q.length;for(let z of[...Z,...Y,...Q])if(IJ(z),await wH(z))$.manualUpdates++;return _H(),vH(),f0={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
282
- `),$}function DH(){let $=[],Z=SH(f0.events);for(let Y of Z)if(Y.count>=jJ){let Q={id:J$(),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 TH(){let $=[],Z=new Set;for(let Y of f0.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(LH)){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>=FH){let K={id:J$(),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 IH(){let $=[];if(Date.now()-f0.sessionStart>1800000&&!f0.events.some((Q)=>Q.name==="save_memo"))$.push({id:J$(),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=f0.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!f0.events.some((Q)=>Q.name.includes("workflow")))$.push({id:J$(),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 SH($){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>=jJ)}function IJ($){if(!V1.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))V1=[...V1,$],PJ?.($)}function SJ($=5){return[...V1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function wH($){try{let Z=bH($.type),Y=`${$.id}.md`,Q=z$(x1,Y),z=k0.find((G)=>G.id===$.id),J=z?z.version+1:1,X={id:$.id,title:$.title,category:Z,content:fH($),tags:yH($),source:"auto_generated",version:J,createdAt:z?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},K=bJ(X);return LJ(Q,K,"utf-8"),k0=k0.filter((G)=>G.id!==X.id),k0=[...k0,X],!0}catch{return!1}}async function wJ($,Z,Y="best_practice",Q=[]){if(!d$)return{success:!1,path:""};try{let z=J$(),J=`${mH($)}-${z.slice(0,4)}.md`,X=z$(x1,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=bJ(K);return LJ(X,G,"utf-8"),k0=[...k0,K],{success:!0,path:X,entry:K}}catch{return{success:!1,path:""}}}function kH($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return k0.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 kJ($){let Z=$?kH($):k0;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=fJ[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(`
283
- `)});return["# Manual de Uso Otimizado","",`Baseado em ${k0.length} entradas do manual vivo.`,"",...Y].join(`
284
- `)}var fJ={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function fH($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
285
- `)}function bJ($){let Z=fJ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
284
+ `)}`}function IJ(){return wH().slice(0,8)}u();import{existsSync as G8,mkdirSync as SJ,readFileSync as LZ,readdirSync as hH,writeFileSync as wJ}from"fs";import{join as J$}from"path";import{homedir as gH}from"os";import{createHash as uH}from"crypto";var mH=20,kJ=3,pH=0.6,dH={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"]},cH={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."}},K8="",v1="",b0={events:[],sessionStart:Date.now()},z$=new Map,U1=[],f0=[],c$=!1,fJ=null,bJ=()=>J$(K8,"usage-patterns.json"),yJ=()=>J$(K8,"insights.json");function _J($,Z){if(K8=J$($,"docs-engine"),v1=J$(gH(),".config","smolerclaw","materials","manual"),fJ=Z||null,!G8(K8))SJ(K8,{recursive:!0});if(!G8(v1))SJ(v1,{recursive:!0});QW(),JW(),XW(),b0={events:[],sessionStart:Date.now()},c$=!0}function jZ($){if(!c$)return;let Z={...$,timestamp:Date.now()},Y=[...b0.events,Z].slice(-mH);b0={...b0,events:Y},lH(Z),setImmediate(()=>oH(Z))}function lH($){let Z=`${$.type}:${$.name}`,Y=z$.get(Z);if(Y){let Q=Y.count+1,z=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;z$.set(Z,{action:Z,count:Q,avgDurationMs:z,lastUsed:$.timestamp})}else z$.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function oH($){let Z=b0.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:z}]of Object.entries(cH))if(Q.test(Z)){if(!U1.find((X)=>X.type==="inefficient_pattern"&&X.relatedActions.includes($.name)&&Date.now()-new Date(X.createdAt).getTime()<3600000)){let X={id:X$(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:z,relatedActions:b0.events.slice(-5).map((K)=>K.name),confidence:0.8,createdAt:new Date().toISOString()};xJ(X)}}}async function l$(){if(!c$)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=iH();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=nH();$.insightsGenerated+=Y.length;let Q=rH();$.insightsGenerated+=Q.length;for(let z of[...Z,...Y,...Q])if(xJ(z),await sH(z))$.manualUpdates++;return YW(),zW(),b0={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
285
+ `),$}function iH(){let $=[],Z=aH(b0.events);for(let Y of Z)if(Y.count>=kJ){let Q={id:X$(),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 nH(){let $=[],Z=new Set;for(let Y of b0.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(dH)){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>=pH){let K={id:X$(),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 rH(){let $=[];if(Date.now()-b0.sessionStart>1800000&&!b0.events.some((Q)=>Q.name==="save_memo"))$.push({id:X$(),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=b0.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!b0.events.some((Q)=>Q.name.includes("workflow")))$.push({id:X$(),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 aH($){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>=kJ)}function xJ($){if(!U1.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))U1=[...U1,$],fJ?.($)}function vJ($=5){return[...U1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function sH($){try{let Z=$W($.type),Y=`${$.id}.md`,Q=J$(v1,Y),z=f0.find((G)=>G.id===$.id),J=z?z.version+1:1,X={id:$.id,title:$.title,category:Z,content:eH($),tags:ZW($),source:"auto_generated",version:J,createdAt:z?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},K=mJ(X);return wJ(Q,K,"utf-8"),f0=f0.filter((G)=>G.id!==X.id),f0=[...f0,X],!0}catch{return!1}}async function hJ($,Z,Y="best_practice",Q=[]){if(!c$)return{success:!1,path:""};try{let z=X$(),J=`${GW($)}-${z.slice(0,4)}.md`,X=J$(v1,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=mJ(K);return wJ(X,G,"utf-8"),f0=[...f0,K],{success:!0,path:X,entry:K}}catch{return{success:!1,path:""}}}function tH($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return f0.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 gJ($){let Z=$?tH($):f0;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=uJ[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(`
286
+ `)});return["# Manual de Uso Otimizado","",`Baseado em ${f0.length} entradas do manual vivo.`,"",...Y].join(`
287
+ `)}var uJ={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(`
288
+ `)}function mJ($){let Z=uJ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
286
289
  Tags: ${$.tags.map((Y)=>`#${Y}`).join(" ")}`:""].filter(Boolean).join(`
287
- `)}function bH($){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 yH($){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 yJ($){return $.summary}function _J($){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(`
290
+ `)}function $W($){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 ZW($){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 pJ($){return $.summary}function dJ($){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(`
288
291
  `)});return`Insights (${$.length}):
289
292
 
290
293
  ${Z.join(`
291
294
 
292
- `)}`}function _H(){if(!d$)return;let $=Object.fromEntries(Q$);A(AJ(),JSON.stringify($,null,2))}function xH(){let $=AJ();if(!K8($)){Q$=new Map;return}try{let Z=JSON.parse(OZ($,"utf-8"));Q$=new Map(Object.entries(Z))}catch{Q$=new Map}}function vH(){if(!d$)return;A(DJ(),JSON.stringify(V1,null,2))}function hH(){let $=DJ();if(!K8($)){V1=[];return}try{let Z=JSON.parse(OZ($,"utf-8"));V1=Array.isArray(Z)?Z:[]}catch{V1=[]}}function gH(){if(!K8(x1)){k0=[];return}try{let $=CH(x1,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=z$(x1,Y.name),z=OZ(Q,"utf-8"),J=uH(Y.name,z);if(J)Z.push(J)}k0=Z}catch{k0=[]}}function uH($,Z){try{let Y=Z.split(`
293
- `),Q=Y[0]?.replace(/^#\s*/,"")||$.replace(".md",""),z="best_practice",J=1,X=[];for(let U of Y.slice(1,6)){if(U.startsWith("> Categoria:")){let H=U.replace("> Categoria:","").trim().toLowerCase();if(H==="workflow"||H==="tool"||H==="shortcut"||H==="best_practice")z=H}if(U.startsWith("> Versao:"))J=parseInt(U.replace("> Versao:","").trim())||1}let G=Y.slice(-3).join(`
294
- `).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]:J$(),title:Q,category:z,content:Y.slice(5).join(`
295
- `).trim(),tags:X,source:"auto_generated",version:J,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function J$(){return EH("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function mH($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}v1();n();d0();p0();import{writeFileSync as lH,unlinkSync as oH,existsSync as iH}from"fs";import{join as rH}from"path";import{tmpdir as nH}from"os";import{randomUUID as aH}from"crypto";var sH=30000,vJ=50000;var tH=[{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)"}],eH=[{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 FZ($){for(let{pattern:Z,reason:Y}of tH)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of eH)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function V8($){if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>vJ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${vJ}).`,exitCode:1,duration:0};let Z=FZ($);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=aH().slice(0,8),Q=rH(nH(),`smolerclaw-${Y}.ps1`);try{lH(Q,$,"utf-8");let z=await a9(Q,{timeout:sH});return{stdout:z.stdout,stderr:z.timedOut?"Script timeout exceeded":z.stderr,exitCode:z.exitCode,duration:z.duration}}finally{try{if(iH(Q))oH(Q)}catch{}}}async function b5(){if(!L)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await $W();if($.type==="text")return $;return await ZW()}async function $W(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await h7($,{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 ZW(){try{let Z=await h7(`
295
+ `)}`}function YW(){if(!c$)return;let $=Object.fromEntries(z$);P(bJ(),JSON.stringify($,null,2))}function QW(){let $=bJ();if(!G8($)){z$=new Map;return}try{let Z=JSON.parse(LZ($,"utf-8"));z$=new Map(Object.entries(Z))}catch{z$=new Map}}function zW(){if(!c$)return;P(yJ(),JSON.stringify(U1,null,2))}function JW(){let $=yJ();if(!G8($)){U1=[];return}try{let Z=JSON.parse(LZ($,"utf-8"));U1=Array.isArray(Z)?Z:[]}catch{U1=[]}}function XW(){if(!G8(v1)){f0=[];return}try{let $=hH(v1,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=J$(v1,Y.name),z=LZ(Q,"utf-8"),J=KW(Y.name,z);if(J)Z.push(J)}f0=Z}catch{f0=[]}}function KW($,Z){try{let Y=Z.split(`
296
+ `),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(`
297
+ `).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]:X$(),title:Q,category:z,content:Y.slice(5).join(`
298
+ `).trim(),tags:X,source:"auto_generated",version:J,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function X$(){return uH("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function GW($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}h1();a();c0();d0();import{writeFileSync as HW,unlinkSync as WW,existsSync as BW}from"fs";import{join as NW}from"path";import{tmpdir as OW}from"os";import{randomUUID as MW}from"crypto";var CW=30000,lJ=50000;var EW=[{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)"}],RW=[{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 DZ($){for(let{pattern:Z,reason:Y}of EW)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of RW)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function U8($){if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>lJ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${lJ}).`,exitCode:1,duration:0};let Z=DZ($);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=MW().slice(0,8),Q=NW(OW(),`smolerclaw-${Y}.ps1`);try{HW(Q,$,"utf-8");let z=await zY(Q,{timeout:CW});return{stdout:z.stdout,stderr:z.timedOut?"Script timeout exceeded":z.stderr,exitCode:z.exitCode,duration:z.duration}}finally{try{if(BW(Q))WW(Q)}catch{}}}async function _5(){if(!L)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await FW();if($.type==="text")return $;return await LW()}async function FW(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await p7($,{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 LW(){try{let Z=await p7(`
296
299
  Add-Type -AssemblyName System.Windows.Forms
297
300
  $img = [System.Windows.Forms.Clipboard]::GetImage()
298
301
  if (-not $img) {
@@ -343,7 +346,7 @@ try {
343
346
  if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
344
347
  }
345
348
  `,{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]
346
- ${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function y5(){if(!L)return"Error: screen context analysis only available on Windows.";let $=`
349
+ ${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function x5(){if(!L)return"Error: screen context analysis only available on Windows.";let $=`
347
350
  $sig = @'
348
351
  [DllImport("user32.dll")]
349
352
  public static extern IntPtr GetForegroundWindow();
@@ -376,7 +379,7 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
376
379
  $marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
377
380
  Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
378
381
  }
379
- `;try{let Z=await K0($,{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 hJ($,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,"''"),z=`
382
+ `;try{let Z=await G0($,{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 oJ($,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,"''"),z=`
380
383
  $notificationTitle = '${Y}'
381
384
  $notificationText = '${Q}'
382
385
  [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
@@ -389,49 +392,56 @@ $xml.LoadXml($toastXml.OuterXml)
389
392
  $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
390
393
  [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Smolerclaw').Show($toast)
391
394
  Write-Output 'OK'
392
- `;try{let J=await V8(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 q8=50000;function r0($){if($.length<=q8)return $;return $.slice(0,q8)+`
393
- ... (output truncated)`}function U8($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function LZ($){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),q=(G-V.getDay()+7)%7||7;return V.setDate(V.getDate()+q),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(),q=new Date(V,G,K);if(!isNaN(q.getTime()))return q}return y$(Z)}var x5=[{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:[]}}],v5=[{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"]}}],h5=[{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:[]}}],g5=[{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"]}}],u5={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"]}},m5=[{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"]}}],p5=[{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:[]}}],d5=[{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"]}}],c5=[{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"]}}],l5=[{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"]}}],o5=[{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"]}}],i5=[{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"]}}],r5=[{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"]}}],n5=[{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:[]}}],a5=[{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 uJ($,Z,Y){switch($){case"open_application":return await q1(Z.name,Z.argument);case"open_file_default":return await X$(Z.path);case"open_url_browser":return await U1(Z.url);case"get_running_apps":return await G8();case"get_system_info":return await K$();case"get_calendar_events":return await i0();case"get_news":{let Q=Z.category;return await I1(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?y$(z):void 0,X=x4(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=v4(Q);return z?`Concluida: "${z.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,z=z1(Q);return e1(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=a4(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 q=Z.date_or_day;if(K==="weekly")G=t4(q)??void 0;else G=s4(q)??void 0}if(K==="once"&&!G){let q=new Date,[U,H]=X.split(":").map(Number),B=new Date(q);if(B.setHours(U,H,0,0),B<=q)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 l4(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 o4(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,z=s2(Q);return t2(z)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=await i4(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 r4(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 n4(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=G5(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=J1(Q);if(!z)return`Pessoa nao encontrada: "${Q}"`;return H5(z)}case"list_people":{let Q=Z.group,z=V5(Q);return U5(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?LZ(X):void 0;if(!Oz(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?LZ(J):void 0,K=q5(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=Cz(Q,z,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${z}`}case"get_people_dashboard":return Ez();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let z=Z.tags||[],J=h4(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 $$(a2());let z=g4(Q);return $$(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=$8(Q,z,J,X);if(!K.allowed)return`Error: ${K.blocked}`;let G=e2(Q,z,J,X);Z8(Q,z,J);let V=G.type==="entrada"?"+":"-",q=Y8(K);return`${V} R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description} [${G.id}]${q?`
394
- `+q:""}`}case"financial_summary":return $5();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=Jz(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 x$(z5());return x$(Z$(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=u6(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=m6(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=p6(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=d6(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=c6(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return r6(z)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=i6(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return z}case"list_investigations":{let Q=Z.query;if(Q?.trim())return X5(o6(Q));let{status:z,type:J}=Z;return X5(l6(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=m4(X),G=await u4(X);return`${K}
395
-
396
- ${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=N5(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 f1(g$());let z=h$(Q);return f1(z)}case"list_materials":{let Q=Z.category,z=Z.limit||30,J=g$(z,Q);return f1(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=Pz(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 O5(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=FZ(Q);if(z.blocked)return`BLOCKED: ${z.reason}
397
- Esse tipo de operacao nao e permitido.`;if(!z.safe&&z.reason);let J=await V8(Q),X=[];if(J.stdout.trim())X.push(`stdout:
395
+ `;try{let J=await U8(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)}}}u();import{existsSync as iJ,mkdirSync as jW,readFileSync as PW}from"fs";import{join as AW}from"path";import{randomUUID as TW}from"crypto";var nJ="",w=[],rJ=()=>AW(nJ,"recommendations.json");function q8(){P(rJ(),JSON.stringify(w,null,2))}function DW(){let $=rJ();if(!iJ($)){w=[];return}try{let Z=JSON.parse(PW($,"utf-8"));if(!Array.isArray(Z)){w=[];return}w=Z}catch{w=[]}}function aJ($){if(nJ=$,!iJ($))jW($,{recursive:!0});DW()}function sJ($,Z,Y,Q=[],z=[],J){let X=new Date().toISOString(),K={id:TW().slice(0,8),type:$,title:Z.trim(),creator:Y.trim(),tags:Q.map((G)=>G.toLowerCase()),moods:z,url:J?.trim()||void 0,rating:null,timesRecommended:0,timesConsumed:0,createdAt:X,updatedAt:X};return w=[...w,K],q8(),K}function tJ($,Z){let Y=Math.max(1,Math.min(5,Math.round(Z)));if(!w.find((z)=>z.id===$))return null;return w=w.map((z)=>z.id===$?{...z,rating:Y,updatedAt:new Date().toISOString()}:z),q8(),w.find((z)=>z.id===$)||null}function eJ($){if(!w.find((Y)=>Y.id===$))return null;return w=w.map((Y)=>Y.id===$?{...Y,timesConsumed:Y.timesConsumed+1,updatedAt:new Date().toISOString()}:Y),q8(),w.find((Y)=>Y.id===$)||null}function $3($){let Z=w.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return w=[...w.slice(0,Z),...w.slice(Z+1)],q8(),!0}function Z3($){let Z=$.toLowerCase().trim();if(!Z)return[...w];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return w.filter((z)=>{if(Y)return z.tags.some((J)=>J.includes(Q));return z.title.toLowerCase().includes(Q)||z.creator.toLowerCase().includes(Q)||z.tags.some((J)=>J.includes(Q))||z.type===Q})}function IZ($,Z=20){return($?w.filter((Q)=>Q.type===$):[...w]).sort((Q,z)=>new Date(z.updatedAt).getTime()-new Date(Q.updatedAt).getTime()).slice(0,Z)}function Y3($,Z,Y=5){if(w.length===0)return[];let J=w.filter((K)=>!Z||K.type===Z).map((K)=>{let G=0,V=[];if($&&K.moods.includes($))G+=30,V.push(`combina com mood "${$}"`);if(K.rating!==null){if(G+=K.rating*5,K.rating>=4)V.push(`avaliado ${K.rating}/5`)}if((Date.now()-new Date(K.createdAt).getTime())/86400000<7)G+=10,V.push("adicionado recentemente");if(K.timesConsumed===0)G+=15,V.push("ainda nao consumido");else if(K.timesConsumed<3)G+=5;if(K.timesRecommended<2)G+=8;if(V.length===0)V.push("item do seu catalogo");return{item:K,reason:V.join(", "),score:G}}).sort((K,G)=>G.score-K.score).slice(0,Y),X=new Set(J.map((K)=>K.item.id));return w=w.map((K)=>X.has(K.id)?{...K,timesRecommended:K.timesRecommended+1}:K),q8(),J}function Q3(){let $=w.reduce((K,G)=>({...K,[G.type]:K[G.type]+1}),{video:0,movie:0,music:0}),Z=w.reduce((K,G)=>G.moods.reduce((V,U)=>({...V,[U]:V[U]+1}),K),{relaxar:0,energizar:0,focar:0,inspirar:0,descontrair:0}),Y=w.filter((K)=>K.rating!==null),Q=Y.reduce((K,G)=>K+(G.rating||0),0),z=Y.length,J=[...w].filter((K)=>K.rating!==null).sort((K,G)=>(G.rating||0)-(K.rating||0)).slice(0,5),X=[...w].filter((K)=>K.timesConsumed>0).sort((K,G)=>G.timesConsumed-K.timesConsumed).slice(0,5);return{total:w.length,byType:$,byMood:Z,avgRating:z>0?Math.round(Q/z*10)/10:null,topRated:J,mostConsumed:X}}var v5={video:"[V]",movie:"[F]",music:"[M]"};function h5($){if($.length===0)return"Nenhum conteudo no catalogo.";let Z=$.map((Y)=>{let Q=Y.rating!==null?` ${"*".repeat(Y.rating)}`:"",z=Y.tags.length>0?` [${Y.tags.map((X)=>"#"+X).join(" ")}]`:"",J=Y.url?` -> ${Y.url}`:"";return` ${v5[Y.type]} ${Y.title} \u2014 ${Y.creator}${Q}${z}${J} {${Y.id}}`});return`Catalogo (${$.length}):
396
+ ${Z.join(`
397
+ `)}`}function z3($,Z){if($.length===0)return Z?`Nenhuma recomendacao encontrada para mood "${Z}". Adicione conteudo ao catalogo primeiro.`:"Nenhuma recomendacao disponivel. Adicione conteudo ao catalogo primeiro.";let Y=Z?`Recomendacoes para "${Z}" (${$.length}):`:`Recomendacoes (${$.length}):`,Q=$.map((z,J)=>{let X=z.item,K=X.rating!==null?` ${"*".repeat(X.rating)}`:"",G=X.url?`
398
+ -> ${X.url}`:"";return` ${J+1}. ${v5[X.type]} ${X.title} \u2014 ${X.creator}${K}
399
+ ${z.reason}${G} {${X.id}}`});return`${Y}
400
+ ${Q.join(`
401
+ `)}`}function J3($){let Z=[`Catalogo: ${$.total} itens`,` Videos: ${$.byType.video} | Filmes: ${$.byType.movie} | Musicas: ${$.byType.music}`,"","Moods:",` Relaxar: ${$.byMood.relaxar} | Energizar: ${$.byMood.energizar} | Focar: ${$.byMood.focar}`,` Inspirar: ${$.byMood.inspirar} | Descontrair: ${$.byMood.descontrair}`];if($.avgRating!==null)Z.push("",`Avaliacao media: ${$.avgRating}/5`);if($.topRated.length>0){Z.push("","Top avaliados:");for(let Y of $.topRated)Z.push(` ${v5[Y.type]} ${Y.title} \u2014 ${"*".repeat(Y.rating||0)}`)}if($.mostConsumed.length>0){Z.push("","Mais consumidos:");for(let Y of $.mostConsumed)Z.push(` ${v5[Y.type]} ${Y.title} (${Y.timesConsumed}x)`)}return Z.join(`
402
+ `)}var H8=50000;function r0($){if($.length<=H8)return $;return $.slice(0,H8)+`
403
+ ... (output truncated)`}function W8($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function SZ($){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 _$(Z)}var u5=[{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:[]}}],m5=[{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"]}}],p5=[{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:[]}}],d5=[{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"]}}],c5={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"]}},l5=[{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"]}}],o5=[{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:[]}}],i5=[{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"]}}],n5=[{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"]}}],r5=[{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"]}}],a5=[{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"]}}],s5=[{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"]}}],t5=[{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"]}}],e5=[{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:[]}}],$7=[{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:[]}}],wZ=[{name:"add_content",description:"Add a video, movie, or music to the recommendation catalog. Types: video, movie, music. Moods: relaxar, energizar, focar, inspirar, descontrair. Use when the user mentions content they like or want to save for later.",input_schema:{type:"object",properties:{type:{type:"string",enum:["video","movie","music"],description:"Content type"},title:{type:"string",description:"Title of the content"},creator:{type:"string",description:"Artist, director, channel, or band"},tags:{type:"array",items:{type:"string"},description:'Genre tags (e.g. "lo-fi", "comedia", "documentario"). Optional.'},moods:{type:"array",items:{type:"string",enum:["relaxar","energizar","focar","inspirar","descontrair"]},description:"Moods this content fits. Optional."},url:{type:"string",description:"URL (YouTube, Spotify, etc.). Optional."}},required:["type","title","creator"]}},{name:"get_recommendations",description:'Get personalized content recommendations for decompression. Optionally filter by mood (relaxar, energizar, focar, inspirar, descontrair) and/or content type (video, movie, music). Use when the user wants a suggestion to watch, listen, or relax. Also responds to "o que assistir?", "me sugere uma musica", "preciso descomprimir".',input_schema:{type:"object",properties:{mood:{type:"string",enum:["relaxar","energizar","focar","inspirar","descontrair"],description:"Desired mood. Optional."},type:{type:"string",enum:["video","movie","music"],description:"Content type filter. Optional."},limit:{type:"number",description:"Max recommendations. Default 5."}},required:[]}},{name:"rate_content",description:"Rate a content item from 1 to 5 stars. Improves future recommendations.",input_schema:{type:"object",properties:{id:{type:"string",description:"Content ID"},rating:{type:"number",description:"Rating from 1 to 5"}},required:["id","rating"]}},{name:"mark_content_consumed",description:"Mark a content item as watched/listened. Tracks consumption for better recommendations.",input_schema:{type:"object",properties:{id:{type:"string",description:"Content ID"}},required:["id"]}},{name:"search_content",description:'Search the content catalog by title, creator, tag, or type. Use #tag syntax to search by tag (e.g. "#lo-fi").',input_schema:{type:"object",properties:{query:{type:"string",description:"Search term or #tag"},type:{type:"string",enum:["video","movie","music"],description:"Filter by content type. Optional."}},required:["query"]}},{name:"list_catalog",description:"List all content in the catalog, optionally filtered by type.",input_schema:{type:"object",properties:{type:{type:"string",enum:["video","movie","music"],description:"Filter by content type. Optional."},limit:{type:"number",description:"Max items. Default 20."}},required:[]}},{name:"remove_content",description:"Remove a content item from the catalog by ID.",input_schema:{type:"object",properties:{id:{type:"string",description:"Content ID"}},required:["id"]}},{name:"content_stats",description:"Show statistics about the content catalog: items by type, mood distribution, average rating, top rated, and most consumed.",input_schema:{type:"object",properties:{},required:[]}}];async function K3($,Z,Y){switch($){case"open_application":return await q1(Z.name,Z.argument);case"open_file_default":return await K$(Z.path);case"open_url_browser":return await H1(Z.url);case"get_running_apps":return await V8();case"get_system_info":return await G$();case"get_calendar_events":return await n0();case"get_news":{let Q=Z.category;return await S1(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?_$(z):void 0,X=h4(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=g4(Q);return z?`Concluida: "${z.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,z=J1(Q);return $$(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=t4(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=$5(U)??void 0;else G=e4(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 i4(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 n4(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,z=t2(Q);return e2(z)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=await r4(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 a4(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 s4(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=U5(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=X1(Q);if(!z)return`Pessoa nao encontrada: "${Q}"`;return B5(z)}case"list_people":{let Q=Z.group,z=q5(Q);return W5(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?SZ(X):void 0;if(!Pz(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?SZ(J):void 0,K=H5(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=Az(Q,z,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${z}`}case"get_people_dashboard":return Dz();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let z=Z.tags||[],J=u4(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 Z$(s2());let z=m4(Q);return Z$(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=Z8(Q,z,J,X);if(!K.allowed)return`Error: ${K.blocked}`;let G=$8(Q,z,J,X);Y8(Q,z,J);let V=G.type==="entrada"?"+":"-",U=Q8(K);return`${V} R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description} [${G.id}]${U?`
404
+ `+U:""}`}case"financial_summary":return Y5();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=Wz(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 v$(X5());return v$(Y$(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=o6(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=i6(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=n6(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=r6(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=a6(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return $Z(z)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=e6(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return z}case"list_investigations":{let Q=Z.query;if(Q?.trim())return G5(t6(Q));let{status:z,type:J}=Z;return G5(s6(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=d4(X),G=await p4(X);return`${K}
405
+
406
+ ${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=M5(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 b1(u$());let z=g$(Q);return b1(z)}case"list_materials":{let Q=Z.category,z=Z.limit||30,J=u$(z,Q);return b1(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=fz(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 C5(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=DZ(Q);if(z.blocked)return`BLOCKED: ${z.reason}
407
+ Esse tipo de operacao nao e permitido.`;if(!z.safe&&z.reason);let J=await U8(Q),X=[];if(J.stdout.trim())X.push(`stdout:
398
408
  ${J.stdout.trim()}`);if(J.stderr.trim())X.push(`stderr:
399
409
  ${J.stderr.trim()}`);return X.push(`exit: ${J.exitCode} (${J.duration}ms)`),X.join(`
400
410
 
401
- `)}case"analyze_screen_context":return await y5();case"read_clipboard_content":{let Q=await b5();switch(Q.type){case"text":return`Clipboard (texto):
402
- ${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 hJ(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 y4();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=w4(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 k4(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 f4(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 b4(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=I5(process.cwd());if(!J)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return p$(J.id),`Projeto ativo: "${J.name}" (${J.path}) \u2014 auto-detectado [${J.id}]`}let z=p$(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=y1();if(!V)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=V.id}let G=await j5(K,z,J);if(!G)return`Projeto nao encontrado: "${K}"`;if(X)return YW(X,G.markdown,"utf-8"),`Relatorio salvo em: ${X}
411
+ `)}case"analyze_screen_context":return await x5();case"read_clipboard_content":{let Q=await _5();switch(Q.type){case"text":return`Clipboard (texto):
412
+ ${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 oJ(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 x4();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=f4(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 b4(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 y4(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 _4(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=w5(process.cwd());if(!J)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return d$(J.id),`Projeto ativo: "${J.name}" (${J.path}) \u2014 auto-detectado [${J.id}]`}let z=d$(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=_1();if(!V)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=V.id}let G=await A5(K,z,J);if(!G)return`Projeto nao encontrado: "${K}"`;if(X)return IW(X,G.markdown,"utf-8"),`Relatorio salvo em: ${X}
403
413
 
404
- ${G.markdown}`;return G.markdown}case"manage_work_session":{let Q=Z.action,z=Z.notes||"",J=y1();if(!J)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=R5(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=_1(J.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=F5(X.id,z);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${J.name}".`}case"status":{let X=_1(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=YZ(Q,z,J,K,X);return`Projeto registrado: "${G.name}" (${G.path}) [${G.id}]`}case"list_projects":{let Q=Z.active_only||!1;return P5(m$(Q))}case"fetch_opportunities":{let{status:Q,tech:z}=Z,J=L5(Q,z);return D5(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=xz(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=vz(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 KZ(Q,{scriptKey:z,cwd:K,iterations:J,warmup:X});if(G.exitCode!==0){let V=VZ(G);return`AVISO: Comando terminou com exit code ${G.exitCode}. Metricas podem nao ser confiaveis.
414
+ ${G.markdown}`;return G.markdown}case"manage_work_session":{let Q=Z.action,z=Z.notes||"",J=_1();if(!J)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=L5(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=x1(J.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=j5(X.id,z);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${J.name}".`}case"status":{let X=x1(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=GZ(Q,z,J,K,X);return`Projeto registrado: "${G.name}" (${G.path}) [${G.id}]`}case"list_projects":{let Q=Z.active_only||!1;return T5(p$(Q))}case"fetch_opportunities":{let{status:Q,tech:z}=Z,J=P5(Q,z);return I5(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=cz(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=lz(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 WZ(Q,{scriptKey:z,cwd:K,iterations:J,warmup:X});if(G.exitCode!==0){let V=NZ(G);return`AVISO: Comando terminou com exit code ${G.exitCode}. Metricas podem nao ser confiaveis.
405
415
 
406
- ${V.markdown}`}return VZ(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 KZ(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.
407
- `+(V.stderr?`Stderr: ${V.stderr.slice(0,300)}`:"");let q=K?iz(V,X):lz(V,X),U=q.metrics.durationNs/1e6;return`Baseline salvo: "${q.scriptKey}" (${q.runs} run${q.runs>1?"s":""})
408
- Duracao: ${U.toFixed(2)}ms
409
- Memoria: ${(q.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
410
- CPU (user): ${(q.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return nz(oz());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return GZ(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=_5(Z.project_dir||process.cwd()),J=_5(z,Q);if(!J.startsWith(z+gJ))return"Error: file must be inside project_dir.";try{let X=UZ(z),K=HZ(X,J);return ZJ(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=_5(Z.project_dir||process.cwd()),J=_5(z,Q);if(!J.startsWith(z+gJ))return"Error: file must be inside project_dir.";try{let X=UZ(z),K=$J(X,J);return QJ(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}):
416
+ ${V.markdown}`}return NZ(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 WZ(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.
417
+ `+(V.stderr?`Stderr: ${V.stderr.slice(0,300)}`:"");let U=K?ZJ(V,X):ez(V,X),q=U.metrics.durationNs/1e6;return`Baseline salvo: "${U.scriptKey}" (${U.runs} run${U.runs>1?"s":""})
418
+ Duracao: ${q.toFixed(2)}ms
419
+ Memoria: ${(U.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
420
+ CPU (user): ${(U.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return QJ($J());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return BZ(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=g5(Z.project_dir||process.cwd()),J=g5(z,Q);if(!J.startsWith(z+X3))return"Error: file must be inside project_dir.";try{let X=MZ(z),K=CZ(X,J);return VJ(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=g5(Z.project_dir||process.cwd()),J=g5(z,Q);if(!J.startsWith(z+X3))return"Error: file must be inside project_dir.";try{let X=MZ(z),K=GJ(X,J);return qJ(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}):
411
421
  ${z.join(`
412
- `)}`}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((U)=>({name:U.name.trim(),description:U.description.trim(),scores:U.scores,pros:U.pros||[],cons:U.cons||[]})),G=Z.custom_criteria,V=G&&G.length>0?G:BZ;return qJ(X,K,V).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let z=Z.stacktrace;return UJ(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=HJ(Q,z,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
422
+ `)}`}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:RZ;return CJ(X,K,V).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let z=Z.stacktrace;return EJ(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=RJ(Q,z,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
413
423
  Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
414
- Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,z=Z.query,J=z?OJ(z).slice(0,Q):NJ(Q);return MJ(J)}case"list_incidents":{let Q=Z.limit||10,z=Z.query,J=z?WJ(z).slice(0,Q):BJ(Q);return EJ(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=CJ(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 wJ(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})
415
- Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return kJ(Q)}case"trigger_self_reflection":{let Q=await c$();return yJ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),z=SJ(Q);return _J(z)}default:return null}}u();var s5=[{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 mJ($,Z){switch($){case"vault_status":{if(!Y2())return"Vault nao inicializado.";return l8(c8())}case"vault_backup":{if(!Y2())return"Vault nao inicializado.";let Y=Z.message||void 0;return await C$(Y)}case"sync_cloud_context":{if(!Y2())return"Vault nao inicializado.";return await i8()}case"vault_init_backup":{if(!Y2())return"Vault nao inicializado.";return await o8()}default:return null}}u();import{existsSync as q$,mkdirSync as QW,readFileSync as l$,readdirSync as zW}from"fs";import{join as V$}from"path";import{createHash as JW}from"crypto";var cJ=1,jZ=400,XW=80,pJ=1.5,dJ=0.75,KW=10,GW=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"]),H8="",t5="",V0=[],H1={},W1=0,B1={},e5=!1,AZ=()=>V$(t5,"rag-index.json");function lJ($){if(H8=$,t5=V$($,"rag"),!q$(t5))QW(t5,{recursive:!0});NW(),e5=!0}function $7(){return e5}function Z7(){return{chunks:V0.length,sources:Object.keys(B1).length,builtAt:V0.length>0?OW()?.builtAt??null:null}}function Y7(){if(!e5)throw Error("Memory not initialized. Call initMemory() first.");let $=HW(),Z=0,Y=0,Q={},z=new Set;for(let[X,K]of Object.entries($)){let G=CW(K);if(Q[X]=G,B1[X]!==G)z.add(X)}let J=Object.keys(B1).filter((X)=>!(X in $));if(z.size===0&&J.length===0)return{indexed:0,skipped:Object.keys($).length,total:V0.length};V0=V0.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),q=X.slice(G+1);if(!["memo","material","session","decision"].includes(V))continue;let H=MW(V,q,K),B=UW(K,V,q,H);V0=[...V0,...B],Z++}return Y=Object.keys($).length-Z,WW(),B1=Q,BW(),{indexed:Z,skipped:Y,total:V0.length}}function Q7($,Z=3){if(V0.length===0)return[];let Y=PZ($);if(Y.length===0)return[];return V0.map((z)=>{let J=VW(Y,z),X=qW(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,KW))}function z7($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let z=EW(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}%)
424
+ Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,z=Z.query,J=z?PJ(z).slice(0,Q):jJ(Q);return TJ(J)}case"list_incidents":{let Q=Z.limit||10,z=Z.query,J=z?FJ(z).slice(0,Q):LJ(Q);return DJ(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=AJ(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 hJ(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})
425
+ Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return gJ(Q)}case"trigger_self_reflection":{let Q=await l$();return pJ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),z=vJ(Q);return dJ(z)}case"add_content":{let Q=Z.type;if(!["video","movie","music"].includes(Q))return"Error: type must be video, movie, or music.";let J=Z.title;if(!J?.trim())return"Error: title is required.";let X=Z.creator;if(!X?.trim())return"Error: creator is required.";let K=Z.tags||[],G=Z.moods||[],V=Z.url,U=sJ(Q,J,X,K,G,V),q=U.moods.length>0?` (${U.moods.join(", ")})`:"",H=U.tags.length>0?` [${U.tags.map((B)=>"#"+B).join(" ")}]`:"";return`Conteudo adicionado: "${U.title}" \u2014 ${U.creator}${q}${H} {${U.id}}`}case"get_recommendations":{let{mood:Q,type:z}=Z,J=Math.min(Math.max(Z.limit||5,1),20),X=Y3(Q,z,J);return z3(X,Q)}case"rate_content":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=Z.rating;if(typeof z!=="number"||z<1||z>5)return"Error: rating must be between 1 and 5.";let J=tJ(Q,z);if(!J)return`Conteudo nao encontrado: "${Q}"`;return`Avaliado: "${J.title}" \u2014 ${"*".repeat(J.rating||0)}/5`}case"mark_content_consumed":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=eJ(Q);if(!z)return`Conteudo nao encontrado: "${Q}"`;return`Marcado como consumido: "${z.title}" (${z.timesConsumed}x)`}case"search_content":{let Q=Z.query;if(!Q?.trim())return h5(IZ());let z=Z3(Q),J=Z.type;if(J)z=z.filter((X)=>X.type===J);return h5(z)}case"list_catalog":{let Q=Z.type,z=Math.min(Math.max(Z.limit||20,1),100);return h5(IZ(Q,z))}case"remove_content":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";return $3(Q)?"Conteudo removido do catalogo.":`Conteudo nao encontrado: "${Q}"`}case"content_stats":return J3(Q3());default:return null}}u();var Z7=[{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 G3($,Z){switch($){case"vault_status":{if(!Q2())return"Vault nao inicializado.";return i8(o8())}case"vault_backup":{if(!Q2())return"Vault nao inicializado.";let Y=Z.message||void 0;return await C$(Y)}case"sync_cloud_context":{if(!Q2())return"Vault nao inicializado.";return await r8()}case"vault_init_backup":{if(!Q2())return"Vault nao inicializado.";return await n8()}default:return null}}u();import{existsSync as q$,mkdirSync as SW,readFileSync as o$,readdirSync as wW}from"fs";import{join as U$}from"path";import{createHash as kW}from"crypto";var q3=1,kZ=400,fW=80,V3=1.5,U3=0.75,bW=10,yW=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"]),B8="",Y7="",U0=[],W1={},B1=0,N1={},Q7=!1,bZ=()=>U$(Y7,"rag-index.json");function H3($){if(B8=$,Y7=U$($,"rag"),!q$(Y7))SW(Y7,{recursive:!0});mW(),Q7=!0}function z7(){return Q7}function J7(){return{chunks:U0.length,sources:Object.keys(N1).length,builtAt:U0.length>0?pW()?.builtAt??null:null}}function X7(){if(!Q7)throw Error("Memory not initialized. Call initMemory() first.");let $=hW(),Z=0,Y=0,Q={},z=new Set;for(let[X,K]of Object.entries($)){let G=dW(K);if(Q[X]=G,N1[X]!==G)z.add(X)}let J=Object.keys(N1).filter((X)=>!(X in $));if(z.size===0&&J.length===0)return{indexed:0,skipped:Object.keys($).length,total:U0.length};U0=U0.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=cW(V,U,K),B=vW(K,V,U,H);U0=[...U0,...B],Z++}return Y=Object.keys($).length-Z,gW(),N1=Q,uW(),{indexed:Z,skipped:Y,total:U0.length}}function K7($,Z=3){if(U0.length===0)return[];let Y=fZ($);if(Y.length===0)return[];return U0.map((z)=>{let J=_W(Y,z),X=xW(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,bW))}function G7($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let z=lW(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}%)
416
426
  ${X}`});return`Resultados da memoria (${$.length}):
417
427
 
418
428
  ${Z.join(`
419
429
 
420
- `)}`}function VW($,Z){let Y=Z.tokens.length;if(Y===0||W1===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=H1[J]??0;if(K===0)continue;let G=X*(pJ+1),V=X+pJ*(1-dJ+dJ*(Y/W1));z+=K*(G/V)}return z}function qW($,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 q=H1[V]??0,U=(Y.get(V)??0)*q,H=(Q.get(V)??0)*q;J+=U*H,X+=U*U,K+=H*H}let G=Math.sqrt(X)*Math.sqrt(K);return G>0?J/G:0}function PZ($){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&&!GW.has(Z))}function UW($,Z,Y,Q){let z=$.trim();if(z.length===0)return[];if(z.length<=jZ)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:z,tokens:PZ(z)}];let J=[],X=0,K=0;while(X<z.length){let G=Math.min(X+jZ,z.length),V=z.slice(X,G);J.push({id:`${Z}:${Y}:${K}`,source:Z,sourceId:Y,title:Q,content:V,tokens:PZ(V)}),X+=jZ-XW,K++}return J}function HW(){let $={},Z=V$(H8,"memos.json");if(q$(Z))try{let J=JSON.parse(l$(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=V$(H8,"materials.json");if(q$(Y))try{let J=JSON.parse(l$(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}
430
+ `)}`}function _W($,Z){let Y=Z.tokens.length;if(Y===0||B1===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=W1[J]??0;if(K===0)continue;let G=X*(V3+1),V=X+V3*(1-U3+U3*(Y/B1));z+=K*(G/V)}return z}function xW($,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=W1[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 fZ($){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&&!yW.has(Z))}function vW($,Z,Y,Q){let z=$.trim();if(z.length===0)return[];if(z.length<=kZ)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:z,tokens:fZ(z)}];let J=[],X=0,K=0;while(X<z.length){let G=Math.min(X+kZ,z.length),V=z.slice(X,G);J.push({id:`${Z}:${Y}:${K}`,source:Z,sourceId:Y,title:Q,content:V,tokens:fZ(V)}),X+=kZ-fW,K++}return J}function hW(){let $={},Z=U$(B8,"memos.json");if(q$(Z))try{let J=JSON.parse(o$(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=U$(B8,"materials.json");if(q$(Y))try{let J=JSON.parse(o$(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}
421
431
  ${G}
422
- ${K.content}${V}`}}catch{}let Q=V$(H8,"decisions.json");if(q$(Q))try{let J=JSON.parse(l$(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(`
423
- `)}}catch{}let z=V$(H8,"sessions");if(q$(z))try{let J=zW(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=V$(z,X);try{let G=JSON.parse(l$(K,"utf-8"));if(!G||typeof G!=="object"||!Array.isArray(G.messages))continue;let V=G.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(`
432
+ ${K.content}${V}`}}catch{}let Q=U$(B8,"decisions.json");if(q$(Q))try{let J=JSON.parse(o$(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(`
433
+ `)}}catch{}let z=U$(B8,"sessions");if(q$(z))try{let J=wW(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=U$(z,X);try{let G=JSON.parse(o$(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(`
424
434
  ---
425
- `);if(V.length>0)$[`session:${G.id}`]=V}catch{}}}catch{}return $}function WW(){let $=V0.length;if($===0){H1={},W1=0;return}let Z=new Map,Y=0;for(let z of V0){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}W1=Y/$;let Q={};for(let[z,J]of Z)Q[z]=Math.log(($-J+0.5)/(J+0.5)+1);H1=Q}function BW(){if(!e5)return;let $={chunks:V0,idf:H1,avgDocLength:W1,sourceHashes:B1,builtAt:new Date().toISOString(),version:cJ};A(AZ(),JSON.stringify($))}function NW(){let $=AZ();if(!q$($)){V0=[],H1={},W1=0,B1={};return}try{let Z=JSON.parse(l$($,"utf-8"));if(Z.version!==cJ){V0=[],H1={},W1=0,B1={};return}V0=Z.chunks,H1=Z.idf,W1=Z.avgDocLength,B1=Z.sourceHashes}catch{V0=[],H1={},W1=0,B1={}}}function OW(){let $=AZ();if(!q$($))return null;try{return{builtAt:JSON.parse(l$($,"utf-8")).builtAt}}catch{return null}}function CW($){return JW("sha256").update($).digest("hex").slice(0,16)}function MW($,Z,Y){switch($){case"material":{let Q=Y.split(`
435
+ `);if(V.length>0)$[`session:${G.id}`]=V}catch{}}}catch{}return $}function gW(){let $=U0.length;if($===0){W1={},B1=0;return}let Z=new Map,Y=0;for(let z of U0){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}B1=Y/$;let Q={};for(let[z,J]of Z)Q[z]=Math.log(($-J+0.5)/(J+0.5)+1);W1=Q}function uW(){if(!Q7)return;let $={chunks:U0,idf:W1,avgDocLength:B1,sourceHashes:N1,builtAt:new Date().toISOString(),version:q3};P(bZ(),JSON.stringify($))}function mW(){let $=bZ();if(!q$($)){U0=[],W1={},B1=0,N1={};return}try{let Z=JSON.parse(o$($,"utf-8"));if(Z.version!==q3){U0=[],W1={},B1=0,N1={};return}U0=Z.chunks,W1=Z.idf,B1=Z.avgDocLength,N1=Z.sourceHashes}catch{U0=[],W1={},B1=0,N1={}}}function pW(){let $=bZ();if(!q$($))return null;try{return{builtAt:JSON.parse(o$($,"utf-8")).builtAt}}catch{return null}}function dW($){return kW("sha256").update($).digest("hex").slice(0,16)}function cW($,Z,Y){switch($){case"material":{let Q=Y.split(`
426
436
  `)[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(`
427
- `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function EW($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var J7=[{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 oJ($,Z){switch($){case"recall_memory":{if(!$7())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=Q7(Y,Q);return z7(z)}case"index_memory":{if(!$7())return"Error: memory not initialized.";let Y=Y7();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!$7())return"Memory: nao inicializada.";let Y=Z7(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
437
+ `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function lW($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var V7=[{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 W3($,Z){switch($){case"recall_memory":{if(!z7())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=K7(Y,Q);return G7(z)}case"index_memory":{if(!z7())return"Error: memory not initialized.";let Y=X7();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!z7())return"Memory: nao inicializada.";let Y=J7(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
428
438
  Chunks: ${Y.chunks}
429
439
  Fontes: ${Y.sources}
430
- Ultima indexacao: ${Q}`}default:return null}}u();d0();import{join as RW}from"path";import{createHash as FW}from"crypto";var LW={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},W8={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"]},jW=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],PW="",P=null,DZ=[],aJ={...LW},sJ=!1,iJ=null,AW=()=>RW(PW,"plan-history.json");function N1(){return sJ}function TZ($,Z){let Y=$.toLowerCase(),Q=DW(Y),z=Z?.files||[],J=Z?.modules||[],X=[],K=[];for(let q of z)for(let U of jW)if(U.test(q))X.push(`Modifying sensitive file: ${q}`);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=aJ.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 DW($){for(let Z of W8.architectural)if($.includes(Z))return"architectural";for(let Z of W8.complex)if($.includes(Z))return"complex";for(let Z of W8.moderate)if($.includes(Z))return"moderate";for(let Z of W8.simple)if($.includes(Z))return"simple";for(let Z of W8.trivial)if($.includes(Z))return"trivial";return"moderate"}function tJ($,Z,Y){let Q=TZ($),z={id:nJ(),objective:$,strategy:Z.map((J,X)=>({...J,id:nJ(),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 P=z,M1().emit("planning:started",{planId:z.id,objective:$,timestamp:Date.now()}),z}async function eJ(){if(!P)return{success:!1,plan:null,message:"No active plan to submit"};if(P.status!=="draft")return{success:!1,plan:P,message:`Plan already in status: ${P.status}`};if(P={...P,status:"pending_approval",updatedAt:new Date().toISOString()},aJ.autoApproveComplexity.includes(P.complexity))return rJ("Auto-approved based on complexity classification");if(iJ)if(await iJ(P))return rJ("Approved by user");else return TW("Rejected by user");return{success:!0,plan:P,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function rJ($){if(!P)return{success:!1,plan:null,message:"No active plan to approve"};if(P.status!=="pending_approval"&&P.status!=="draft")return{success:!1,plan:P,message:`Cannot approve plan in status: ${P.status}`};return P={...P,status:"approved",approvedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),userFeedback:$},M1().emit("planning:approved",{planId:P.id,feedback:$,timestamp:Date.now()}),{success:!0,plan:P,message:"Plan approved \u2014 execution may proceed"}}function TW($){if(!P)return{success:!1,plan:null,message:"No active plan to reject"};return P={...P,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},M1().emit("planning:rejected",{planId:P.id,feedback:$,timestamp:Date.now()}),z3(P),P=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function $3(){if(!P)return{allowed:!0,reason:"No plan required \u2014 trivial operation"};if(P.status==="approved"||P.status==="executing")return{allowed:!0,reason:"Plan approved \u2014 execution permitted"};if(P.status==="draft"||P.status==="pending_approval")return{allowed:!1,reason:`Execution blocked \u2014 plan awaiting approval (status: ${P.status})`};return{allowed:!1,reason:`Execution blocked \u2014 plan status: ${P.status}`}}function Z3($,Z){if(!P)return{success:!1,message:"No active plan"};let Y=P.strategy.findIndex((K)=>K.id===$);if(Y===-1)return{success:!1,message:`Step not found: ${$}`};let Q=P.strategy.map((K,G)=>G===Y?{...K,status:"completed",result:Z}:K);P={...P,strategy:Q,updatedAt:new Date().toISOString()},M1().emit("planning:step_completed",{planId:P.id,stepId:$,result:Z,timestamp:Date.now()});let z=P.strategy.find((K)=>K.status==="pending"),J=P.strategy[Y].action;if(P.strategy.every((K)=>K.status==="completed"||K.status==="skipped"))IW();return{success:!0,message:`Step completed: ${J}`,nextStep:z}}function Y3($,Z,Y){if(!P)return{success:!1,message:"No active plan"};let Q=P.strategy.findIndex((J)=>J.id===$);if(Q===-1)return{success:!1,message:`Step not found: ${$}`};let z=P.strategy.map((J,X)=>X===Q?{...J,status:"blocked",blockedReason:Z}:J);return P={...P,strategy:z,status:"blocked",blockedAt:new Date().toISOString(),blockedReason:Z,updatedAt:new Date().toISOString()},M1().emit("planning:blocked",{planId:P.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 IW(){if(!P)return;P={...P,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},M1().emit("planning:completed",{planId:P.id,stepsCompleted:P.strategy.filter(($)=>$.status==="completed").length,timestamp:Date.now()}),z3(P),P=null}function B8(){return P?{...P}:null}function IZ($){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(`
440
+ Ultima indexacao: ${Q}`}default:return null}}u();c0();import{join as oW}from"path";import{createHash as iW}from"crypto";var nW={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},N8={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"]},rW=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],aW="",A=null,yZ=[],M3={...nW},C3=!1,B3=null,sW=()=>oW(aW,"plan-history.json");function O1(){return C3}function _Z($,Z){let Y=$.toLowerCase(),Q=tW(Y),z=Z?.files||[],J=Z?.modules||[],X=[],K=[];for(let U of z)for(let q of rW)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=M3.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 tW($){for(let Z of N8.architectural)if($.includes(Z))return"architectural";for(let Z of N8.complex)if($.includes(Z))return"complex";for(let Z of N8.moderate)if($.includes(Z))return"moderate";for(let Z of N8.simple)if($.includes(Z))return"simple";for(let Z of N8.trivial)if($.includes(Z))return"trivial";return"moderate"}function E3($,Z,Y){let Q=_Z($),z={id:O3(),objective:$,strategy:Z.map((J,X)=>({...J,id:O3(),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,E1().emit("planning:started",{planId:z.id,objective:$,timestamp:Date.now()}),z}async function R3(){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()},M3.autoApproveComplexity.includes(A.complexity))return N3("Auto-approved based on complexity classification");if(B3)if(await B3(A))return N3("Approved by user");else return eW("Rejected by user");return{success:!0,plan:A,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function N3($){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:$},E1().emit("planning:approved",{planId:A.id,feedback:$,timestamp:Date.now()}),{success:!0,plan:A,message:"Plan approved \u2014 execution may proceed"}}function eW($){if(!A)return{success:!1,plan:null,message:"No active plan to reject"};return A={...A,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},E1().emit("planning:rejected",{planId:A.id,feedback:$,timestamp:Date.now()}),A3(A),A=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function F3(){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 L3($,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()},E1().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"))$B();return{success:!0,message:`Step completed: ${J}`,nextStep:z}}function j3($,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()},E1().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 $B(){if(!A)return;A={...A,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},E1().emit("planning:completed",{planId:A.id,stepsCompleted:A.strategy.filter(($)=>$.status==="completed").length,timestamp:Date.now()}),A3(A),A=null}function O8(){return A?{...A}:null}function xZ($){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(`
431
441
  `):" (nenhuma)",Q=$.risks.length>0?$.risks.map((z)=>` - ${z}`).join(`
432
442
  `):" (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(`
433
- `)}function Q3($){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(`
434
- `)}function z3($){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};DZ=[...DZ,Z],SW()}function SW(){if(!sJ)return;A(AW(),JSON.stringify(DZ,null,2))}function nJ(){return FW("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function J3(){return`
443
+ `)}function P3($){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(`
444
+ `)}function A3($){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};yZ=[...yZ,Z],ZB()}function ZB(){if(!C3)return;P(sW(),JSON.stringify(yZ,null,2))}function O3(){return iW("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function T3(){return`
435
445
  ## Protocolo de Alta Ag\xEAncia
436
446
 
437
447
  Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
@@ -473,54 +483,54 @@ Ao usar \`propose_plan\`, estruture assim:
473
483
  - **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
474
484
  - **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
475
485
  - **Bloqueio**: Sempre termine com "Posso prosseguir com este plano?"
476
- `.trim()}var X7=[{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 X3($,Z){switch($){case"propose_plan":{if(!N1())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=tJ(Y,z,{assumptions:Z.assumptions,risks:Z.risks}),X=await eJ();if(!X.success)return`Error creating plan: ${X.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
486
+ `.trim()}var U7=[{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 D3($,Z){switch($){case"propose_plan":{if(!O1())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=E3(Y,z,{assumptions:Z.assumptions,risks:Z.risks}),X=await R3();if(!X.success)return`Error creating plan: ${X.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
477
487
 
478
- ${IZ(J)}`}case"check_plan_status":{if(!N1())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=$3(),Q=B8();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${Q3(Q)}
488
+ ${xZ(J)}`}case"check_plan_status":{if(!O1())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=F3(),Q=O8();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${P3(Q)}
479
489
 
480
490
  Execu\xE7\xE3o: ${Y.allowed?"PERMITIDA":"BLOQUEADA"}
481
- Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!N1())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=B8();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)Y3(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(`
482
- `)}case"complete_plan_step":{if(!N1())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=Z3(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let z=B8(),J=z?`Progresso: ${z.strategy.filter((K)=>K.status==="completed").length}/${z.strategy.length}`:"",X=Q.nextStep?`
491
+ Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!O1())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=O8();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)j3(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(`
492
+ `)}case"complete_plan_step":{if(!O1())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=L3(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let z=O8(),J=z?`Progresso: ${z.strategy.filter((K)=>K.status==="completed").length}/${z.strategy.length}`:"",X=Q.nextStep?`
483
493
  Pr\xF3ximo passo: ${Q.nextStep.action} \u2192 ${Q.nextStep.target}`:`
484
494
  Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Q.message}
485
- ${J}${X}`}case"get_current_plan":{if(!N1())return"Agency engine not initialized. No planning features available.";let Y=B8();if(!Y)return"Nenhum plano ativo no momento.";return IZ(Y)}case"analyze_task_complexity":{if(!N1())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=TZ(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(`
486
- `)}default:return null}}n();import{existsSync as H3,readdirSync as kW,readFileSync as fW,mkdirSync as bW}from"fs";import{join as kZ}from"path";var N8={"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.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 K3={"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.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 G3($){if($!=="auto")return SZ($);try{let Y=Intl.DateTimeFormat().resolvedOptions().locale;if(Y){let Q=SZ(Y);if(Q!=="en")return Q}}catch{}let Z=process.env.LANG||process.env.LC_ALL||process.env.LANGUAGE||"";if(Z)return SZ(Z);return"en"}function SZ($){if($.toLowerCase().replace(/_/g,"-").startsWith("pt"))return"pt";return"en"}var wW={en:N8,pt:K3},V3="en",wZ=N8;function q3($){V3=G3($),wZ=wW[V3]||N8}function O8($,Z){let Y=wZ[$]||N8[$]||$;if(Z)for(let[Q,z]of Object.entries(Z))Y=Y.replace(new RegExp(`\\{\\{${Q}\\}\\}`,"g"),String(z));return Y}function U3(){return{...wZ}}function o$($){if(!H3($))return[];let Z=[],Y=kW($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let z=JSON.parse(fW(kZ($,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:kZ($,Q)})}catch{}return Z}function i$($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function K7($,Z){let Y=$.command;for(let[q,U]of Object.entries(Z)){let H=String(U).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${q}\\}\\}`,"g"),H)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let Q=O$(),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?`
495
+ ${J}${X}`}case"get_current_plan":{if(!O1())return"Agency engine not initialized. No planning features available.";let Y=O8();if(!Y)return"Nenhum plano ativo no momento.";return xZ(Y)}case"analyze_task_complexity":{if(!O1())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=_Z(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(`
496
+ `)}default:return null}}a();import{existsSync as b3,readdirSync as QB,readFileSync as zB,mkdirSync as JB}from"fs";import{join as gZ}from"path";var M8={"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.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 I3={"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.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 S3($){if($!=="auto")return vZ($);try{let Y=Intl.DateTimeFormat().resolvedOptions().locale;if(Y){let Q=vZ(Y);if(Q!=="en")return Q}}catch{}let Z=process.env.LANG||process.env.LC_ALL||process.env.LANGUAGE||"";if(Z)return vZ(Z);return"en"}function vZ($){if($.toLowerCase().replace(/_/g,"-").startsWith("pt"))return"pt";return"en"}var YB={en:M8,pt:I3},w3="en",hZ=M8;function k3($){w3=S3($),hZ=YB[w3]||M8}function C8($,Z){let Y=hZ[$]||M8[$]||$;if(Z)for(let[Q,z]of Object.entries(Z))Y=Y.replace(new RegExp(`\\{\\{${Q}\\}\\}`,"g"),String(z));return Y}function f3(){return{...hZ}}function i$($){if(!b3($))return[];let Z=[],Y=QB($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let z=JSON.parse(zB(gZ($,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:gZ($,Q)})}catch{}return Z}function n$($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function q7($,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=M$(),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?`
487
497
  `:"")+K.trim();if(G!==0)V+=(V?`
488
- `:"")+`Exit code: ${G}`;return V||"(no output)"}function W3($){let Z=kZ($,"plugins");if(!H3(Z))bW(Z,{recursive:!0});return Z}import{existsSync as B0,readdirSync as q7,readFileSync as M8,mkdirSync as bZ,renameSync as fZ,rmSync as C8}from"fs";import{join as p,basename as G7,extname as V7}from"path";d0();d0();var S=[],L0="",B3="";async function N3($,Z){if(L0=$,B3=Z,S=[],!B0($))return bZ($,{recursive:!0}),[];let Y=o$($);for(let z of Y)S=[...S,{name:z.name,description:z.description,version:"1.0.0",type:"json",source:z.source,enabled:!0,tools:i$([z]),jsonPlugin:z,eventUnsubs:[]}];let Q=q7($).filter((z)=>{let J=V7(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){g.debug(`Skipping invalid script plugin: ${z}`);continue}let G=await yZ(K,J);if(G)S=[...S,G]}catch(X){g.debug(`Failed to load script plugin: ${z}`,{error:X instanceof Error?X.message:String(X)})}}return Q0("status:update",{source:"plugin-system",message:`${S.length} plugin(s) carregado(s)`,level:"info",timestamp:Date.now()}),S}async function yZ($,Z){let Y=p(B3,"plugins",$.name);if(!B0(Y))bZ(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 g.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 O3(){return S.filter(($)=>$.enabled).flatMap(($)=>[...$.tools])}async function C3($,Z){for(let Y of S){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 K7(Y.jsonPlugin,Z)}return null}function M3($){let Z=S.findIndex((J)=>J.name===$);if(Z===-1)return!1;let Y=S[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(L0,"disabled");if(!B0(Q))bZ(Q,{recursive:!0});let z=p(Q,G7(Y.source));try{fZ(Y.source,z)}catch{}return S=S.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 E3($){let Z=S.findIndex((G)=>G.name===$&&!G.enabled);if(Z!==-1){let G=S[Z],V=p(L0,"disabled"),q=p(V,G7(G.source)),U=p(L0,G7(G.source));if(B0(q))try{fZ(q,U)}catch{}return S=S.map((H,B)=>B===Z?{...H,enabled:!0,source:U}:H),Q0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}let Y=p(L0,"disabled");if(!B0(Y))return!1;let z=q7(Y).find((G)=>{return G7(G,V7(G))===$});if(!z)return!1;let J=p(Y,z),X=p(L0,z);try{fZ(J,X)}catch{return!1}let K=V7(z);if(K===".json"){let G=o$(L0).filter((V)=>V.source===X);for(let V of G)S=[...S,{name:V.name,description:V.description,version:"1.0.0",type:"json",source:V.source,enabled:!0,tools:i$([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 q=await yZ(V,X);if(q)S=[...S,q]}}catch{}return Q0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}async function R3($){if(!L0)return{success:!1,name:"",message:"Plugin system nao inicializado."};let Z=yW($);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(L0,"installed",`${Y}--${Q}`);if(B0(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 C=Bun.spawn(K,{stdout:"pipe",stderr:"pipe"}),M=setTimeout(()=>C.kill(),30000),[,F]=await Promise.all([new Response(C.stdout).text(),new Response(C.stderr).text()]),w=await C.exited;if(clearTimeout(M),w!==0){try{C8(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`git clone falhou: ${F.trim().split(`
489
- `)[0]||`exit code ${w}`}`}}}catch(C){try{C8(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`Erro ao clonar: ${C instanceof Error?C.message:String(C)}`}}let G=_W(J);if(!G){try{C8(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=V7(G.path),q=`${Y}--${Q}${V}`,U=p(L0,q);if(V===".ts"||V===".js"){let C=G.path.replace(/\\/g,"/"),M=`// Auto-installed from github.com/${Y}/${Q}
490
- export { default } from '${C}'
491
- `;Bun.write(U,M)}else{let C=M8(G.path,"utf-8");Bun.write(U,C)}if(V===".json"){let C=o$(L0).filter((M)=>M.source===U);for(let M of C)S=[...S,{name:M.name,description:M.description,version:"1.0.0",type:"json",source:U,enabled:!0,tools:i$([M]),jsonPlugin:M,eventUnsubs:[]}]}else try{let C=await import(G.path),M=C.default||C;if(M.name&&M.description){let F=await yZ(M,U);if(F)S=[...S,F]}}catch{}let B=S.find((C)=>C.source===U)?.name||`${Y}/${Q}`;Q0("status:update",{source:"plugin-system",message:`Plugin "${B}" instalado de github.com/${Y}/${Q}`,level:"success",timestamp:Date.now()});let N=p(J,".smolerclaw-install.json");return Bun.write(N,JSON.stringify({source:`${Y}/${Q}`,branch:z||"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 F3($){if(!L0)return{success:!1,message:"Plugin system nao inicializado."};let Z=p(L0,"installed");if(!B0(Z))return{success:!1,message:`Plugin "${$}" nao encontrado.`};let Y=S.find((J)=>J.name===$),Q=null,z=null;if(Y){z=Y.source;let J=q7(Z).filter((X)=>B0(p(Z,X,".smolerclaw-install.json")));for(let X of J)try{let K=JSON.parse(M8(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(B0(X)){Q=X;try{z=JSON.parse(M8(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{}S=S.filter((J)=>J.name!==$)}if(z&&B0(z))try{C8(z,{force:!0})}catch{}if(Q)try{C8(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 L3(){let $=p(L0,"installed");if(!B0($))return[];let Z=[],Y=q7($);for(let Q of Y){let z=p($,Q,".smolerclaw-install.json");if(!B0(z))continue;try{let J=JSON.parse(M8(z,"utf-8"));Z.push({name:J.pluginName||Q,source:J.source||Q.replace("--","/"),installedAt:J.installedAt||"desconhecido"})}catch{}}return Z}function yW($){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 _W($){let Z=p($,"package.json");if(B0(Z))try{let z=JSON.parse(M8(Z,"utf-8"));if(z.smolerclaw){let J=p($,z.smolerclaw);if(B0(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(B0(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(B0(J))return{path:J}}return null}function j3($){return S.find((Z)=>Z.name===$)}function P3(){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",z=Z.tools.length;$.push(` ${Z.name} v${Z.version} (${Q}) \u2014 ${Z.description} [${z} tool${z!==1?"s":""}]${Y}`)}return $.join(`
492
- `)}async function A3(){for(let $ of S){for(let Z of $.eventUnsubs)Z();if($.type==="script"&&$.scriptDef?.onUnload)try{await $.scriptDef.onUnload()}catch{}}S=[]}u();import{existsSync as vZ,readFileSync as I3,statSync as gW}from"fs";import{resolve as hZ}from"path";import{existsSync as xW,realpathSync as vW}from"fs";import{resolve as hW,sep as D3}from"path";var _Z=10485760;function h1($){let Z=hW($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+D3))return`Error: path outside working directory is not permitted: ${Z}`;try{if(xW(Z)){let Q=vW(Z);if(Q!==Y&&!Q.startsWith(Y+D3))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function O1($,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 xZ($){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 T3($){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,`
498
+ `:"")+`Exit code: ${G}`;return V||"(no output)"}function y3($){let Z=gZ($,"plugins");if(!b3(Z))JB(Z,{recursive:!0});return Z}import{existsSync as N0,readdirSync as B7,readFileSync as R8,mkdirSync as mZ,renameSync as uZ,rmSync as E8}from"fs";import{join as d,basename as H7,extname as W7}from"path";c0();c0();var S=[],j0="",_3="";async function x3($,Z){if(j0=$,_3=Z,S=[],!N0($))return mZ($,{recursive:!0}),[];let Y=i$($);for(let z of Y)S=[...S,{name:z.name,description:z.description,version:"1.0.0",type:"json",source:z.source,enabled:!0,tools:n$([z]),jsonPlugin:z,eventUnsubs:[]}];let Q=B7($).filter((z)=>{let J=W7(z);return J===".ts"||J===".js"});for(let z of Q){let J=d($,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 pZ(K,J);if(G)S=[...S,G]}catch(X){m.debug(`Failed to load script plugin: ${z}`,{error:X instanceof Error?X.message:String(X)})}}return z0("status:update",{source:"plugin-system",message:`${S.length} plugin(s) carregado(s)`,level:"info",timestamp:Date.now()}),S}async function pZ($,Z){let Y=d(_3,"plugins",$.name);if(!N0(Y))mZ(Y,{recursive:!0});let Q={notify:(J,X="info")=>{z0("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=e.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 v3(){return S.filter(($)=>$.enabled).flatMap(($)=>[...$.tools])}async function h3($,Z){for(let Y of S){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 q7(Y.jsonPlugin,Z)}return null}function g3($){let Z=S.findIndex((J)=>J.name===$);if(Z===-1)return!1;let Y=S[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=d(j0,"disabled");if(!N0(Q))mZ(Q,{recursive:!0});let z=d(Q,H7(Y.source));try{uZ(Y.source,z)}catch{}return S=S.map((J,X)=>X===Z?{...J,enabled:!1,eventUnsubs:[]}:J),z0("status:update",{source:"plugin-system",message:`Plugin "${$}" desabilitado`,level:"info",timestamp:Date.now()}),!0}async function u3($){let Z=S.findIndex((G)=>G.name===$&&!G.enabled);if(Z!==-1){let G=S[Z],V=d(j0,"disabled"),U=d(V,H7(G.source)),q=d(j0,H7(G.source));if(N0(U))try{uZ(U,q)}catch{}return S=S.map((H,B)=>B===Z?{...H,enabled:!0,source:q}:H),z0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}let Y=d(j0,"disabled");if(!N0(Y))return!1;let z=B7(Y).find((G)=>{return H7(G,W7(G))===$});if(!z)return!1;let J=d(Y,z),X=d(j0,z);try{uZ(J,X)}catch{return!1}let K=W7(z);if(K===".json"){let G=i$(j0).filter((V)=>V.source===X);for(let V of G)S=[...S,{name:V.name,description:V.description,version:"1.0.0",type:"json",source:V.source,enabled:!0,tools:n$([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 pZ(V,X);if(U)S=[...S,U]}}catch{}return z0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}async function m3($){if(!j0)return{success:!1,name:"",message:"Plugin system nao inicializado."};let Z=XB($);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=d(j0,"installed",`${Y}--${Q}`);if(N0(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{E8(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`git clone falhou: ${F.trim().split(`
499
+ `)[0]||`exit code ${k}`}`}}}catch(M){try{E8(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=KB(J);if(!G){try{E8(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=W7(G.path),U=`${Y}--${Q}${V}`,q=d(j0,U);if(V===".ts"||V===".js"){let M=G.path.replace(/\\/g,"/"),C=`// Auto-installed from github.com/${Y}/${Q}
500
+ export { default } from '${M}'
501
+ `;Bun.write(q,C)}else{let M=R8(G.path,"utf-8");Bun.write(q,M)}if(V===".json"){let M=i$(j0).filter((C)=>C.source===q);for(let C of M)S=[...S,{name:C.name,description:C.description,version:"1.0.0",type:"json",source:q,enabled:!0,tools:n$([C]),jsonPlugin:C,eventUnsubs:[]}]}else try{let M=await import(G.path),C=M.default||M;if(C.name&&C.description){let F=await pZ(C,q);if(F)S=[...S,F]}}catch{}let B=S.find((M)=>M.source===q)?.name||`${Y}/${Q}`;z0("status:update",{source:"plugin-system",message:`Plugin "${B}" instalado de github.com/${Y}/${Q}`,level:"success",timestamp:Date.now()});let N=d(J,".smolerclaw-install.json");return Bun.write(N,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 p3($){if(!j0)return{success:!1,message:"Plugin system nao inicializado."};let Z=d(j0,"installed");if(!N0(Z))return{success:!1,message:`Plugin "${$}" nao encontrado.`};let Y=S.find((J)=>J.name===$),Q=null,z=null;if(Y){z=Y.source;let J=B7(Z).filter((X)=>N0(d(Z,X,".smolerclaw-install.json")));for(let X of J)try{let K=JSON.parse(R8(d(Z,X,".smolerclaw-install.json"),"utf-8"));if(K.pluginName===$||K.entryPoint===z){Q=d(Z,X);break}}catch{}}else{let J=$.replace("/","--"),X=d(Z,J);if(N0(X)){Q=X;try{z=JSON.parse(R8(d(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{}S=S.filter((J)=>J.name!==$)}if(z&&N0(z))try{E8(z,{force:!0})}catch{}if(Q)try{E8(Q,{recursive:!0,force:!0})}catch{}return z0("status:update",{source:"plugin-system",message:`Plugin "${$}" desinstalado`,level:"info",timestamp:Date.now()}),{success:!0,message:`Plugin "${$}" desinstalado com sucesso.`}}function d3(){let $=d(j0,"installed");if(!N0($))return[];let Z=[],Y=B7($);for(let Q of Y){let z=d($,Q,".smolerclaw-install.json");if(!N0(z))continue;try{let J=JSON.parse(R8(z,"utf-8"));Z.push({name:J.pluginName||Q,source:J.source||Q.replace("--","/"),installedAt:J.installedAt||"desconhecido"})}catch{}}return Z}function XB($){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 KB($){let Z=d($,"package.json");if(N0(Z))try{let z=JSON.parse(R8(Z,"utf-8"));if(z.smolerclaw){let J=d($,z.smolerclaw);if(N0(J))return{path:J}}}catch{}let Y=["plugin.json","plugin.ts","plugin.js","index.ts","index.js"];for(let z of Y){let J=d($,z);if(N0(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=d($,z);if(N0(J))return{path:J}}return null}function c3($){return S.find((Z)=>Z.name===$)}function l3(){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",z=Z.tools.length;$.push(` ${Z.name} v${Z.version} (${Q}) \u2014 ${Z.description} [${z} tool${z!==1?"s":""}]${Y}`)}return $.join(`
502
+ `)}async function o3(){for(let $ of S){for(let Z of $.eventUnsubs)Z();if($.type==="script"&&$.scriptDef?.onUnload)try{await $.scriptDef.onUnload()}catch{}}S=[]}u();import{existsSync as lZ,readFileSync as r3,statSync as qB}from"fs";import{resolve as oZ}from"path";import{existsSync as GB,realpathSync as VB}from"fs";import{resolve as UB,sep as i3}from"path";var dZ=10485760;function g1($){let Z=UB($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+i3))return`Error: path outside working directory is not permitted: ${Z}`;try{if(GB(Z)){let Q=VB(Z);if(Q!==Y&&!Q.startsWith(Y+i3))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function M1($,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 cZ($){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 n3($){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,`
493
503
  `).replace(/<(br|hr)[^>]*\/?>/gi,`
494
504
  `).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,`
495
505
 
496
- `).trim()}function S3($){let Z=O1($,"path");if(Z)return Z;let Y=hZ($.path),Q=h1(Y);if(Q)return Q;if(!vZ(Y))return`Error: file not found: ${Y}`;let z=gW(Y).size;if(z>_Z)return`Error: file too large (${U8(z)}). Max is ${U8(_Z)}.`;let X=I3(Y,"utf-8").split(`
497
- `),K=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),U=X.slice(K-1,K-1+G).map((B,N)=>`${String(K+N).padStart(4)} ${B}`).join(`
498
- `),H=X.length-(K-1+G);if(H>0)U+=`
499
- ... (${H} more lines, total ${X.length})`;return r0(U)}function w3($,Z){let Y=O1($,"path");if(Y)return Y;let Q=hZ($.path),z=h1(Q);if(z)return z;let J=$.content,X=vZ(Q);Z.saveState(Q),A(Q,J);let K=J.split(`
500
- `).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function k3($,Z){let Y=O1($,"path");if(Y)return Y;let Q=hZ($.path),z=h1(Q);if(z)return z;if(!vZ(Q))return`Error: file not found: ${Q}`;let J=I3(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);A(Q,V);let q=X.split(`
501
- `).length,U=K.split(`
502
- `).length;return`Edited: ${Q} (replaced ${q} lines with ${U} lines)`}n();import{existsSync as uW,readdirSync as mW,readFileSync as pW,statSync as dW}from"fs";import{resolve as gZ,join as b3,sep as f3}from"path";async function y3($){let Z=O1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=gZ($.path||"."),z=h1(Q);if(z)return z;let J=$.include;if(await QY())return cW(Y,Q,J);return lW(Y,Q,J)}async function cW($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let K of $2)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 oW(J,Z)}async function lW($,Z,Y){let Q;try{Q=new RegExp($)}catch(q){return`Error: invalid regex pattern: ${q instanceof Error?q.message:$}`}let z=Y||"**/*",J=new Bun.Glob(z),X=[],K=0,G=5000;for await(let q of J.scan({cwd:Z,onlyFiles:!0})){if(u7(q))continue;if(++K>G){X.push(`... (stopped after scanning ${G} files)`);break}let U=b3(Z,q);try{let B=pW(U,"utf-8").split(`
503
- `);for(let N=0;N<B.length;N++)if(Q.test(B[N])){if(X.push(`${q}:${N+1}:${B[N]}`),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
+ `).trim()}function a3($){let Z=M1($,"path");if(Z)return Z;let Y=oZ($.path),Q=g1(Y);if(Q)return Q;if(!lZ(Y))return`Error: file not found: ${Y}`;let z=qB(Y).size;if(z>dZ)return`Error: file too large (${W8(z)}). Max is ${W8(dZ)}.`;let X=r3(Y,"utf-8").split(`
507
+ `),K=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),q=X.slice(K-1,K-1+G).map((B,N)=>`${String(K+N).padStart(4)} ${B}`).join(`
508
+ `),H=X.length-(K-1+G);if(H>0)q+=`
509
+ ... (${H} more lines, total ${X.length})`;return r0(q)}function s3($,Z){let Y=M1($,"path");if(Y)return Y;let Q=oZ($.path),z=g1(Q);if(z)return z;let J=$.content,X=lZ(Q);Z.saveState(Q),P(Q,J);let K=J.split(`
510
+ `).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function t3($,Z){let Y=M1($,"path");if(Y)return Y;let Q=oZ($.path),z=g1(Q);if(z)return z;if(!lZ(Q))return`Error: file not found: ${Q}`;let J=r3(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(`
511
+ `).length,q=K.split(`
512
+ `).length;return`Edited: ${Q} (replaced ${U} lines with ${q} lines)`}a();import{existsSync as HB,readdirSync as WB,readFileSync as BB,statSync as NB}from"fs";import{resolve as iZ,join as $X,sep as e3}from"path";async function ZX($){let Z=M1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=iZ($.path||"."),z=g1(Q);if(z)return z;let J=$.include;if(await qY())return OB(Y,Q,J);return MB(Y,Q,J)}async function OB($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let K of Z2)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 CB(J,Z)}async function MB($,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(c7(U))continue;if(++K>G){X.push(`... (stopped after scanning ${G} files)`);break}let q=$X(Z,U);try{let B=BB(q,"utf-8").split(`
513
+ `);for(let N=0;N<B.length;N++)if(Q.test(B[N])){if(X.push(`${U}:${N+1}:${B[N]}`),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(`
504
514
  `);if(X.length>100)V+=`
505
- ... (showing first 100 matches)`;return r0(V)}async function _3($){let Z=O1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=gZ($.path||"."),z=h1(Q);if(z)return z;let J=new Bun.Glob(Y),X=[];for await(let G of J.scan({cwd:Q,onlyFiles:!0})){if(u7(G))continue;if(X.push(G),X.length>=200)break}if(X.length===0)return"No files found.";let K=X.join(`
515
+ ... (showing first 100 matches)`;return r0(V)}async function YX($){let Z=M1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=iZ($.path||"."),z=g1(Q);if(z)return z;let J=new Bun.Glob(Y),X=[];for await(let G of J.scan({cwd:Q,onlyFiles:!0})){if(c7(G))continue;if(X.push(G),X.length>=200)break}if(X.length===0)return"No files found.";let K=X.join(`
506
516
  `);if(X.length>=200)K+=`
507
- ... (showing first 200 files)`;return K}function x3($){let Z=gZ($.path||"."),Y=h1(Z);if(Y)return Y;if(!uW(Z))return`Error: not found: ${Z}`;return mW(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=dW(b3(Z,J.name)),K=U8(X.size);return`f ${J.name} ${K}`}catch{return`f ${J.name}`}}).join(`
508
- `)}function oW($,Z){let Y=process.cwd(),Q=Y+f3,z=Z+f3,X=$.trim().split(`
517
+ ... (showing first 200 files)`;return K}function QX($){let Z=iZ($.path||"."),Y=g1(Z);if(Y)return Y;if(!HB(Z))return`Error: not found: ${Z}`;return WB(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=NB($X(Z,J.name)),K=W8(X.size);return`f ${J.name} ${K}`}catch{return`f ${J.name}`}}).join(`
518
+ `)}function CB($,Z){let Y=process.cwd(),Q=Y+e3,z=Z+e3,X=$.trim().split(`
509
519
  `).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(`
510
520
  `);if(K>100)G+=`
511
- ... (${K-100} more matches)`;return r0(G)}n();async function v3($){let Z=O1($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),z=O$(),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 q="";if(K.trim())q+=K.trim();if(G.trim())q+=(q?`
521
+ ... (${K-100} more matches)`;return r0(G)}a();async function zX($){let Z=M1($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),z=M$(),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?`
512
522
  `:"")+`STDERR:
513
- `+G.trim();if(V!==0)q+=(q?`
514
- `:"")+`Exit code: ${V}`;return r0(q||"(no output)")}async function h3($){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=xZ(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 N=xZ(B);if(N)return`Redirect blocked: ${N}`;return`Status: ${G.status} -> Redirect to: ${B}
515
- (Use fetch_url on the redirect target if needed)`}let V=`${G.status} ${G.statusText}`,q=G.headers.get("content-type")||"";if(Y==="HEAD"){let B=[...G.headers.entries()].map(([N,C])=>`${N}: ${C}`).join(`
523
+ `+G.trim();if(V!==0)U+=(U?`
524
+ `:"")+`Exit code: ${V}`;return r0(U||"(no output)")}async function JX($){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=cZ(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 N=cZ(B);if(N)return`Redirect blocked: ${N}`;return`Status: ${G.status} -> Redirect to: ${B}
525
+ (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(([N,M])=>`${N}: ${M}`).join(`
516
526
  `);return`Status: ${V}
517
- ${B}`}let U=G.headers.get("content-length");if(U&&Number(U)>q8*2)return`Status: ${V}
527
+ ${B}`}let q=G.headers.get("content-length");if(q&&Number(q)>H8*2)return`Status: ${V}
518
528
 
519
- Error: response body too large (${U} bytes). Max is ${q8*2} bytes.`;let H=await G.text();if(q.includes("text/html")){let B=T3(H);return r0(`Status: ${V}
529
+ Error: response body too large (${q} bytes). Max is ${H8*2} bytes.`;let H=await G.text();if(U.includes("text/html")){let B=n3(H);return r0(`Status: ${V}
520
530
 
521
531
  ${B}`)}return r0(`Status: ${V}
522
532
 
523
- ${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 g3($,Z,Y,Q,z){let J=performance.now();try{let X=await iW($,Z,Y,Q,z);return setImmediate(()=>{CZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!X.startsWith("Error:")})}),X}catch(X){return setImmediate(()=>{CZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${X instanceof Error?X.message:String(X)}`}}async function iW($,Z,Y,Q,z){switch($){case"read_file":return S3(Z);case"write_file":return w3(Z,Y);case"edit_file":return k3(Z,Y);case"search_files":return await y3(Z);case"find_files":return await _3(Z);case"list_directory":return x3(Z);case"run_command":return await v3(Z);case"fetch_url":return await h3(Z)}let J=await mJ($,Z);if(J!==null)return J;let X=oJ($,Z);if(X!==null)return X;let K=await X3($,Z);if(K!==null)return K;let G=await uJ($,Z,z);if(G!==null)return G;let V=await C3($,Z);if(V!==null)return V;let q=Q.find((U)=>U.name===$);if(q)return await K7(q,Z);return`Error: unknown tool "${$}"`}var r$=new D6,m3=[];function uZ($){m3=$}var p3=null;function mZ($){p3=$}var u3=!1;function pZ(){if(u3)return;if(u3=!0,L)b.push(...o2),b.push(...A4),b.push(...D4);else b.push(T4);b.push(...x5),b.push(...v5),b.push(...h5),b.push(...g5),b.push(u5),b.push(...m5),b.push(...p5),b.push(...d5),b.push(...J7),b.push(...r5),b.push(...s5),b.push(...c5),b.push(...l5),b.push(...o5),b.push(...n5),b.push(...i5),b.push(...a5),b.push(...X7)}async function U7($,Z){return g3($,Z,r$,m3,p3)}var rW=new Set([429,500,502,503,529]);async function c3($,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(nW(X)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(J+1,500,"Auth refreshed, retrying..."),await d3(500,Z.signal);continue}}if(!aW(X))throw X;let G=sW(X)??Q*Math.pow(2,J),V=X instanceof Error?X.message:String(X);Z.onRetry?.(J+1,G,V),await d3(G,Z.signal)}throw z}function nW($){if(!($ instanceof Error))return!1;return $.status===401}function aW($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&rW.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 sW($){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 d3($,Z){return new Promise((Y,Q)=>{let z=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(z),Q(Error("Aborted"))},{once:!0})})}var tW={haiku:200000,sonnet:200000,opus:200000};function g1($){return Math.ceil($.length/3.5)}function dZ($){let Z=0;for(let Y of $){if(Z+=g1(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=g1(JSON.stringify(Q.input)),Z+=g1(Q.result);Z+=10}return Z}function cZ($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(tW))if(Z.includes(Y))return Q;return 200000}function l3($,Z,Y){let Q=cZ(Z)-20000-Y;if(dZ($)<=Q)return $;let J=[],X=Q,K=[...$].reverse(),G=[];for(let q of K){let U=g1(q.content)+(q.toolCalls?.reduce((H,B)=>H+g1(JSON.stringify(B.input))+g1(B.result),0)??0)+10;if(X-U<0)break;X-=U,G.unshift(q)}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 o3($,Z,Y){let Q=cZ(Z)-20000-Y;return dZ($)>Q*0.7}function i3($,Z,Y){let Q=cZ(Z)-20000-Y;if(dZ($)<=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 r3($){return`Summarize this conversation concisely. Focus on:
533
+ ${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 XX($,Z,Y,Q,z){let J=performance.now();try{let X=await EB($,Z,Y,Q,z);return setImmediate(()=>{jZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!X.startsWith("Error:")})}),X}catch(X){return setImmediate(()=>{jZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${X instanceof Error?X.message:String(X)}`}}async function EB($,Z,Y,Q,z){switch($){case"read_file":return a3(Z);case"write_file":return s3(Z,Y);case"edit_file":return t3(Z,Y);case"search_files":return await ZX(Z);case"find_files":return await YX(Z);case"list_directory":return QX(Z);case"run_command":return await zX(Z);case"fetch_url":return await JX(Z)}let J=await G3($,Z);if(J!==null)return J;let X=W3($,Z);if(X!==null)return X;let K=await D3($,Z);if(K!==null)return K;let G=await K3($,Z,z);if(G!==null)return G;let V=await h3($,Z);if(V!==null)return V;let U=Q.find((q)=>q.name===$);if(U)return await q7(U,Z);return`Error: unknown tool "${$}"`}var r$=new w6,GX=[];function nZ($){GX=$}var VX=null;function rZ($){VX=$}var KX=!1;function aZ(){if(KX)return;if(KX=!0,L)b.push(...i2),b.push(...D4),b.push(...I4);else b.push(S4);b.push(...u5),b.push(...m5),b.push(...p5),b.push(...d5),b.push(c5),b.push(...l5),b.push(...o5),b.push(...i5),b.push(...V7),b.push(...t5),b.push(...Z7),b.push(...n5),b.push(...r5),b.push(...a5),b.push(...e5),b.push(...s5),b.push(...$7),b.push(...U7),b.push(...wZ)}async function N7($,Z){return XX($,Z,r$,GX,VX)}var RB=new Set([429,500,502,503,529]);async function qX($,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(FB(X)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(J+1,500,"Auth refreshed, retrying..."),await UX(500,Z.signal);continue}}if(!LB(X))throw X;let G=jB(X)??Q*Math.pow(2,J),V=X instanceof Error?X.message:String(X);Z.onRetry?.(J+1,G,V),await UX(G,Z.signal)}throw z}function FB($){if(!($ instanceof Error))return!1;return $.status===401}function LB($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&RB.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 jB($){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 UX($,Z){return new Promise((Y,Q)=>{let z=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(z),Q(Error("Aborted"))},{once:!0})})}var PB={haiku:200000,sonnet:200000,opus:200000};function u1($){return Math.ceil($.length/3.5)}function sZ($){let Z=0;for(let Y of $){if(Z+=u1(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=u1(JSON.stringify(Q.input)),Z+=u1(Q.result);Z+=10}return Z}function tZ($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(PB))if(Z.includes(Y))return Q;return 200000}function HX($,Z,Y){let Q=tZ(Z)-20000-Y;if(sZ($)<=Q)return $;let J=[],X=Q,K=[...$].reverse(),G=[];for(let U of K){let q=u1(U.content)+(U.toolCalls?.reduce((H,B)=>H+u1(JSON.stringify(B.input))+u1(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 WX($,Z,Y){let Q=tZ(Z)-20000-Y;return sZ($)>Q*0.7}function BX($,Z,Y){let Q=tZ(Z)-20000-Y;if(sZ($)<=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 NX($){return`Summarize this conversation concisely. Focus on:
524
534
  1. Key decisions made
525
535
  2. Files created or modified
526
536
  3. Important context the user shared
@@ -532,32 +542,32 @@ Be brief but preserve actionable information. Output ONLY the summary.
532
542
  ${$.map((Y)=>{let Q=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)Q+=`
533
543
  Tools used: ${Y.toolCalls.map((z)=>z.name).join(", ")}`;return Q}).join(`
534
544
 
535
- `)}`}function n3($,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(`
536
- `),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 q=V.join(`
537
- `);return{...z,result:q}});return{...Y,toolCalls:Q}})}var eW=[/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 lZ($){for(let Z of eW)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var $B=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],ZB=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function a3($){return(process.platform==="win32"?$B:ZB).some((Y)=>Y.test($))}var YB=[/\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],QB=[/\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 s3($,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(a3(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),z=lZ(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(a3(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),z=lZ(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=lZ(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let z of YB)if(z.test(Y))return{level:"dangerous",reason:Y};for(let z of QB)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 oZ($){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: ${zB(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.
538
- Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${JB(Y)}" may not exist or be unavailable.
545
+ `)}`}function OX($,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(`
546
+ `),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(`
547
+ `);return{...z,result:U}});return{...Y,toolCalls:Q}})}var AB=[/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 eZ($){for(let Z of AB)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var TB=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],DB=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function MX($){return(process.platform==="win32"?TB:DB).some((Y)=>Y.test($))}var IB=[/\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],SB=[/\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 CX($,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(MX(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),z=eZ(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(MX(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),z=eZ(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=eZ(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let z of IB)if(z.test(Y))return{level:"dangerous",reason:Y};for(let z of SB)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 $9($){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: ${wB(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.
548
+ Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${kB(Y)}" may not exist or be unavailable.
539
549
  Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
540
- 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 zB($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function JB($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function t3($,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 e3($,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(`
550
+ 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 wB($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function kB($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function EX($,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 RX($,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(`
541
551
  `)[0]||"",z=Y.split(`
542
- `).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 $X($,Z,Y=20){let Q=$.split(`
552
+ `).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 FX($,Z,Y=20){let Q=$.split(`
543
553
  `),z=Z.split(`
544
- `),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 iZ{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new l0({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new l0({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=n3($),z=g1(Z);if(o3(Q,this.model,z)){let G=i3(Q,this.model,z);if(G)try{let q={role:"assistant",content:`[Conversation summary]
545
- ${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};Q=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},q,...G.toKeep]}catch{}}let J=l3(Q,this.model,z),X=XB(J),K=Y?b:void 0;try{yield*this.streamLoop(X,Z,K)}catch(G){yield{type:"error",error:oZ(G)}}}async generateSummary($){let Z=r3($),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 c3(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(q){yield{type:"error",error:oZ(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 G=K.content.filter((q)=>q.type==="tool_use");z.push({role:"assistant",content:K.content});let V=[];for(let q of G){let U=q.input,H=s3(q.name,U);if(H.level==="dangerous"){yield{type:"tool_blocked",id:q.id,name:q.name,reason:`Blocked dangerous operation: ${H.reason}`},V.push({type:"tool_result",tool_use_id:q.id,content:`Error: Operation blocked for safety. Reason: ${H.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&t3(this.approvalMode,q.name,H.level)&&this.approvalCallback){if(yield{type:"tool_call",id:q.id,name:q.name,input:q.input},!await this.approvalCallback(q.name,U,H.level)){yield{type:"tool_blocked",id:q.id,name:q.name,reason:"Rejected by user"},V.push({type:"tool_result",tool_use_id:q.id,content:"Error: User rejected this operation."});continue}let C=await U7(q.name,U);yield{type:"tool_result",id:q.id,name:q.name,result:C},V.push({type:"tool_result",tool_use_id:q.id,content:C});continue}yield{type:"tool_call",id:q.id,name:q.name,input:q.input};let B=await U7(q.name,U);yield{type:"tool_result",id:q.id,name:q.name,result:B},V.push({type:"tool_result",tool_use_id:q.id,content:B})}z.push({role:"user",content:V})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function XB($){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 rZ{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 q=await z.text();yield{type:"error",error:`${this.name} API error ${z.status}: ${q.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((q,U)=>q+U.content.length,0),V=0;while(!0){let{done:q,value:U}=await J.read();if(q)break;K+=X.decode(U,{stream:!0});let H=K.split(`
546
- `);K=H.pop()||"";for(let B of H){if(!B.startsWith("data: "))continue;let N=B.slice(6).trim();if(N==="[DONE]")continue;try{let M=JSON.parse(N).choices?.[0]?.delta;if(M?.content)yield{type:"text",text:M.content},V+=M.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 H7($){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 KB={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 ZX(){let $=["Providers:"];for(let[Z,Y]of Object.entries(KB)){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(`
547
- `)}function YX($,Z,Y,Q){let{provider:z,model:J}=H7(Z);if(z==="openai"||z==="ollama")return new rZ(z,J,Y);let X=new iZ($.auth.token,Z,Y,Q);return X.setAuthRefresh(()=>{let K=l1();if(K&&K.token!==$.auth.token)return $.auth=K,X.updateToken(K.token),!0;return!1}),X}u();import{existsSync as j0,mkdirSync as QX,readdirSync as zX,readFileSync as E8,unlinkSync as JX,renameSync as nZ}from"fs";import{join as e}from"path";class aZ{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=e($,"sessions"),this.archiveDir=e($,"sessions","archive"),!j0(this.sessionsDir))QX(this.sessionsDir,{recursive:!0});if(!j0(this.archiveDir))QX(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(!j0(this.sessionsDir))return[];return zX(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=e(this.sessionsDir,`${$}.json`);if(!j0(Z))return null;try{let Y=JSON.parse(E8(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=e(this.sessionsDir,`${$}.json`);if(j0(Z))return JX(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 A(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=e(this.sessionsDir,`${$}.json`);if(!j0(Z))return!1;let Y=e(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=e(this.archiveDir,`${$}.json`);if(!j0(Z))return!1;let Y=e(this.sessionsDir,`${$}.json`);return nZ(Z,Y),!0}listArchived(){if(!j0(this.archiveDir))return[];return zX(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=e(this.archiveDir,`${$}.json`);if(!j0(Z))return null;try{let Y=JSON.parse(E8(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=e(this.archiveDir,`${$}.json`);if(j0(Z))return JX(Z),!0;return!1}loadOrCreate($){let Z=e(this.sessionsDir,`${$}.json`);if(j0(Z))try{return JSON.parse(E8(Z,"utf-8"))}catch{let Q=e(this.sessionsDir,`${$}.corrupt.json`);try{nZ(Z,Q)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return A(Z,JSON.stringify(Y,null,2)),Y}saveLastSession(){let $=e(this.sessionsDir,"..","last-session.txt");A($,this.current.name)}getLastSession(){let $=e(this.sessionsDir,"..","last-session.txt");if(!j0($))return null;try{let Z=E8($,"utf-8").trim();if(!Z||!j0(e(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}getSession($){let Z=e(this.sessionsDir,`${$}.json`);if(!j0(Z))return null;try{return JSON.parse(E8(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(A(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 A(Q,JSON.stringify(Y,null,2)),Y}save(){let $=e(this.sessionsDir,`${this.current.name}.json`);A($,JSON.stringify(this.current,null,2))}}import{existsSync as GX,readdirSync as UB,readFileSync as VX}from"fs";import{join as tZ}from"path";n();import{existsSync as sZ,readFileSync as XX}from"fs";import{basename as GB,join as W7}from"path";function KX(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${YY()}`),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=VB($);if(Y)Z.push(`Project: ${Y}`);let Q=qB($);if(Q)Z.push(Q);return Z.join(`
548
- `)}function VB($){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(sZ(W7($,z)))Y.push(J);if(Y.length===0)return null;let Q=GB($);try{let z=W7($,"package.json");if(sZ(z)){let J=JSON.parse(XX(z,"utf-8"));if(J.name)Q=J.name}}catch(z){g.debug("Failed to parse package.json for project name",{error:z})}return`Project: ${Q} (${Y.join(", ")})`}function qB($){if(!sZ(W7($,".git")))return null;let Z=[];try{let Y=XX(W7($,".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(`
549
- `)}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){g.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(`
554
+ `),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 Z9{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new o0({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new o0({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=OX($),z=u1(Z);if(WX(Q,this.model,z)){let G=BX(Q,this.model,z);if(G)try{let U={role:"assistant",content:`[Conversation summary]
555
+ ${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=HX(Q,this.model,z),X=fB(J),K=Y?b:void 0;try{yield*this.streamLoop(X,Z,K)}catch(G){yield{type:"error",error:$9(G)}}}async generateSummary($){let Z=NX($),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 qX(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:$9(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=CX(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&&EX(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 N7(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 N7(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 fB($){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 Y9{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(`
556
+ `);K=H.pop()||"";for(let B of H){if(!B.startsWith("data: "))continue;let N=B.slice(6).trim();if(N==="[DONE]")continue;try{let C=JSON.parse(N).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 O7($){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 bB={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 LX(){let $=["Providers:"];for(let[Z,Y]of Object.entries(bB)){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(`
557
+ `)}function jX($,Z,Y,Q){let{provider:z,model:J}=O7(Z);if(z==="openai"||z==="ollama")return new Y9(z,J,Y);let X=new Z9($.auth.token,Z,Y,Q);return X.setAuthRefresh(()=>{let K=o1();if(K&&K.token!==$.auth.token)return $.auth=K,X.updateToken(K.token),!0;return!1}),X}u();import{existsSync as P0,mkdirSync as PX,readdirSync as AX,readFileSync as F8,unlinkSync as TX,renameSync as Q9}from"fs";import{join as $0}from"path";class z9{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=$0($,"sessions"),this.archiveDir=$0($,"sessions","archive"),!P0(this.sessionsDir))PX(this.sessionsDir,{recursive:!0});if(!P0(this.archiveDir))PX(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(!P0(this.sessionsDir))return[];return AX(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=$0(this.sessionsDir,`${$}.json`);if(!P0(Z))return null;try{let Y=JSON.parse(F8(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=$0(this.sessionsDir,`${$}.json`);if(P0(Z))return TX(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=$0(this.sessionsDir,`${$}.json`);return P(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=$0(this.sessionsDir,`${$}.json`);if(!P0(Z))return!1;let Y=$0(this.archiveDir,`${$}.json`);return Q9(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=$0(this.archiveDir,`${$}.json`);if(!P0(Z))return!1;let Y=$0(this.sessionsDir,`${$}.json`);return Q9(Z,Y),!0}listArchived(){if(!P0(this.archiveDir))return[];return AX(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=$0(this.archiveDir,`${$}.json`);if(!P0(Z))return null;try{let Y=JSON.parse(F8(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=$0(this.archiveDir,`${$}.json`);if(P0(Z))return TX(Z),!0;return!1}loadOrCreate($){let Z=$0(this.sessionsDir,`${$}.json`);if(P0(Z))try{return JSON.parse(F8(Z,"utf-8"))}catch{let Q=$0(this.sessionsDir,`${$}.corrupt.json`);try{Q9(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 $=$0(this.sessionsDir,"..","last-session.txt");P($,this.current.name)}getLastSession(){let $=$0(this.sessionsDir,"..","last-session.txt");if(!P0($))return null;try{let Z=F8($,"utf-8").trim();if(!Z||!P0($0(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}getSession($){let Z=$0(this.sessionsDir,`${$}.json`);if(!P0(Z))return null;try{return JSON.parse(F8(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=$0(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=$0(this.sessionsDir,`${$}.json`);return P(Q,JSON.stringify(Y,null,2)),Y}save(){let $=$0(this.sessionsDir,`${this.current.name}.json`);P($,JSON.stringify(this.current,null,2))}}import{existsSync as SX,readdirSync as vB,readFileSync as wX}from"fs";import{join as X9}from"path";a();import{existsSync as J9,readFileSync as DX}from"fs";import{basename as yB,join as M7}from"path";function IX(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${UY()}`),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=_B($);if(Y)Z.push(`Project: ${Y}`);let Q=xB($);if(Q)Z.push(Q);return Z.join(`
558
+ `)}function _B($){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(J9(M7($,z)))Y.push(J);if(Y.length===0)return null;let Q=yB($);try{let z=M7($,"package.json");if(J9(z)){let J=JSON.parse(DX(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 xB($){if(!J9(M7($,".git")))return null;let Z=[];try{let Y=DX(M7($,".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(`
559
+ `)}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(`
550
560
  `),J=z.slice(0,15);if(z.length>15)J.push(`... and ${z.length-15} more files`);Z.push(`Uncommitted changes:
551
561
  `+J.join(`
552
- `))}}}catch(Y){g.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(`
562
+ `))}}}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(`
553
563
  `).slice(0,10);Z.push(`Staged:
554
564
  `+z.join(`
555
- `))}}}catch(Y){g.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
556
- `):null}function qX($,Z){if(!GX($))return[];let Y=[],Q=UB($,{withFileTypes:!0});for(let z of Q)if(z.isFile()&&z.name.endsWith(".md")){let J=VX(tZ($,z.name),"utf-8");Y.push({name:z.name.replace(".md",""),content:J.trim(),source:Z})}else if(z.isDirectory()){let J=tZ($,z.name,"SKILL.md");if(GX(J)){let X=VX(J,"utf-8");Y.push({name:z.name,content:X.trim(),source:Z})}}return Y}function UX($){let Z=qX($,"global"),Y=tZ(process.cwd(),".smolerclaw","skills"),Q=qX(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 HX($){if($.length===0)return"No skills loaded.";return`Skills:
565
+ `))}}}catch(Y){m.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
566
+ `):null}function kX($,Z){if(!SX($))return[];let Y=[],Q=vB($,{withFileTypes:!0});for(let z of Q)if(z.isFile()&&z.name.endsWith(".md")){let J=wX(X9($,z.name),"utf-8");Y.push({name:z.name.replace(".md",""),content:J.trim(),source:Z})}else if(z.isDirectory()){let J=X9($,z.name,"SKILL.md");if(SX(J)){let X=wX(J,"utf-8");Y.push({name:z.name,content:X.trim(),source:Z})}}return Y}function fX($){let Z=kX($,"global"),Y=X9(process.cwd(),".smolerclaw","skills"),Q=kX(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 bX($){if($.length===0)return"No skills loaded.";return`Skills:
557
567
  `+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
558
- `)}function B7($,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
559
- ALWAYS respond in ${J}. This is a hard requirement.`)}if(N1())Q.push(`---
560
- `+J3());if(Q.push(`---
568
+ `)}function C7($,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
569
+ ALWAYS respond in ${J}. This is a hard requirement.`)}if(O1())Q.push(`---
570
+ `+T3());if(Q.push(`---
561
571
  ## Meta-Learning & Self-Awareness
562
572
  You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
563
573
 
@@ -577,102 +587,102 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
577
587
  ## Environment
578
588
  The user's current working directory and project info. Use this context when they ask about code or files.
579
589
 
580
- `+KX()),$)Q.push(`## User Instructions
590
+ `+IX()),$)Q.push(`## User Instructions
581
591
  `+$);return Q.join(`
582
592
 
583
- `)}async function WX($,Z,Y){let Q=new aZ($.dataDir),z=Z||Q.getLastSession()||"default";if(z!=="default")Q.switchTo(z);let J=UX($.skillsDir),X=B7($.systemPrompt,J,$.language),K=!Y;pZ();let G=W3(i7()),V=o$(G);if(V.length>0)uZ(V),b.push(...i$(V));await N3(G,$.dataDir);let q=O3(),U=new Set(b.map((N)=>N.name));for(let N of q)if(!U.has(N.name))b.push(N);let H=Tz(),B=H?`${X}
593
+ `)}async function yX($,Z,Y){let Q=new z9($.dataDir),z=Z||Q.getLastSession()||"default";if(z!=="default")Q.switchTo(z);let J=fX($.skillsDir),X=C7($.systemPrompt,J,$.language),K=!Y;aZ();let G=y3(s7()),V=i$(G);if(V.length>0)nZ(V),b.push(...n$(V));await x3(G,$.dataDir);let U=v3(),q=new Set(b.map((N)=>N.name));for(let N of U)if(!q.has(N.name))b.push(N);let H=_z(),B=H?`${X}
584
594
 
585
- ${H}`:X;return{sessions:Q,sessionName:z,skills:J,systemPrompt:X,activeSystemPrompt:B,enableTools:K,plugins:V}}async function BX($,Z,Y,Q,z,J){let X=z||"";if(J){let q=await HB();X=X?`${X}
595
+ ${H}`:X;return{sessions:Q,sessionName:z,skills:J,systemPrompt:X,activeSystemPrompt:B,enableTools:K,plugins:V}}async function _X($,Z,Y,Q,z,J){let X=z||"";if(J){let U=await hB();X=X?`${X}
586
596
 
587
- ${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 G="";for await(let q of $.chat(Z.messages,Y,Q))if(q.type==="text")process.stdout.write(q.text),G+=q.text;else if(q.type==="error")console.error(`
588
- smolerclaw error: ${q.error}`);if(G&&!G.endsWith(`
597
+ ${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(`
598
+ smolerclaw error: ${U.error}`);if(G&&!G.endsWith(`
589
599
  `))process.stdout.write(`
590
- `);let V={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(V)}async function HB(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var WB=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function n0($){return WB?"":$}var W={altOn:n0("\x1B[?1049h"),altOff:n0("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:n0("\x1B[1m"),dim:n0("\x1B[2m"),italic:n0("\x1B[3m"),underline:n0("\x1B[4m"),reset:n0("\x1B[0m"),inv:n0("\x1B[7m"),fg:($)=>n0(`\x1B[38;5;${$}m`),bg:($)=>n0(`\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)},BB={primary:W.fg(75),secondary:W.fg(39),accent:W.fg(220),muted:W.fg(245),header:W.fg(81)},NB={primary:W.fg(215),secondary:W.fg(220),accent:W.fg(196),muted:W.fg(245),header:W.fg(214)},OB={primary:W.fg(183),secondary:W.fg(157),accent:W.fg(147),muted:W.fg(242),header:W.fg(183)};function eZ($){switch($){case"productivity":return BB;case"spillover_alert":return NB;case"sharpen_or_relax":return OB}}function E($){process.stdout.write($)}var CB=/\x1b\[[0-9;]*[a-zA-Z]/g;function u1($){return $.replace(CB,"")}function MB($){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 N0($){let Z=u1($),Y=0;for(let Q of Z)Y+=MB(Q);return Y}function m1($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
591
- `)){if(N0(Q)<=Z){Y.push(Q);continue}let X=u1(Q).split(" "),K=[],G="";for(let q of X)if(G.length+(G?1:0)+q.length>Z&&G)K.push(G),G=" "+q;else G+=(G?" ":"")+q;if(G)K.push(G);let V=EB(Q);for(let q=0;q<K.length;q++)if(V&&q===0)K[q]=V+K[q]+W.reset;else if(V)K[q]=V+K[q]+W.reset;Y.push(...K)}return Y}function EB($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function N7($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
592
- `),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,N=V[2],C=B===1?"\u2501":B===2?"\u2500":"\xB7";z.push(` ${I.heading}${W.bold}${C} ${R8(N)}${W.reset}`);continue}if(G.trimStart().startsWith(">")){let B=G.replace(/^\s*>\s?/,"");$9(z,` ${I.quote}\u2502 ${R8(B)}${W.reset}`,Y);continue}let q=G.match(/^(\s*)([-*+])\s+(.+)/);if(q){let B=Math.floor(q[1].length/2),N=q[3],C=" ".repeat(B);$9(z,` ${C}${W.dim}\u2022${W.reset} ${R8(N)}`,Y);continue}let U=G.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(U){let B=Math.floor(U[1].length/2),N=U[2],C=U[3],M=" ".repeat(B);$9(z,` ${M}${W.dim}${N}.${W.reset} ${R8(C)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(G.trim())){z.push(` ${W.dim}${"\u2500".repeat(40)}${W.reset}`);continue}let H=` ${R8(G)}`;if(N0(H)>Y)for(let B of m1(H,Y))z.push(B);else z.push(H)}if(J)z.push(` ${W.dim}\u2514${"\u2500".repeat(42)}${W.reset}`);return z}function $9($,Z,Y){if(N0(Z)>Y)for(let Q of m1(Z,Y))$.push(Q);else $.push(Z)}function R8($){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 RB,readFileSync as FB,writeFileSync as LB}from"fs";var Z9=500;class Y9{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>Z9)this.entries=this.entries.slice(-Z9);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(RB(this.filePath)){let $=FB(this.filePath,"utf-8");this.entries=$.split(`
593
- `).filter(Boolean).slice(-Z9)}}catch{}}save(){try{LB(this.filePath,this.entries.join(`
600
+ `);let V={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(V)}async function hB(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var gB=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function a0($){return gB?"":$}var W={altOn:a0("\x1B[?1049h"),altOff:a0("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:a0("\x1B[1m"),dim:a0("\x1B[2m"),italic:a0("\x1B[3m"),underline:a0("\x1B[4m"),reset:a0("\x1B[0m"),inv:a0("\x1B[7m"),fg:($)=>a0(`\x1B[38;5;${$}m`),bg:($)=>a0(`\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)},uB={primary:W.fg(75),secondary:W.fg(39),accent:W.fg(220),muted:W.fg(245),header:W.fg(81)},mB={primary:W.fg(215),secondary:W.fg(220),accent:W.fg(196),muted:W.fg(245),header:W.fg(214)},pB={primary:W.fg(183),secondary:W.fg(157),accent:W.fg(147),muted:W.fg(242),header:W.fg(183)};function K9($){switch($){case"productivity":return uB;case"spillover_alert":return mB;case"sharpen_or_relax":return pB}}function E($){process.stdout.write($)}var dB=/\x1b\[[0-9;]*[a-zA-Z]/g;function m1($){return $.replace(dB,"")}function cB($){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 O0($){let Z=m1($),Y=0;for(let Q of Z)Y+=cB(Q);return Y}function p1($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
601
+ `)){if(O0(Q)<=Z){Y.push(Q);continue}let X=m1(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=lB(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 lB($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function E7($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
602
+ `),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,N=V[2],M=B===1?"\u2501":B===2?"\u2500":"\xB7";z.push(` ${I.heading}${W.bold}${M} ${L8(N)}${W.reset}`);continue}if(G.trimStart().startsWith(">")){let B=G.replace(/^\s*>\s?/,"");G9(z,` ${I.quote}\u2502 ${L8(B)}${W.reset}`,Y);continue}let U=G.match(/^(\s*)([-*+])\s+(.+)/);if(U){let B=Math.floor(U[1].length/2),N=U[3],M=" ".repeat(B);G9(z,` ${M}${W.dim}\u2022${W.reset} ${L8(N)}`,Y);continue}let q=G.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(q){let B=Math.floor(q[1].length/2),N=q[2],M=q[3],C=" ".repeat(B);G9(z,` ${C}${W.dim}${N}.${W.reset} ${L8(M)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(G.trim())){z.push(` ${W.dim}${"\u2500".repeat(40)}${W.reset}`);continue}let H=` ${L8(G)}`;if(O0(H)>Y)for(let B of p1(H,Y))z.push(B);else z.push(H)}if(J)z.push(` ${W.dim}\u2514${"\u2500".repeat(42)}${W.reset}`);return z}function G9($,Z,Y){if(O0(Z)>Y)for(let Q of p1(Z,Y))$.push(Q);else $.push(Z)}function L8($){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 oB,readFileSync as iB,writeFileSync as nB}from"fs";var V9=500;class U9{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>V9)this.entries=this.entries.slice(-V9);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(oB(this.filePath)){let $=iB(this.filePath,"utf-8");this.entries=$.split(`
603
+ `).filter(Boolean).slice(-V9)}}catch{}}save(){try{nB(this.filePath,this.entries.join(`
594
604
  `)+`
595
- `)}catch{}}}import{join as hB}from"path";var jB=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],PB=" ";function Q9($,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=_B($,Y),G=z-Q||1,q=K.map((H)=>{if(H===0&&Q===0)return PB;let B=(H-Q)/G,N=Math.min(7,Math.floor(B*8));return jB[N]}).join(""),U=J?`${J}${q}${W.reset}`:q;if(X)return`${W.dim}${Q.toFixed(0)}${W.reset}${U}${W.dim}${z.toFixed(0)}${W.reset}`;return U}var AB="\u2588",DB="\u2589",TB="\u258A",IB="\u258B",SB="\u258C",wB="\u258D",kB="\u258E",fB="\u258F",bB="\u2591",yB=[" ",fB,kB,wB,SB,IB,TB,DB];function z9($,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,q=Math.floor(V*8),U=AB.repeat(G);if(q>0&&G<Y)U+=yB[q];let H=Y-N0(U);U+=bB.repeat(Math.max(0,H));let B=J?`${J}${U}${W.reset}`:U,N=[];if(X)N.push(`${W.dim}${X.padEnd(12)}${W.reset}`);if(N.push(B),z)N.push(` ${W.dim}${$.toFixed(1)}%${W.reset}`);return N.join("")}function F8($,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}${NX(X)}/${NX(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=N0(Q),J=Math.max(0,Z-z-2);return`${W.inv} ${Q}${" ".repeat(J)} ${W.reset}`}function J9($,Z=40){let Y=[];Y.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),Y.push(`${I.heading}${W.bold} System${W.reset}`);let Q=Q9($.cpu,{width:15,color:W.fg(75)}),z=z9($.currentCpu,{width:10,showValue:!1,color:W.fg(75)});Y.push(` ${W.dim}CPU:${W.reset} ${Q} ${z} ${$.currentCpu.toFixed(0)}%`);let J=Q9($.memory,{width:15,color:W.fg(114)}),X=z9($.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 _B($,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,q)=>V+q,0)/K.length;Q.push(G)}return Q}function NX($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function L8($,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 q=N0(Q),U=2,H=Math.max(1,Z-q-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 q of $){let U=N0(q)>K?m1(q,K):[q];for(let H of U){let B=N0(H),N=Math.max(0,K-B);G.push(`${J}\u2502${W.reset}${V}${H}${" ".repeat(N)}${V}${J}\u2502${W.reset}`)}}return G.push(`${J}\u2514${"\u2500".repeat(Z-2)}\u2518${W.reset}`),G}function X9($,Z,Y,Q,z={}){let J=L8($,Q,z);for(let X=0;X<J.length;X++)E(W.to(Z+X,Y)),E(J[X])}var O7={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},xB={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function K9($,Z={}){let{width:Y=60,showActions:Q=!0,compact:z=!1}=Z,J=[],X=xB[$.category]||"\uD83D\uDCA1",K=O7.dimYellow+O7.italic;if(z){let q=$.title.length>Y-10?$.title.slice(0,Y-13)+"...":$.title;return J.push(` ${K}${X} ${q}${W.reset}`),J}J.push(` ${K}${X} ${$.title}${W.reset}`);let G=Y-6,V=m1($.explanation,G);for(let q of V)J.push(` ${K} ${u1(q)}${W.reset}`);if($.suggestedAction)J.push(` ${O7.dimCyan} \u2192 ${$.suggestedAction.label}${W.reset}`);if(Q)J.push(` ${W.dim} [Y] Aceitar [N] Ignorar${W.reset}`);return J}function OX($,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} ${O7.dimYellow}${V}${W.reset}`);let q=Z-4,U=J.description.length>q?J.description.slice(0,q-3)+"...":J.description;Y.push(` ${W.dim}${U}${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 C7($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:OX($,Z)}}class j8{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(F8(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],q=V.row??X,U=V.col??K,H=V.width??J,B=V.height??Math.floor(z/Math.ceil($.length/Z));if(this.drawDashboardPanel(V,q,U,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);X9(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:J9($,35)}],columns:1,gap:1}}}function M7($,Z){E(`\x1B[${$};${Z}r`)}function E7(){E("\x1B[r")}var vB=new j8;d0();class G9{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=eZ("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","/macro","/macros","/atalho","/atalhos","/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"],"/macro":["list","all","info","create","delete","enable","disable"],"/macros":["list","all","info","create","delete","enable","disable"],"/atalho":["list","all","info","criar","deletar","ativar","desativar"],"/atalhos":["list","all","info","criar","deletar","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 j8}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 Y9(hB(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=N7(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=N7(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(`
605
+ `)}catch{}}}import{join as UN}from"path";var rB=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],aB=" ";function q9($,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=KN($,Y),G=z-Q||1,U=K.map((H)=>{if(H===0&&Q===0)return aB;let B=(H-Q)/G,N=Math.min(7,Math.floor(B*8));return rB[N]}).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 sB="\u2588",tB="\u2589",eB="\u258A",$N="\u258B",ZN="\u258C",YN="\u258D",QN="\u258E",zN="\u258F",JN="\u2591",XN=[" ",zN,QN,YN,ZN,$N,eB,tB];function H9($,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=sB.repeat(G);if(U>0&&G<Y)q+=XN[U];let H=Y-O0(q);q+=JN.repeat(Math.max(0,H));let B=J?`${J}${q}${W.reset}`:q,N=[];if(X)N.push(`${W.dim}${X.padEnd(12)}${W.reset}`);if(N.push(B),z)N.push(` ${W.dim}${$.toFixed(1)}%${W.reset}`);return N.join("")}function j8($,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}${xX(X)}/${xX(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=O0(Q),J=Math.max(0,Z-z-2);return`${W.inv} ${Q}${" ".repeat(J)} ${W.reset}`}function W9($,Z=40){let Y=[];Y.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),Y.push(`${I.heading}${W.bold} System${W.reset}`);let Q=q9($.cpu,{width:15,color:W.fg(75)}),z=H9($.currentCpu,{width:10,showValue:!1,color:W.fg(75)});Y.push(` ${W.dim}CPU:${W.reset} ${Q} ${z} ${$.currentCpu.toFixed(0)}%`);let J=q9($.memory,{width:15,color:W.fg(114)}),X=H9($.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 KN($,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 xX($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function P8($,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=O0(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=O0(U)>K?p1(U,K):[U];for(let H of q){let B=O0(H),N=Math.max(0,K-B);G.push(`${J}\u2502${W.reset}${V}${H}${" ".repeat(N)}${V}${J}\u2502${W.reset}`)}}return G.push(`${J}\u2514${"\u2500".repeat(Z-2)}\u2518${W.reset}`),G}function B9($,Z,Y,Q,z={}){let J=P8($,Q,z);for(let X=0;X<J.length;X++)E(W.to(Z+X,Y)),E(J[X])}var R7={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},GN={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function N9($,Z={}){let{width:Y=60,showActions:Q=!0,compact:z=!1}=Z,J=[],X=GN[$.category]||"\uD83D\uDCA1",K=R7.dimYellow+R7.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=p1($.explanation,G);for(let U of V)J.push(` ${K} ${m1(U)}${W.reset}`);if($.suggestedAction)J.push(` ${R7.dimCyan} \u2192 ${$.suggestedAction.label}${W.reset}`);if(Q)J.push(` ${W.dim} [Y] Aceitar [N] Ignorar${W.reset}`);return J}function vX($,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} ${R7.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 F7($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:vX($,Z)}}class A8{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(j8(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);B9(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:W9($,35)}],columns:1,gap:1}}}function L7($,Z){E(`\x1B[${$};${Z}r`)}function j7(){E("\x1B[r")}var VN=new A8;c0();class O9{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=K9("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","/macro","/macros","/atalho","/atalhos","/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"],"/macro":["list","all","info","create","delete","enable","disable"],"/macros":["list","all","info","create","delete","enable","disable"],"/atalho":["list","all","info","criar","deletar","ativar","desativar"],"/atalhos":["list","all","info","criar","deletar","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 A8}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 U9(UN(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(e.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(e.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(e.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(e.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(e.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(e.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=E7(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=E7(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(`
596
606
  `),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===`
597
- `)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((q)=>q.name.toLowerCase().includes(V))},X=()=>{let U=this.height-2-2,H=J();if(Y>=H.length)Y=Math.max(0,H.length-1);let B=2,N=2,C=U-B-N,M=Math.max(1,C),F=0;if(H.length>M)F=Math.max(0,Y-Math.floor(M/2)),F=Math.min(F,H.length-M);let w=H.slice(F,F+M);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 k=0;k<M;k++){let h=2+B+k+1;if(E(W.to(h,1)),E(W.clearLine),k>=w.length)continue;let Y0=w[k],q0=F+k===Y,c=Y0.isCurrent?"*":" ",U0=Y0.isArchived?`${W.dim}[arch] ${W.reset}`:" ",g0=`${Y0.messageCount} msgs`.padEnd(10),P0=uB(Y0.updated);if(q0)E(` ${I.prompt}${W.bold}\u203A ${c} ${U0}${I.prompt}${W.bold}${Y0.name.padEnd(20)}${W.reset} ${W.dim}${g0} ${P0}${W.reset}`);else{let M0=Y0.isArchived?W.dim:I.sys;E(` ${c} ${U0}${M0}${Y0.name.padEnd(20)}${W.reset} ${W.dim}${g0} ${P0}${W.reset}`)}}for(let k=w.length;k<M;k++){let h=2+B+k+1;E(W.to(h,1)),E(W.clearLine)}let d=2+B+M+1;if(E(W.to(d,1)),E(W.clearLine),H.length>M){let k=Math.round((Y+1)/H.length*100);E(` ${W.dim}${F>0?"\u2191":" "} ${k}% ${F+M<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 q=V.toString("utf-8"),U=J();if(q==="\x1B"&&V.length===1){if(z)z=!1,Q="",X();else K(null);return}if(q==="\x03"){K(null);return}if(q==="\r"||q===`
598
- `){if(U.length>0&&Y<U.length)K({action:"load",name:U[Y].name});return}if(q==="\x1B[A"||q==="w"&&!z){if(Y>0)Y--,X();return}if(q==="\x1B[B"||q==="s"&&!z){if(Y<U.length-1)Y++,X();return}if(q==="d"&&z===!1){if(U.length>0&&Y<U.length){let H=U[Y];if(!H.isCurrent)K({action:"delete",name:H.name,isArchived:H.isArchived})}return}if(q==="a"&&z===!1){if(U.length>0&&Y<U.length){let H=U[Y];if(!H.isCurrent){let B=H.isArchived?"unarchive":"archive";K({action:B,name:H.name})}}return}if(q==="/"&&z===!1){z=!0,Q="",X();return}if(z){if(q==="\x7F"||q==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,X();else z=!1,X();return}if(q.length===1&&q>=" "){Q+=q,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((N)=>N.title.toLowerCase().includes(B)||N.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 N=this.height-2-2,C=K();if(Y>=C.length)Y=Math.max(0,C.length-1);let M=2,F=2,w=N-M-F,d=Math.max(1,w),D=0;if(C.length>d)D=Math.max(0,Y-Math.floor(d/2)),D=Math.min(D,C.length-d);let k=C.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 y=J?G(J):"Todas";E(` ${I.heading}${W.bold}Noticias${W.reset} ${W.dim}(${C.length}) ${y}${W.reset}`)}E(W.to(4,1)),E(W.clearLine);for(let y=0;y<d;y++){let q0=2+M+y+1;if(E(W.to(q0,1)),E(W.clearLine),y>=k.length)continue;let c=k[y],U0=D+y===Y,g0=c.time?`[${c.time}]`:" ",P0=this.width-30,M0=c.title.length>P0?c.title.slice(0,P0-1)+"\u2026":c.title;if(U0)E(` ${I.prompt}${W.bold}\u203A ${g0} ${M0}${W.reset} ${W.dim}(${c.source})${W.reset}`);else E(` ${W.dim}${g0}${W.reset} ${I.sys}${M0}${W.reset} ${W.dim}(${c.source})${W.reset}`)}for(let y=k.length;y<d;y++){let q0=2+M+y+1;E(W.to(q0,1)),E(W.clearLine)}let h=2+M+d+1;if(E(W.to(h,1)),E(W.clearLine),C.length>d){let y=Math.round((Y+1)/C.length*100);E(` ${W.dim}${D>0?"\u2191":" "} ${y}% ${D+d<C.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}`)},q=(H)=>{this.pickerActive=!1,process.stdin.removeListener("data",U),this.renderAll(),Z(H)},U=(H)=>{let B=H.toString("utf-8"),N=K();if(B==="\x1B"&&H.length===1){if(z)z=!1,Q="",V();else q(null);return}if(B==="\x03"){q(null);return}if(B===`
599
- `||B==="\x1B\r"||B==="\x1BOM"){if(N.length>0&&Y<N.length)q({action:"read",link:N[Y].link});return}if(B==="\r"||B===`
600
- `){if(N.length>0&&Y<N.length)q({action:"open",link:N[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<N.length-1)Y++,V();return}if(B==="\t"){if(!J)J=X[0]||"";else{let C=X.indexOf(J);J=C<X.length-1?X[C+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",U),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(`
601
- `))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(),E7(),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=C7(this.metaLearningEntries,Q);Z=[...Z,z]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),M7(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=K9($,{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=C7($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=eZ($),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 q=0;q<J;q++)for(let U=0;U<z&&V<Q.length;U++){let H=Q[V],B=$+X+q*(G+X)+1,N=X+U*(K+X)+1;this.drawDashboardPanel(H,B,N,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=L8($.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=F8($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${u1(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-N0(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=N0(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=N0(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")&&!EX(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===`
607
+ `)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,N=2,M=q-B-N,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 Q0=k[f],q0=F+f===Y,l=Q0.isCurrent?"*":" ",H0=Q0.isArchived?`${W.dim}[arch] ${W.reset}`:" ",u0=`${Q0.messageCount} msgs`.padEnd(10),A0=HN(Q0.updated);if(q0)E(` ${I.prompt}${W.bold}\u203A ${l} ${H0}${I.prompt}${W.bold}${Q0.name.padEnd(20)}${W.reset} ${W.dim}${u0} ${A0}${W.reset}`);else{let E0=Q0.isArchived?W.dim:I.sys;E(` ${l} ${H0}${E0}${Q0.name.padEnd(20)}${W.reset} ${W.dim}${u0} ${A0}${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 c=2+B+C+1;if(E(W.to(c,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 T=this.height-2;E(W.to(T,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===`
608
+ `){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((N)=>N.title.toLowerCase().includes(B)||N.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 N=this.height-2-2,M=K();if(Y>=M.length)Y=Math.max(0,M.length-1);let C=2,F=2,k=N-C-F,c=Math.max(1,k),T=0;if(M.length>c)T=Math.max(0,Y-Math.floor(c/2)),T=Math.min(T,M.length-c);let f=M.slice(T,T+c);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;_<c;_++){let q0=2+C+_+1;if(E(W.to(q0,1)),E(W.clearLine),_>=f.length)continue;let l=f[_],H0=T+_===Y,u0=l.time?`[${l.time}]`:" ",A0=this.width-30,E0=l.title.length>A0?l.title.slice(0,A0-1)+"\u2026":l.title;if(H0)E(` ${I.prompt}${W.bold}\u203A ${u0} ${E0}${W.reset} ${W.dim}(${l.source})${W.reset}`);else E(` ${W.dim}${u0}${W.reset} ${I.sys}${E0}${W.reset} ${W.dim}(${l.source})${W.reset}`)}for(let _=f.length;_<c;_++){let q0=2+C+_+1;E(W.to(q0,1)),E(W.clearLine)}let g=2+C+c+1;if(E(W.to(g,1)),E(W.clearLine),M.length>c){let _=Math.round((Y+1)/M.length*100);E(` ${W.dim}${T>0?"\u2191":" "} ${_}% ${T+c<M.length?"\u2193":" "}${W.reset}`)}let Q0=this.height-2;E(W.to(Q0,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"),N=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===`
609
+ `||B==="\x1B\r"||B==="\x1BOM"){if(N.length>0&&Y<N.length)U({action:"read",link:N[Y].link});return}if(B==="\r"||B===`
610
+ `){if(N.length>0&&Y<N.length)U({action:"open",link:N[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<N.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(`
611
+ `))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(),j7(),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=F7(this.metaLearningEntries,Q);Z=[...Z,z]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),L7(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=N9($,{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(e.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=F7($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=K9($),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,N=X+q*(K+X)+1;this.drawDashboardPanel(H,B,N,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=P8($.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=j8($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${m1(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-O0(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=O0(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=O0(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")&&!uX(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===`
602
612
  `){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
603
- `,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=CX(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-=CX(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=MX(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=MX(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.renderInput()}break}}return}if(gB(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")M7(3,this.height-2);else E7();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=m1(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=N7($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function EX($){return[...$].length===1}function gB($){if(!EX($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function CX($,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 MX($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function uB($){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 P8={"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}},mB={input:3,output:15};function RX($,Z){let Y=pB(Z),Q=$.inputTokens/1e6*Y.input*100,z=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:z,totalCostCents:Q+z}}function pB($){if(P8[$])return P8[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return P8["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return P8["claude-opus-4-20250514"];if(Z.includes("sonnet"))return P8["claude-sonnet-4-20250514"];return mB}class V9{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=RX($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=RX($,this.model);return`${R7($.inputTokens)} in / ${R7($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${R7(this.totalInput)} in / ${R7(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function R7($){return $.toLocaleString("en-US")}import{existsSync as FX,readFileSync as LX,statSync as jX}from"fs";import{basename as dB,extname as PX,resolve as AX}from"path";var DX=new Set([".png",".jpg",".jpeg",".gif",".webp"]),cB=20971520,lB=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"]),oB=1048576;function TX($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=PX(J).toLowerCase();if(DX.has(X)){let K=AX(J);if(FX(K))try{if(jX(K).size>cB){Q.push(`[image too large: ${J}]`);continue}let q=LX(K).toString("base64"),U=iB(X);Z.push({path:K,mediaType:U,base64:q}),Q.push(`[image: ${J}]`)}catch{Q.push(z)}else Q.push(z)}else Q.push(z)}return{text:Q.join(" "),images:Z}}function iB($){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 IX($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=PX(J).toLowerCase();if(DX.has(X)){Q.push(z);continue}if(!(lB.has(X)||(J.includes("/")||J.includes("\\"))&&X.length>0)){Q.push(z);continue}let G=AX(J);if(!FX(G)){Q.push(z);continue}try{let V=jX(G);if(!V.isFile()){Q.push(z);continue}if(V.size>oB){Q.push(`[file too large: ${J} (${(V.size/1024).toFixed(0)}KB)]`);continue}if(V.size===0){Q.push(`[empty file: ${J}]`);continue}let q=LX(G,"utf-8"),U=dB(G);Z.push({path:G,name:U,content:q,size:V.size}),Q.push(`[file: ${U}]`)}catch{Q.push(z)}}return{text:Q.join(" "),files:Z}}v1();import{existsSync as SX,readFileSync as rB}from"fs";import{join as wX}from"path";n();function nB(){let $=new Date().getDay();return $===0||$===6}function aB(){return nB()?"weekend":"weekday"}async function sB($){let Z=[],Y=[],Q=[],z=new Date,J=new Date(z);J.setHours(23,59,59,999);let X=wX($,"tasks.json");if(SX(X))try{let V=JSON.parse(rB(X,"utf-8"));for(let q of V){if(q.done)continue;if(q.dueAt){let U=new Date(q.dueAt),H=U<z,B=!H&&U<=J;if(H)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(V){g.debug("Failed to parse task for spillover check",{error:V})}let K=m$(!0);for(let V of K.slice(0,5)){let q=await tB(V);if(q)Q.push(q)}return{hasSpillover:Z.length>0||Y.length>0||Q.length>0,urgentTasks:Z,overdueTasks:Y,pendingCommits:Q}}async function tB($){if(!SX(wX($.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){g.debug("Git status check failed for project",{error:Z})}return null}function eB($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function A8($){let Z=aB(),Y=await sB($),Q=eB(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function $N($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
613
+ `,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=hX(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-=hX(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=gX(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=gX(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.renderInput()}break}}return}if(qN(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")L7(3,this.height-2);else j7();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=p1(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=E7($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function uX($){return[...$].length===1}function qN($){if(!uX($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function hX($,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 gX($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function HN($){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 T8={"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}},WN={input:3,output:15};function mX($,Z){let Y=BN(Z),Q=$.inputTokens/1e6*Y.input*100,z=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:z,totalCostCents:Q+z}}function BN($){if(T8[$])return T8[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return T8["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return T8["claude-opus-4-20250514"];if(Z.includes("sonnet"))return T8["claude-sonnet-4-20250514"];return WN}class M9{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=mX($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=mX($,this.model);return`${P7($.inputTokens)} in / ${P7($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${P7(this.totalInput)} in / ${P7(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function P7($){return $.toLocaleString("en-US")}import{existsSync as pX,readFileSync as dX,statSync as cX}from"fs";import{basename as NN,extname as lX,resolve as oX}from"path";var iX=new Set([".png",".jpg",".jpeg",".gif",".webp"]),ON=20971520,MN=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"]),CN=1048576;function nX($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=lX(J).toLowerCase();if(iX.has(X)){let K=oX(J);if(pX(K))try{if(cX(K).size>ON){Q.push(`[image too large: ${J}]`);continue}let U=dX(K).toString("base64"),q=EN(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 EN($){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 rX($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=lX(J).toLowerCase();if(iX.has(X)){Q.push(z);continue}if(!(MN.has(X)||(J.includes("/")||J.includes("\\"))&&X.length>0)){Q.push(z);continue}let G=oX(J);if(!pX(G)){Q.push(z);continue}try{let V=cX(G);if(!V.isFile()){Q.push(z);continue}if(V.size>CN){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=dX(G,"utf-8"),q=NN(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}}h1();import{existsSync as aX,readFileSync as RN}from"fs";import{join as sX}from"path";a();function FN(){let $=new Date().getDay();return $===0||$===6}function LN(){return FN()?"weekend":"weekday"}async function jN($){let Z=[],Y=[],Q=[],z=new Date,J=new Date(z);J.setHours(23,59,59,999);let X=sX($,"tasks.json");if(aX(X))try{let V=JSON.parse(RN(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=p$(!0);for(let V of K.slice(0,5)){let U=await PN(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 PN($){if(!aX(sX($.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 AN($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function D8($){let Z=LN(),Y=await jN($),Q=AN(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function TN($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
604
614
  Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${Y}
605
615
  \u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${Y}
606
- Modo: Sharpen or Relax`}}function ZN($){let Z=[];if($.overdueTasks.length>0){Z.push(`
616
+ Modo: Sharpen or Relax`}}function DN($){let Z=[];if($.overdueTasks.length>0){Z.push(`
607
617
  --- 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(`
608
618
  --- 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(`
609
619
  --- 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(`
610
- `)}function YN($){if($.persona!=="sharpen_or_relax")return"";return`
620
+ `)}function IN($){if($.persona!=="sharpen_or_relax")return"";return`
611
621
  --- Fim de Semana Livre ---
612
622
 
613
623
  [A] Amolar o Machado
614
624
  Estudo de arquitetura, refatoracao, melhoria do CLI
615
625
 
616
626
  [B] Descompressao Criativa
617
- Projetos paralelos sem prazo, foco pessoal/familia`}function QN($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
627
+ Projetos paralelos sem prazo, foco pessoal/familia`}function SN($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
618
628
  --- Sugestao: Timebox ---
619
629
  Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
620
- Depois: descanso merecido.`}async function kX($){let Z=[],Y=null;if($)Y=await A8($),Z.push($N(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await G$();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let J=ZN(Y);if(J)Z.push(J);let X=QN(Y);if(X)Z.push(X)}if(Y){let J=YN(Y);if(J)Z.push(J)}if(L)try{let J=await i0();Z.push(`
630
+ Depois: descanso merecido.`}async function tX($){let Z=[],Y=null;if($)Y=await D8($),Z.push(TN(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await V$();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let J=DN(Y);if(J)Z.push(J);let X=SN(Y);if(X)Z.push(X)}if(Y){let J=IN(Y);if(J)Z.push(J)}if(L)try{let J=await n0();Z.push(`
621
631
  --- Agenda ---
622
632
  ${J}`)}catch{Z.push(`
623
633
  --- Agenda ---
624
- Outlook nao disponivel.`)}if(L)try{let J=await K$();Z.push(`
634
+ Outlook nao disponivel.`)}if(L)try{let J=await G$();Z.push(`
625
635
  --- Sistema ---
626
- ${J}`)}catch(J){g.debug("System info unavailable for briefing",{error:J})}let z=Y?.persona==="sharpen_or_relax"?2:3;try{let J=await I1(["finance","business","tech"],z);Z.push(`
636
+ ${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 S1(["finance","business","tech"],z);Z.push(`
627
637
  ${J}`)}catch{Z.push(`
628
638
  --- Noticias ---
629
639
  Falha ao carregar noticias.`)}return Z.push(`
630
640
  ======================`),Z.join(`
631
- `)}n();p0();var v=null,F7=null,q9=null,U9=0;function yX($){q9=$}function _X($="foco",Z=25,Y=5){if(v)return`Pomodoro ja ativo: "${v.label}" (${hX()}). Use /pomodoro stop para parar.`;return v={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},U9++,vX(),`Pomodoro #${U9} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function xX(){if(!v)return"Nenhum pomodoro ativo.";let $=v.label,Z=Math.floor((Date.now()-v.startedAt)/60000);return L7(),v=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function H9(){if(!v)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=hX();return`${v.type==="work"?"Trabalhando":"Pausa"}: "${v.label}" \u2014 ${$} restante(s) (ciclo #${U9})`}function vX(){if(!v)return;L7();let $=v.startedAt+v.durationMs-Date.now();if($<=0){fX();return}F7=setTimeout(fX,$)}function fX(){if(!v)return;if(v.type==="work"){let $=`Pomodoro: "${v.label}" concluido! Hora da pausa (${v.breakMs/60000}min).`;bX("Pausa!",`"${v.label}" concluido. Descanse ${v.breakMs/60000} minutos.`),q9?.($),v={...v,type:"break",startedAt:Date.now(),durationMs:v.breakMs},vX()}else bX("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),q9?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),L7(),v=null}function L7(){if(F7)clearTimeout(F7),F7=null}function hX(){if(!v)return"0min";let $=Math.max(0,v.startedAt+v.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function bX($,Z){if(!L)return;try{await C1($,Z,{timeout:1e4})}catch{}}function gX(){L7(),v=null}n();p0();var m0=new Map,W9=null;function mX($){W9=$}function pX($,Z=60){if(!L)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(m0.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>uX(Y),Z*1000);return m0.set(Y,{name:$,interval:Q,lastSeen:!0}),uX(Y),`Monitorando "${$}" a cada ${Z}s.`}function dX($){let Z=$.toLowerCase(),Y=m0.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),m0.delete(Z),`Monitor parado: "${$}"`}function cX(){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}):
641
+ `)}a();d0();var h=null,A7=null,C9=null,E9=0;function ZK($){C9=$}function YK($="foco",Z=25,Y=5){if(h)return`Pomodoro ja ativo: "${h.label}" (${JK()}). Use /pomodoro stop para parar.`;return h={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},E9++,zK(),`Pomodoro #${E9} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function QK(){if(!h)return"Nenhum pomodoro ativo.";let $=h.label,Z=Math.floor((Date.now()-h.startedAt)/60000);return T7(),h=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function R9(){if(!h)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=JK();return`${h.type==="work"?"Trabalhando":"Pausa"}: "${h.label}" \u2014 ${$} restante(s) (ciclo #${E9})`}function zK(){if(!h)return;T7();let $=h.startedAt+h.durationMs-Date.now();if($<=0){eX();return}A7=setTimeout(eX,$)}function eX(){if(!h)return;if(h.type==="work"){let $=`Pomodoro: "${h.label}" concluido! Hora da pausa (${h.breakMs/60000}min).`;$K("Pausa!",`"${h.label}" concluido. Descanse ${h.breakMs/60000} minutos.`),C9?.($),h={...h,type:"break",startedAt:Date.now(),durationMs:h.breakMs},zK()}else $K("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),C9?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),T7(),h=null}function T7(){if(A7)clearTimeout(A7),A7=null}function JK(){if(!h)return"0min";let $=Math.max(0,h.startedAt+h.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function $K($,Z){if(!L)return;try{await C1($,Z,{timeout:1e4})}catch{}}function XK(){T7(),h=null}a();d0();var p0=new Map,F9=null;function GK($){F9=$}function VK($,Z=60){if(!L)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(p0.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>KK(Y),Z*1000);return p0.set(Y,{name:$,interval:Q,lastSeen:!0}),KK(Y),`Monitorando "${$}" a cada ${Z}s.`}function UK($){let Z=$.toLowerCase(),Y=p0.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),p0.delete(Z),`Monitor parado: "${$}"`}function qK(){if(p0.size===0)return"Nenhum processo monitorado.";let $=[...p0.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${p0.size}):
632
642
  ${$.join(`
633
- `)}`}function lX(){for(let $ of m0.values())clearInterval($.interval);m0.clear()}async function uX($){let Z=m0.get($);if(!Z)return;let Y=await g8(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;C1("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),W9?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;W9?.(Q)}m0.set($,{...Z,lastSeen:Y})}u();d0();var zN=60000,JN=300000,h0={timer:null,lastRefresh:0,refreshCount:0,running:!1},p1=null;function oX($,Z={}){B9(),p1=$;let Y=Z.checkIntervalMs??zN,Q=Z.refreshBufferMs??JN,z=setInterval(()=>{KN(Q,Z)},Y);if(z.unref)z.unref();h0={timer:z,lastRefresh:Date.now(),refreshCount:0,running:!0},g.debug("Auto-refresh started",{checkInterval:Y,refreshBuffer:Q}),Q0("status:update",{source:"auto-refresh",message:"Auto-refresh ativo",level:"info",timestamp:Date.now()})}function B9(){if(h0.timer)clearInterval(h0.timer);h0={...h0,timer:null,running:!1},p1=null}function iX($){p1=$}function XN(){let $=p1?.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:h0.running,lastRefresh:h0.lastRefresh,refreshCount:h0.refreshCount,tokenExpiresAt:$,tokenExpiresIn:Z}}function rX(){let $=XN(),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(`
634
- `)}function KN($,Z){if(!p1)return;let Y=Date.now(),Q=p1.expiresAt-Y;if(Q>$)return;g.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=l1();if(z&&z.expiresAt>p1.expiresAt){nX(z,Y,Z);return}GN(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 nX($,Z,Y){p1=$,h0={...h0,lastRefresh:Z,refreshCount:h0.refreshCount+1},Y.onRefreshed?.($),Q0("status:update",{source:"auto-refresh",message:`Token renovado (expira ${VN($.expiresAt)})`,level:"success",timestamp:Z}),g.debug("Auto-refresh successful",{expiresAt:new Date($.expiresAt).toISOString(),refreshCount:h0.refreshCount})}function GN($,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=l1();if(z&&z.expiresAt>$)nX(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 VN($){return new Date($).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}v1();import{existsSync as qN,readFileSync as UN,writeFileSync as HN}from"fs";import{join as WN}from"path";n();var aX="",sX=()=>WN(aX,"last-morning.txt");function tX($){aX=$;let Z=sX(),Y=new Date().toISOString().split("T")[0];if(!qN(Z))return!0;try{return UN(Z,"utf-8").trim()!==Y}catch{return!0}}function eX(){let $=new Date().toISOString().split("T")[0];HN(sX(),$)}async function $K(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
635
- `);let Q=await G$();$.push(Q);let J=z1().filter((U)=>{if(!U.dueAt)return!1;let H=new Date(U.dueAt),B=new Date;return H.toDateString()===B.toDateString()});if(J.length>0)$.push(`
636
- --- Tarefas do dia ---`),$.push(e1(J));let X=v$();if(X.length>0)$.push(`
637
- --- Follow-ups pendentes ---`),$.push(B5(X));let G=Y$().filter((U)=>U.status==="atrasado");if(G.length>0)$.push(`
638
- --- Delegacoes atrasadas ---`),$.push(W5(G));let V=T5();if(V)$.push(`
639
- ${V}`);if(L)try{let U=await i0();$.push(`
640
- --- Agenda ---`),$.push(U)}catch{}try{let U=await I1(["finance","business","tech"],2);$.push(`
641
- `+U)}catch{}let q=z1();if(q.length>0&&J.length!==q.length)$.push(`
642
- ${q.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
643
+ `)}`}function HK(){for(let $ of p0.values())clearInterval($.interval);p0.clear()}async function KK($){let Z=p0.get($);if(!Z)return;let Y=await m8(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;C1("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),F9?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;F9?.(Q)}p0.set($,{...Z,lastSeen:Y})}u();c0();var wN=60000,kN=300000,g0={timer:null,lastRefresh:0,refreshCount:0,running:!1},d1=null;function WK($,Z={}){L9(),d1=$;let Y=Z.checkIntervalMs??wN,Q=Z.refreshBufferMs??kN,z=setInterval(()=>{bN(Q,Z)},Y);if(z.unref)z.unref();g0={timer:z,lastRefresh:Date.now(),refreshCount:0,running:!0},m.debug("Auto-refresh started",{checkInterval:Y,refreshBuffer:Q}),z0("status:update",{source:"auto-refresh",message:"Auto-refresh ativo",level:"info",timestamp:Date.now()})}function L9(){if(g0.timer)clearInterval(g0.timer);g0={...g0,timer:null,running:!1},d1=null}function BK($){d1=$}function fN(){let $=d1?.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:g0.running,lastRefresh:g0.lastRefresh,refreshCount:g0.refreshCount,tokenExpiresAt:$,tokenExpiresIn:Z}}function NK(){let $=fN(),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(`
644
+ `)}function bN($,Z){if(!d1)return;let Y=Date.now(),Q=d1.expiresAt-Y;if(Q>$)return;m.debug("Token near expiration, attempting refresh",{expiresIn:Math.round(Q/1000)}),z0("status:update",{source:"auto-refresh",message:"Renovando token automaticamente...",level:"warning",timestamp:Y});try{let z=o1();if(z&&z.expiresAt>d1.expiresAt){OK(z,Y,Z);return}yN(Y,Z)}catch(z){let J=`Erro ao renovar: ${z instanceof Error?z.message:String(z)}`;Z.onRefreshFailed?.(J),z0("status:update",{source:"auto-refresh",message:J,level:"error",timestamp:Y})}}function OK($,Z,Y){d1=$,g0={...g0,lastRefresh:Z,refreshCount:g0.refreshCount+1},Y.onRefreshed?.($),z0("status:update",{source:"auto-refresh",message:`Token renovado (expira ${_N($.expiresAt)})`,level:"success",timestamp:Z}),m.debug("Auto-refresh successful",{expiresAt:new Date($.expiresAt).toISOString(),refreshCount:g0.refreshCount})}function yN($,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=o1();if(z&&z.expiresAt>$)OK(z,Date.now(),Z);else Z.onRefreshFailed?.("Falha ao renovar token \u2014 claude nao rotacionou credenciais"),z0("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),z0("status:update",{source:"auto-refresh",message:z,level:"error",timestamp:Date.now()})})}catch{Z.onRefreshFailed?.("claude CLI nao encontrado \u2014 renovacao automatica indisponivel"),z0("status:update",{source:"auto-refresh",message:"claude CLI nao encontrado \u2014 renovacao automatica indisponivel",level:"error",timestamp:Date.now()})}}function _N($){return new Date($).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}h1();import{existsSync as xN,readFileSync as vN,writeFileSync as hN}from"fs";import{join as gN}from"path";a();var MK="",CK=()=>gN(MK,"last-morning.txt");function EK($){MK=$;let Z=CK(),Y=new Date().toISOString().split("T")[0];if(!xN(Z))return!0;try{return vN(Z,"utf-8").trim()!==Y}catch{return!0}}function RK(){let $=new Date().toISOString().split("T")[0];hN(CK(),$)}async function FK(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
645
+ `);let Q=await V$();$.push(Q);let J=J1().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(`
646
+ --- Tarefas do dia ---`),$.push($$(J));let X=h$();if(X.length>0)$.push(`
647
+ --- Follow-ups pendentes ---`),$.push(O5(X));let G=Q$().filter((q)=>q.status==="atrasado");if(G.length>0)$.push(`
648
+ --- Delegacoes atrasadas ---`),$.push(N5(G));let V=S5();if(V)$.push(`
649
+ ${V}`);if(L)try{let q=await n0();$.push(`
650
+ --- Agenda ---`),$.push(q)}catch{}try{let q=await S1(["finance","business","tech"],2);$.push(`
651
+ `+q)}catch{}let U=J1();if(U.length>0&&J.length!==U.length)$.push(`
652
+ ${U.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
643
653
  ==============================`),$.join(`
644
- `)}u();u();v1();n();p0();import{existsSync as ZK,mkdirSync as BN,readFileSync as NN}from"fs";import{join as ON}from"path";import{randomUUID as CN}from"crypto";var YK="",O0=[],QK=()=>ON(YK,"workflows.json");function D8(){A(QK(),JSON.stringify(O0,null,2))}function MN(){let $=QK();if(!ZK($)){O0=N9(),D8();return}try{let Z=JSON.parse(NN($,"utf-8"));if(!Array.isArray(Z)){O0=N9(),D8();return}O0=Z.map((Y)=>({id:Y.id||O9(),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{O0=N9(),D8()}}function N9(){let $=new Date().toISOString();return[{id:O9(),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:O9(),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 zK($){if(YK=$,!ZK($))BN($,{recursive:!0});MN()}function T8($){let Z=$.toLowerCase().trim();return O0.find((Y)=>Y.id===$)||O0.find((Y)=>Y.name.toLowerCase()===Z)||O0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function JK($){let Z=[...O0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z}function C9($,Z){let Y=T8($);if(!Y)return null;return O0=O0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),D8(),O0.find((Q)=>Q.id===Y.id)||null}function XK($){let Z=T8($);if(!Z)return!1;return O0=O0.filter((Y)=>Y.id!==Z.id),D8(),!0}async function M9($,Z){let Y=T8($);if(!Y){let z=O0.map((J)=>J.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${z}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await KK(Y.name,Y.steps,Z);return RN(Q)}async function KK($,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 q=Z[V],U=q.label||`${q.action}:${q.target}`,H=`[${V+1}/${Z.length}]`,B=q.on_error||"continue";Y?.(`${H} ${U}...`);try{let N=await EN(q,Y);z.push(` ${H} ${N}`),J++}catch(N){let C=N instanceof Error?N.message:String(N);switch(K++,B){case"stop":return z.push(` ${H} ERRO (parando): ${C}`),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): ${C}`),X++;break;case"continue":default:z.push(` ${H} ERRO (continuando): ${C}`);break}}}return{workflow:$,success:G,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)}}async function EN($,Z){switch($.action){case"open_app":{if(!L)return`skip: ${$.target} (not Windows)`;return await q1($.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 U1(Y)}case"run_command":{if(!L)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await K0(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(L)try{C1("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 g8(Y,{timeout:5000});if(Q&&$.condition_steps&&$.condition_steps.length>0){let z=await KK(`${$.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 GK($){let Z=$||O0;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}
654
+ `)}u();u();h1();a();d0();import{existsSync as LK,mkdirSync as uN,readFileSync as mN}from"fs";import{join as pN}from"path";import{randomUUID as dN}from"crypto";var jK="",M0=[],PK=()=>pN(jK,"workflows.json");function I8(){P(PK(),JSON.stringify(M0,null,2))}function cN(){let $=PK();if(!LK($)){M0=j9(),I8();return}try{let Z=JSON.parse(mN($,"utf-8"));if(!Array.isArray(Z)){M0=j9(),I8();return}M0=Z.map((Y)=>({id:Y.id||P9(),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{M0=j9(),I8()}}function j9(){let $=new Date().toISOString();return[{id:P9(),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:P9(),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 AK($){if(jK=$,!LK($))uN($,{recursive:!0});cN()}function S8($){let Z=$.toLowerCase().trim();return M0.find((Y)=>Y.id===$)||M0.find((Y)=>Y.name.toLowerCase()===Z)||M0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function TK($){let Z=[...M0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z}function A9($,Z){let Y=S8($);if(!Y)return null;return M0=M0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),I8(),M0.find((Q)=>Q.id===Y.id)||null}function DK($){let Z=S8($);if(!Z)return!1;return M0=M0.filter((Y)=>Y.id!==Z.id),I8(),!0}async function T9($,Z){let Y=S8($);if(!Y){let z=M0.map((J)=>J.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${z}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await IK(Y.name,Y.steps,Z);return oN(Q)}async function IK($,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 N=await lN(U,Y);z.push(` ${H} ${N}`),J++}catch(N){let M=N instanceof Error?N.message:String(N);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 lN($,Z){switch($.action){case"open_app":{if(!L)return`skip: ${$.target} (not Windows)`;return await q1($.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 H1(Y)}case"run_command":{if(!L)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await G0(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(L)try{C1("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 m8(Y,{timeout:5000});if(Q&&$.condition_steps&&$.condition_steps.length>0){let z=await IK(`${$.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 SK($){let Z=$||M0;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}
645
655
  ${" ".repeat(4)}${X} {${Q.id}}`});return`Workflows (${Z.length}):
646
656
  ${Y.join(`
647
657
 
648
- `)}`}function VK($){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(`
649
- `)}function RN($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
650
- `)}function O9(){return CN().slice(0,8)}u();v1();n();p0();import{existsSync as qK,mkdirSync as FN,readFileSync as LN}from"fs";import{join as jN}from"path";import{randomUUID as PN}from"crypto";var UK="",r=[],HK=()=>jN(UK,"macros.json");function n$(){A(HK(),JSON.stringify(r,null,2))}function AN(){let $=HK();if(!qK($)){r=E9(),n$();return}try{let Z=JSON.parse(LN($,"utf-8"));if(!Array.isArray(Z)){r=E9(),n$();return}r=Z.map((Y)=>({id:Y.id||X0(),name:Y.name||"unnamed",description:Y.description||"",action:Y.action||"open_app",target:Y.target||"",args:Y.args,icon:Y.icon,tags:Array.isArray(Y.tags)?Y.tags:[],enabled:Y.enabled!==!1,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString()}))}catch{r=E9(),n$()}}function E9(){let $=new Date().toISOString();return[{id:X0(),name:"vscode",description:"Abrir VS Code",action:"open_app",target:"vscode",icon:"\uD83D\uDCBB",tags:["dev","editor"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"terminal",description:"Abrir Terminal Windows",action:"open_app",target:"terminal",icon:"\u2328\uFE0F",tags:["dev","terminal"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"excel",description:"Abrir Microsoft Excel",action:"open_app",target:"excel",icon:"\uD83D\uDCCA",tags:["office","planilha"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"word",description:"Abrir Microsoft Word",action:"open_app",target:"word",icon:"\uD83D\uDCDD",tags:["office","documento"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"outlook",description:"Abrir Microsoft Outlook",action:"open_app",target:"outlook",icon:"\uD83D\uDCE7",tags:["office","email"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"teams",description:"Abrir Microsoft Teams",action:"open_app",target:"teams",icon:"\uD83D\uDCAC",tags:["office","comunicacao"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"edge",description:"Abrir Microsoft Edge",action:"open_app",target:"edge",icon:"\uD83C\uDF10",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"chrome",description:"Abrir Google Chrome",action:"open_app",target:"chrome",icon:"\uD83D\uDD35",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"explorer",description:"Abrir Explorador de Arquivos",action:"open_app",target:"explorer",icon:"\uD83D\uDCC1",tags:["sistema","arquivos"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"calc",description:"Abrir Calculadora",action:"open_app",target:"calculator",icon:"\uD83D\uDD22",tags:["sistema","utilitario"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"notepad",description:"Abrir Bloco de Notas",action:"open_app",target:"notepad",icon:"\uD83D\uDCC4",tags:["editor","texto"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"tarefas",description:"Abrir Gerenciador de Tarefas",action:"open_app",target:"taskmanager",icon:"\uD83D\uDCCB",tags:["sistema","monitor"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"settings",description:"Abrir Configuracoes do Windows",action:"open_app",target:"settings",icon:"\u2699\uFE0F",tags:["sistema","config"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"github",description:"Abrir GitHub",action:"open_url",target:"https://github.com",icon:"\uD83D\uDC19",tags:["dev","web"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"claude",description:"Abrir Claude.ai",action:"open_url",target:"https://claude.ai",icon:"\uD83E\uDD16",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$},{id:X0(),name:"chatgpt",description:"Abrir ChatGPT",action:"open_url",target:"https://chat.openai.com",icon:"\uD83D\uDCAC",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$}]}function WK($){if(UK=$,!qK($))FN($,{recursive:!0});AN()}function I8($){let Z=$.toLowerCase().trim();return r.find((Y)=>Y.id===$)||r.find((Y)=>Y.name.toLowerCase()===Z)||r.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function BK($){let Z=[...r];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z.filter((Y)=>Y.enabled)}function NK(){return[...r]}function OK($,Z,Y,Q,z){let J=new Date().toISOString();r=r.filter((K)=>K.name.toLowerCase()!==$.toLowerCase().trim());let X={id:X0(),name:$.toLowerCase().trim(),description:Z.trim(),action:Y,target:Q.trim(),args:z?.args,icon:z?.icon,tags:(z?.tags||[]).map((K)=>K.toLowerCase().trim()).filter(Boolean),enabled:!0,createdAt:J,updatedAt:J};return r=[...r,X],n$(),X}function R9($,Z){let Y=I8($);if(!Y)return null;return r=r.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),n$(),r.find((Q)=>Q.id===Y.id)||null}function CK($){let Z=I8($);if(!Z)return!1;return r=r.filter((Y)=>Y.id!==Z.id),n$(),!0}async function MK($){let Z=performance.now(),Y=I8($);if(!Y){let Q=$.toLowerCase().trim(),z=r.filter((X)=>X.enabled&&X.tags.some((K)=>K===Q));if(z.length>0){let X=z.map((K)=>K.name).join(", ");return{macro:$,success:!1,message:`"${$}" e uma tag, nao um macro. Macros com tag "${$}": ${X}`,duration:Math.round(performance.now()-Z)}}let J=r.filter((X)=>X.enabled).map((X)=>X.name).join(", ");return{macro:$,success:!1,message:`Macro nao encontrado: "${$}". Disponiveis: ${J}`,duration:Math.round(performance.now()-Z)}}if(!Y.enabled)return{macro:Y.name,success:!1,message:`Macro "${Y.name}" esta desativado.`,duration:Math.round(performance.now()-Z)};try{let Q=await DN(Y);return{macro:Y.name,success:!0,message:Q,duration:Math.round(performance.now()-Z)}}catch(Q){return{macro:Y.name,success:!1,message:`Erro: ${Q instanceof Error?Q.message:String(Q)}`,duration:Math.round(performance.now()-Z)}}}async function DN($){switch($.action){case"open_app":{if(!L)return`skip: ${$.target} (not Windows)`;return await q1($.target,$.args)}case"open_url":{if(!L)return`skip: ${$.target} (not Windows)`;let Z=$.target.trim();if(!Z.startsWith("http://")&&!Z.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Z}`);return await U1(Z)}case"open_file":{if(!L)return`skip: ${$.target} (not Windows)`;return await X$($.target)}case"run_command":{if(!L)return"skip: command (not Windows)";let Z=$.args?`${$.target} ${$.args}`:$.target;if(!Z.trim())throw Error("Comando vazio");let Y=await K0(Z,{timeout:30000});if(Y.timedOut)throw Error("Command timeout (30s)");if(Y.exitCode!==0&&Y.stderr.trim())throw Error(`exit ${Y.exitCode}: ${Y.stderr.trim().slice(0,200)}`);let Q=Y.stdout.trim().slice(0,200);return`Command: ${Z.slice(0,60)}${Q?" -> "+Q:""}`}default:throw Error(`Acao desconhecida: ${$.action}`)}}function F9($){let Z=$||r.filter((X)=>X.enabled);if(Z.length===0)return"Nenhum macro configurado.";let Y={},Q=[];for(let X of Z)if(X.tags.length===0)Q.push(X);else{let K=X.tags[0];if(!Y[K])Y[K]=[];Y[K].push(X)}let z=[`Macros (${Z.length}):`],J=Object.keys(Y).sort();for(let X of J){z.push(`
658
+ `)}`}function wK($){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(`
659
+ `)}function oN($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
660
+ `)}function P9(){return dN().slice(0,8)}u();h1();a();d0();import{existsSync as kK,mkdirSync as iN,readFileSync as nN}from"fs";import{join as rN}from"path";import{randomUUID as aN}from"crypto";var fK="",r=[],bK=()=>rN(fK,"macros.json");function a$(){P(bK(),JSON.stringify(r,null,2))}function sN(){let $=bK();if(!kK($)){r=D9(),a$();return}try{let Z=JSON.parse(nN($,"utf-8"));if(!Array.isArray(Z)){r=D9(),a$();return}r=Z.map((Y)=>({id:Y.id||K0(),name:Y.name||"unnamed",description:Y.description||"",action:Y.action||"open_app",target:Y.target||"",args:Y.args,icon:Y.icon,tags:Array.isArray(Y.tags)?Y.tags:[],enabled:Y.enabled!==!1,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString()}))}catch{r=D9(),a$()}}function D9(){let $=new Date().toISOString();return[{id:K0(),name:"vscode",description:"Abrir VS Code",action:"open_app",target:"vscode",icon:"\uD83D\uDCBB",tags:["dev","editor"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"terminal",description:"Abrir Terminal Windows",action:"open_app",target:"terminal",icon:"\u2328\uFE0F",tags:["dev","terminal"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"excel",description:"Abrir Microsoft Excel",action:"open_app",target:"excel",icon:"\uD83D\uDCCA",tags:["office","planilha"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"word",description:"Abrir Microsoft Word",action:"open_app",target:"word",icon:"\uD83D\uDCDD",tags:["office","documento"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"outlook",description:"Abrir Microsoft Outlook",action:"open_app",target:"outlook",icon:"\uD83D\uDCE7",tags:["office","email"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"teams",description:"Abrir Microsoft Teams",action:"open_app",target:"teams",icon:"\uD83D\uDCAC",tags:["office","comunicacao"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"edge",description:"Abrir Microsoft Edge",action:"open_app",target:"edge",icon:"\uD83C\uDF10",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"chrome",description:"Abrir Google Chrome",action:"open_app",target:"chrome",icon:"\uD83D\uDD35",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"explorer",description:"Abrir Explorador de Arquivos",action:"open_app",target:"explorer",icon:"\uD83D\uDCC1",tags:["sistema","arquivos"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"calc",description:"Abrir Calculadora",action:"open_app",target:"calculator",icon:"\uD83D\uDD22",tags:["sistema","utilitario"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"notepad",description:"Abrir Bloco de Notas",action:"open_app",target:"notepad",icon:"\uD83D\uDCC4",tags:["editor","texto"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"tarefas",description:"Abrir Gerenciador de Tarefas",action:"open_app",target:"taskmanager",icon:"\uD83D\uDCCB",tags:["sistema","monitor"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"settings",description:"Abrir Configuracoes do Windows",action:"open_app",target:"settings",icon:"\u2699\uFE0F",tags:["sistema","config"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"github",description:"Abrir GitHub",action:"open_url",target:"https://github.com",icon:"\uD83D\uDC19",tags:["dev","web"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"claude",description:"Abrir Claude.ai",action:"open_url",target:"https://claude.ai",icon:"\uD83E\uDD16",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$},{id:K0(),name:"chatgpt",description:"Abrir ChatGPT",action:"open_url",target:"https://chat.openai.com",icon:"\uD83D\uDCAC",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$}]}function yK($){if(fK=$,!kK($))iN($,{recursive:!0});sN()}function w8($){let Z=$.toLowerCase().trim();return r.find((Y)=>Y.id===$)||r.find((Y)=>Y.name.toLowerCase()===Z)||r.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function _K($){let Z=[...r];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z.filter((Y)=>Y.enabled)}function xK(){return[...r]}function vK($,Z,Y,Q,z){let J=new Date().toISOString();r=r.filter((K)=>K.name.toLowerCase()!==$.toLowerCase().trim());let X={id:K0(),name:$.toLowerCase().trim(),description:Z.trim(),action:Y,target:Q.trim(),args:z?.args,icon:z?.icon,tags:(z?.tags||[]).map((K)=>K.toLowerCase().trim()).filter(Boolean),enabled:!0,createdAt:J,updatedAt:J};return r=[...r,X],a$(),X}function I9($,Z){let Y=w8($);if(!Y)return null;return r=r.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),a$(),r.find((Q)=>Q.id===Y.id)||null}function hK($){let Z=w8($);if(!Z)return!1;return r=r.filter((Y)=>Y.id!==Z.id),a$(),!0}async function gK($){let Z=performance.now(),Y=w8($);if(!Y){let Q=$.toLowerCase().trim(),z=r.filter((X)=>X.enabled&&X.tags.some((K)=>K===Q));if(z.length>0){let X=z.map((K)=>K.name).join(", ");return{macro:$,success:!1,message:`"${$}" e uma tag, nao um macro. Macros com tag "${$}": ${X}`,duration:Math.round(performance.now()-Z)}}let J=r.filter((X)=>X.enabled).map((X)=>X.name).join(", ");return{macro:$,success:!1,message:`Macro nao encontrado: "${$}". Disponiveis: ${J}`,duration:Math.round(performance.now()-Z)}}if(!Y.enabled)return{macro:Y.name,success:!1,message:`Macro "${Y.name}" esta desativado.`,duration:Math.round(performance.now()-Z)};try{let Q=await tN(Y);return{macro:Y.name,success:!0,message:Q,duration:Math.round(performance.now()-Z)}}catch(Q){return{macro:Y.name,success:!1,message:`Erro: ${Q instanceof Error?Q.message:String(Q)}`,duration:Math.round(performance.now()-Z)}}}async function tN($){switch($.action){case"open_app":{if(!L)return`skip: ${$.target} (not Windows)`;return await q1($.target,$.args)}case"open_url":{if(!L)return`skip: ${$.target} (not Windows)`;let Z=$.target.trim();if(!Z.startsWith("http://")&&!Z.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Z}`);return await H1(Z)}case"open_file":{if(!L)return`skip: ${$.target} (not Windows)`;return await K$($.target)}case"run_command":{if(!L)return"skip: command (not Windows)";let Z=$.args?`${$.target} ${$.args}`:$.target;if(!Z.trim())throw Error("Comando vazio");let Y=await G0(Z,{timeout:30000});if(Y.timedOut)throw Error("Command timeout (30s)");if(Y.exitCode!==0&&Y.stderr.trim())throw Error(`exit ${Y.exitCode}: ${Y.stderr.trim().slice(0,200)}`);let Q=Y.stdout.trim().slice(0,200);return`Command: ${Z.slice(0,60)}${Q?" -> "+Q:""}`}default:throw Error(`Acao desconhecida: ${$.action}`)}}function S9($){let Z=$||r.filter((X)=>X.enabled);if(Z.length===0)return"Nenhum macro configurado.";let Y={},Q=[];for(let X of Z)if(X.tags.length===0)Q.push(X);else{let K=X.tags[0];if(!Y[K])Y[K]=[];Y[K].push(X)}let z=[`Macros (${Z.length}):`],J=Object.keys(Y).sort();for(let X of J){z.push(`
651
661
  [${X}]`);for(let K of Y[X]){let G=K.icon||"\u25B8",V=K.enabled?"":" (desativado)";z.push(` ${G} ${K.name.padEnd(12)} ${K.description}${V}`)}}if(Q.length>0){z.push(`
652
662
  [outros]`);for(let X of Q){let K=X.icon||"\u25B8",G=X.enabled?"":" (desativado)";z.push(` ${K} ${X.name.padEnd(12)} ${X.description}${G}`)}}return z.push(`
653
663
  Uso: /macro <nome> para executar`),z.join(`
654
- `)}function EK($){let Z=$.enabled?"ativo":"desativado",Y=$.tags.length>0?`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`:"",Q=[`--- Macro {${$.id}} ---`,`Nome: ${$.icon||""} ${$.name}`,`Descricao: ${$.description}`,`Acao: ${$.action}`,`Target: ${$.target}`];if($.args)Q.push(`Args: ${$.args}`);if(Q.push(`Status: ${Z}`),Y)Q.push(Y);return Q.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Q.join(`
655
- `)}function X0(){return PN().slice(0,8)}z8();var RK=!1;function L9($,Z){if(RK)return;RK=!0,HY($,n8().replace(/[/\\]config\.json$/,"")),Nz($),yQ($),jz($),FQ($),mZ(Z),sQ($),eQ(),zz($),zK($),WK($),g6($),lJ($),_z($),cz($),VJ($),k6($,()=>{})}function FK($,Z,Y){L9($,Y),yX((Q)=>Z.showSystem(`
664
+ `)}function uK($){let Z=$.enabled?"ativo":"desativado",Y=$.tags.length>0?`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`:"",Q=[`--- Macro {${$.id}} ---`,`Nome: ${$.icon||""} ${$.name}`,`Descricao: ${$.description}`,`Acao: ${$.action}`,`Target: ${$.target}`];if($.args)Q.push(`Args: ${$.args}`);if(Q.push(`Status: ${Z}`),Y)Q.push(Y);return Q.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Q.join(`
665
+ `)}function K0(){return aN().slice(0,8)}J8();var mK=!1;function w9($,Z){if(mK)return;mK=!0,RY($,s8().replace(/[/\\]config\.json$/,"")),jz($),pQ($),kz($),SQ($),rZ(Z),Jz($),Kz(),Hz($),AK($),yK($),l6($),H3($),dz($),tz($),MJ($),aJ($),_6($,()=>{})}function pK($,Z,Y){w9($,Y),ZK((Q)=>Z.showSystem(`
656
666
  *** ${Q} ***
657
- `)),TJ($,(Q)=>{Z.showSystem(`
667
+ `)),_J($,(Q)=>{Z.showSystem(`
658
668
  *** Meta-Insight: ${Q.title} ***
659
669
  ${Q.recommendation}
660
- `)}),mX((Q)=>Z.showSystem(`
670
+ `)}),GK((Q)=>Z.showSystem(`
661
671
  *** ${Q} ***
662
- `)),pQ($,(Q)=>Z.showSystem(`
672
+ `)),aQ($,(Q)=>Z.showSystem(`
663
673
  *** ${Q} ***
664
- `)),k6($,(Q)=>{Z.showSystem(`
674
+ `)),_6($,(Q)=>{Z.showSystem(`
665
675
  *** LEMBRETE: ${Q.title} ***
666
- `)})}function LK($,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=TN(K.name,K.input);z.push(`> **Tool:** \`${K.name}\`${G}`);let V=K.result.split(`
676
+ `)})}function dK($,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=eN(K.name,K.input);z.push(`> **Tool:** \`${K.name}\`${G}`);let V=K.result.split(`
667
677
  `).slice(0,5).join(`
668
- `);if(V.trim()){z.push("> ```");for(let q of V.split(`
669
- `))z.push(`> ${q}`);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(`
670
- `)}function TN($,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 U$(...$){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 jK(){let $=await U$("git","diff","--cached"),Z=await U$("git","diff"),Y=await U$("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
678
+ `);if(V.trim()){z.push("> ```");for(let U of V.split(`
679
+ `))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(`
680
+ `)}function eN($,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 H$(...$){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 cK(){let $=await H$("git","diff","--cached"),Z=await H$("git","diff"),Y=await H$("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
671
681
  `+$.stdout);if(Z.stdout)Q.push(`=== UNSTAGED ===
672
682
  `+Z.stdout);if(Y.stdout)Q.push(`=== UNTRACKED ===
673
683
  `+Y.stdout);return Q.join(`
674
684
 
675
- `)||"(no changes)"}async function PK(){let $=await U$("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function AK(){return(await U$("git","add","-A")).ok}async function DK($){let Z=await U$("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function TK(){let $=await U$("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var IK={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.
685
+ `)||"(no changes)"}async function lK(){let $=await H$("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function oK(){return(await H$("git","add","-A")).ok}async function iK($){let Z=await H$("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function nK(){let $=await H$("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var rK={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.
676
686
 
677
687
  Behavior:
678
688
  - Write clean, production-grade code. No shortcuts.
@@ -703,73 +713,73 @@ Behavior:
703
713
  - Be specific. Show the line, explain the problem, suggest the fix.
704
714
  - Check for: error handling, input validation, edge cases, naming, complexity.
705
715
  - Don't nitpick formatting unless it affects readability.
706
- - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function SK($){return IK[$.toLowerCase()]||null}function wK($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(IK)){let z=Y===$?" *":" ";Z.push(`${z} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
707
- `)}n();async function kK($){try{let Z=L?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:ZY?["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}}u();v1();import{writeFileSync as IN}from"fs";async function fK($,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((q)=>q.name===G))Z.sessions.unarchive(G);Z.sessions.switchTo(G),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(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?SN(G.updated):"",q=G?`${G.messageCount} msgs`:"";return` ${K.padEnd(20)} ${q.padEnd(10)} ${V}`});Z.tui.showSystem(`Sessoes arquivadas (${J.length}):
716
+ - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function aK($){return rK[$.toLowerCase()]||null}function sK($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(rK)){let z=Y===$?" *":" ";Z.push(`${z} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
717
+ `)}a();async function tK($){try{let Z=L?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:VY?["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}}u();h1();import{writeFileSync as $O}from"fs";async function eK($,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?ZO(G.updated):"",U=G?`${G.messageCount} msgs`:"";return` ${K.padEnd(20)} ${U.padEnd(10)} ${V}`});Z.tui.showSystem(`Sessoes arquivadas (${J.length}):
708
718
  ${X.join(`
709
- `)}`);break}case"model":case"modelo":{let J=z[0];if(!J){Z.tui.showSystem(FY(Z.config.model)+`
719
+ `)}`);break}case"model":case"modelo":{let J=z[0];if(!J){Z.tui.showSystem(SY(Z.config.model)+`
710
720
 
711
- `+ZX());break}let{provider:X,model:K}=H7(J),G=X==="anthropic"?s8(K):K;if(Z.config.model=X==="anthropic"?G:`${X}:${G}`,r8(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(HX(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
712
- 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=l1();if(K){if(Z.auth.auth=K,"updateToken"in Z.claude)Z.claude.updateToken(K.token);iX(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(rX());break}case"config":Z.tui.showSystem(`Config: ${n8()}`);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=LK(Z.sessions.session);IN(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)","","Macros / Atalhos:"," /macro /atalho Listar macros (atalhos rapidos)"," /macro <nome> Executar macro (ex: /macro vscode)"," /macro info <nome> Ver detalhes do macro"," /macro create Criar novo macro","","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(`
713
- `));break;case"commit":case"commitar":{if(!await TK()){Z.tui.showError("Not a git repository.");break}let J=await PK();if(J==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
721
+ `+LX());break}let{provider:X,model:K}=O7(J),G=X==="anthropic"?e8(K):K;if(Z.config.model=X==="anthropic"?G:`${X}:${G}`,a8(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(bX(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
722
+ 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=o1();if(K){if(Z.auth.auth=K,"updateToken"in Z.claude)Z.claude.updateToken(K.token);BK(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(NK());break}case"config":Z.tui.showSystem(`Config: ${s8()}`);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=dK(Z.sessions.session);$O(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)","","Macros / Atalhos:"," /macro /atalho Listar macros (atalhos rapidos)"," /macro <nome> Executar macro (ex: /macro vscode)"," /macro info <nome> Ver detalhes do macro"," /macro create Criar novo macro","","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(`
723
+ `));break;case"commit":case"commitar":{if(!await nK()){Z.tui.showError("Not a git repository.");break}let J=await lK();if(J==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
714
724
  `+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.
715
725
 
716
726
  Diff:
717
- ${(await jK()).slice(0,8000)}`;Z.tui.startStream();let G="";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")G+=q.text,Z.tui.appendStream(q.text);else if(q.type==="error")Z.tui.showError(q.error);if(Z.tui.endStream(),G=G.trim().replace(/^["']|["']$/g,""),!G){Z.tui.showError("Failed to generate commit message. Aborting.");break}await AK();let V=await DK(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(wK(Z.currentPersona));break}let X=SK(J);if(!X){Z.tui.showError(`Unknown persona: ${J}. Try /persona to see options.`);break}if(Z.setCurrentPersona(X.name),X.systemPrompt)Z.setActiveSystemPrompt(B7(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 kK(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(M3(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 E3(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 R3(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=F3(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(J==="installed"||J==="instalados"){let X=L3();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(`
718
- `))}}else if(J==="info"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin info <nome>");break}let K=j3(X);if(K)Z.tui.showSystem(`${K.name} v${K.version} (${K.type})
727
+ ${(await cK()).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 oK();let V=await iK(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(sK(Z.currentPersona));break}let X=aK(J);if(!X){Z.tui.showError(`Unknown persona: ${J}. Try /persona to see options.`);break}if(Z.setCurrentPersona(X.name),X.systemPrompt)Z.setActiveSystemPrompt(C7(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 tK(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(g3(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 u3(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 m3(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=p3(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(J==="installed"||J==="instalados"){let X=d3();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(`
728
+ `))}}else if(J==="info"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin info <nome>");break}let K=c3(X);if(K)Z.tui.showSystem(`${K.name} v${K.version} (${K.type})
719
729
  ${K.description}
720
730
  Status: ${K.enabled?"ativo":"desabilitado"}
721
731
  Source: ${K.source}
722
- Tools: ${K.tools.map((G)=>G.name).join(", ")||"nenhuma"}`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else Z.tui.showSystem(P3());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,r8(Z.config),Z.tui.showSystem(X===0?"Budget: unlimited":`Budget set: $${(X/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!r$.peek()){Z.tui.showError("Nothing to undo.");break}let X=r$.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":""}:
732
+ Tools: ${K.tools.map((G)=>G.name).join(", ")||"nenhuma"}`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else Z.tui.showSystem(l3());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,a8(Z.config),Z.tui.showSystem(X===0?"Budget: unlimited":`Budget set: $${(X/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!r$.peek()){Z.tui.showError("Nothing to undo.");break}let X=r$.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":""}:
723
733
  ${X.join(`
724
- `)}`:`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,r8(Z.config),Z.tui.showSystem(`Language -> ${J}`);break}case"briefing":case"resumo":{Z.tui.showSystem("Carregando briefing..."),Z.tui.disableInput();try{let J=await kX(Z.config.dataDir);Z.tui.showSystem(J);let X=await A8(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 S6(J?[J]:void 0);if(X.length===0){Z.tui.showSystem(K.length>0?`Nenhuma noticia encontrada.
725
- Falhas: ${K.join(", ")}`:"Nenhuma noticia encontrada."),Z.tui.enableInput();break}let G=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"}):""})),V=await Z.tui.promptNewsPicker(G);if(V){if(V.action==="open"){let{openUrl:q}=await Promise.resolve().then(() => (v1(),xJ));q(V.link),Z.tui.showSystem(`Abrindo: ${V.link}`)}else if(V.action==="read"){Z.tui.showSystem("Buscando conteudo...");let q=await LQ(V.link);if(typeof q==="string")Z.tui.showError(q);else{let H=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
734
+ `)}`:`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,a8(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 D8(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 b6(J?[J]:void 0);if(X.length===0){Z.tui.showSystem(K.length>0?`Nenhuma noticia encontrada.
735
+ 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(() => (h1(),cJ));U(V.link),Z.tui.showSystem(`Abrindo: ${V.link}`)}else if(V.action==="read"){Z.tui.showSystem("Buscando conteudo...");let U=await wQ(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:
726
736
 
727
- ${`Noticia: ${q.title}
737
+ ${`Noticia: ${U.title}
728
738
  Fonte: ${V.link}
729
739
 
730
- ${q.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(y4());break}case"addfeed":case"novafonte":{if(z.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
731
- Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let J=z[0],X=z[1],K=z[2],G=w4(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(k4(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(f4(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(b4(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: ${RZ().join(", ")}
732
- Uso: /open <app> ou /open <app> <arquivo>`);break}let X=z.length>1?z.slice(1).join(" "):void 0,K=await q1(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 X$(J);Z.tui.showSystem(X);break}case"openurl":{let J=z[0];if(!J){Z.tui.showError("Uso: /openurl <url>");break}let X=await U1(J);Z.tui.showSystem(X);break}case"apps":case"programas":{Z.tui.disableInput();try{let J=await G8();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 K$();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 G$(),X=await i0();Z.tui.showSystem(`${J}
740
+ ${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(x4());break}case"addfeed":case"novafonte":{if(z.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
741
+ Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let J=z[0],X=z[1],K=z[2],G=f4(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(b4(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(y4(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(_4(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: ${TZ().join(", ")}
742
+ Uso: /open <app> ou /open <app> <arquivo>`);break}let X=z.length>1?z.slice(1).join(" "):void 0,K=await q1(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 K$(J);Z.tui.showSystem(X);break}case"openurl":{let J=z[0];if(!J){Z.tui.showError("Uso: /openurl <url>");break}let X=await H1(J);Z.tui.showSystem(X);break}case"apps":case"programas":{Z.tui.disableInput();try{let J=await V8();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 G$();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 V$(),X=await n0();Z.tui.showSystem(`${J}
733
743
 
734
744
  --- Agenda ---
735
- ${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(cX());else if(J==="stop"||J==="parar"){let X=z[1];if(!X){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(dX(X))}else{let X=parseInt(z[1])||60;Z.tui.showSystem(pX(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(GK(JK(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 M9(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=T8(X);if(K)Z.tui.showSystem(VK(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(XK(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=C9(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=C9(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 M9(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"macro":case"macros":case"atalho":case"atalhos":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let X=z[1];Z.tui.showSystem(F9(BK(X)))}else if(J==="all"||J==="todos")Z.tui.showSystem(F9(NK()));else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro info <nome>");break}let K=I8(X);if(K)Z.tui.showSystem(EK(K));else Z.tui.showError(`Macro nao encontrado: ${X}`)}else if(J==="create"||J==="criar"||J==="new"||J==="novo"){let X=z[1],K=z[2],G=z[3];if(!X||!K||!G){Z.tui.showSystem(`Uso: /macro create <nome> <acao> <target> [descricao]
745
+ ${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(qK());else if(J==="stop"||J==="parar"){let X=z[1];if(!X){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(UK(X))}else{let X=parseInt(z[1])||60;Z.tui.showSystem(VK(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(SK(TK(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 T9(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=S8(X);if(K)Z.tui.showSystem(wK(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(DK(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=A9(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=A9(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 T9(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"macro":case"macros":case"atalho":case"atalhos":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let X=z[1];Z.tui.showSystem(S9(_K(X)))}else if(J==="all"||J==="todos")Z.tui.showSystem(S9(xK()));else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro info <nome>");break}let K=w8(X);if(K)Z.tui.showSystem(uK(K));else Z.tui.showError(`Macro nao encontrado: ${X}`)}else if(J==="create"||J==="criar"||J==="new"||J==="novo"){let X=z[1],K=z[2],G=z[3];if(!X||!K||!G){Z.tui.showSystem(`Uso: /macro create <nome> <acao> <target> [descricao]
736
746
  Acoes: open_app, open_url, open_file, run_command
737
747
  Exemplos:
738
748
  /macro create mysite open_url https://example.com "Meu site"
739
749
  /macro create docs open_file C:\\Users\\Docs "Pasta de documentos"
740
- /macro create cleanup run_command "Remove-Item $env:TEMP\\* -Force"`);break}let V=["open_app","open_url","open_file","run_command"];if(!V.includes(K)){Z.tui.showError(`Acao invalida: ${K}. Use: ${V.join(", ")}`);break}let q=z.slice(4).join(" ")||`Macro: ${X}`,U=OK(X,q,K,G);Z.tui.showSystem(`Macro criado: "${U.name}" (${U.action}: ${U.target})`)}else if(J==="delete"||J==="deletar"||J==="rm"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro delete <nome>");break}if(CK(X))Z.tui.showSystem(`Macro removido: ${X}`);else Z.tui.showError(`Macro nao encontrado: ${X}`)}else if(J==="enable"||J==="ativar"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro enable <nome>");break}let K=R9(X,{enabled:!0});if(K)Z.tui.showSystem(`Macro ativado: ${K.name}`);else Z.tui.showError(`Macro nao encontrado: ${X}`)}else if(J==="disable"||J==="desativar"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro disable <nome>");break}let K=R9(X,{enabled:!1});if(K)Z.tui.showSystem(`Macro desativado: ${K.name}`);else Z.tui.showError(`Macro nao encontrado: ${X}`)}else{Z.tui.disableInput();try{let X=await MK(J);if(X.success)Z.tui.showSystem(`${X.message} (${X.duration}ms)`);else Z.tui.showError(X.message)}catch(X){Z.tui.showError(`Macro: ${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(xX());else if(J==="status")Z.tui.showSystem(H9());else if(!J)Z.tui.showSystem(H9());else{let X=z.join(" "),K=25,G=5;Z.tui.showSystem(_X(X,25,5))}break}case"agendar":case"schedule":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let N=s2(z[1]==="all"||z[1]==="todos");Z.tui.showSystem(t2(N));break}if(J==="remove"||J==="remover"||J==="delete"){if(!z[1]){Z.tui.showSystem("Uso: /agendar remove <id ou nome>");break}let N=await o4(z[1]);Z.tui.showSystem(N?"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 N=await i4(z[1]);Z.tui.showSystem(N?`Agendamento "${N.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 N=await r4(z[1]);Z.tui.showSystem(N?`Agendamento "${N.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 n4(z[1]));break}if(J==="clear"||J==="limpar"){Z.tui.showSystem(await oQ());break}if(J==="detail"||J==="detalhe"||J==="info"){if(!z[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let N=dQ(z[1]);Z.tui.showSystem(N?_6(N):"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]
750
+ /macro create cleanup run_command "Remove-Item $env:TEMP\\* -Force"`);break}let V=["open_app","open_url","open_file","run_command"];if(!V.includes(K)){Z.tui.showError(`Acao invalida: ${K}. Use: ${V.join(", ")}`);break}let U=z.slice(4).join(" ")||`Macro: ${X}`,q=vK(X,U,K,G);Z.tui.showSystem(`Macro criado: "${q.name}" (${q.action}: ${q.target})`)}else if(J==="delete"||J==="deletar"||J==="rm"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro delete <nome>");break}if(hK(X))Z.tui.showSystem(`Macro removido: ${X}`);else Z.tui.showError(`Macro nao encontrado: ${X}`)}else if(J==="enable"||J==="ativar"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro enable <nome>");break}let K=I9(X,{enabled:!0});if(K)Z.tui.showSystem(`Macro ativado: ${K.name}`);else Z.tui.showError(`Macro nao encontrado: ${X}`)}else if(J==="disable"||J==="desativar"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro disable <nome>");break}let K=I9(X,{enabled:!1});if(K)Z.tui.showSystem(`Macro desativado: ${K.name}`);else Z.tui.showError(`Macro nao encontrado: ${X}`)}else{Z.tui.disableInput();try{let X=await gK(J);if(X.success)Z.tui.showSystem(`${X.message} (${X.duration}ms)`);else Z.tui.showError(X.message)}catch(X){Z.tui.showError(`Macro: ${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(QK());else if(J==="status")Z.tui.showSystem(R9());else if(!J)Z.tui.showSystem(R9());else{let X=z.join(" "),K=25,G=5;Z.tui.showSystem(YK(X,25,5))}break}case"agendar":case"schedule":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let N=t2(z[1]==="all"||z[1]==="todos");Z.tui.showSystem(e2(N));break}if(J==="remove"||J==="remover"||J==="delete"){if(!z[1]){Z.tui.showSystem("Uso: /agendar remove <id ou nome>");break}let N=await n4(z[1]);Z.tui.showSystem(N?"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 N=await r4(z[1]);Z.tui.showSystem(N?`Agendamento "${N.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 N=await a4(z[1]);Z.tui.showSystem(N?`Agendamento "${N.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 s4(z[1]));break}if(J==="clear"||J==="limpar"){Z.tui.showSystem(await $z());break}if(J==="detail"||J==="detalhe"||J==="info"){if(!z[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let N=sQ(z[1]);Z.tui.showSystem(N?m6(N):"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]
741
751
  Exemplos:
742
752
  /agendar "Reuniao" "14:00"
743
753
  /agendar "Standup" "09:00" daily
744
754
  /agendar "Review" "15:00" weekly sexta
745
- /agendar "Dentista" "10:00" once 15/04/2026`);break}let G=K[0].slice(1,-1),V=K[1].slice(1,-1),q=a4(V);if(!q){Z.tui.showSystem(`Horario invalido: "${V}". Use formato HH:MM ou HHh.`);break}let U=X.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),H="once",B;for(let N of U){let C=N.toLowerCase();if(C==="daily"||C==="diario")H="daily";else if(C==="weekly"||C==="semanal")H="weekly";else if(C==="once"||C==="uma-vez")H="once";else if(H==="weekly"){let M=t4(N);if(M)B=M}else if(H==="once"){let M=s4(N);if(M)B=M}}if(H==="once"&&!B){let N=new Date,[C,M]=q.split(":").map(Number),F=new Date(N);if(F.setHours(C,M,0,0),F<=N)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 N=await l4(G,H,q,"toast",G,B);Z.tui.showSystem(`Tarefa "${N.name}" agendada para ${_6(N).split(`
746
- `).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(N){Z.tui.showError(`Erro ao agendar: ${N instanceof Error?N.message:String(N)}`)}break}case"agendamentos":case"schedules":{let J=s2(z[0]==="all"||z[0]==="todos");Z.tui.showSystem(t2(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=$8("entrada",J,X,K);if(!G.allowed){Z.tui.showError(G.blocked);break}let V=e2("entrada",J,X,K);Z8("entrada",J,X);let q=Y8(G);if(Z.tui.showSystem(`+ R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description}`),q)Z.tui.showSystem(q);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=$8("saida",J,X,K);if(!G.allowed){Z.tui.showError(G.blocked);break}let V=e2("saida",J,X,K);Z8("saida",J,X);let q=Y8(G);if(Z.tui.showSystem(`- R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description}`),q)Z.tui.showSystem(q);break}case"finance":case"financas":case"balanco":{let J=z[0];if(J==="recent"||J==="recentes")Z.tui.showSystem(v6());else Z.tui.showSystem($5()+`
755
+ /agendar "Dentista" "10:00" once 15/04/2026`);break}let G=K[0].slice(1,-1),V=K[1].slice(1,-1),U=t4(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 N of q){let M=N.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=$5(N);if(C)B=C}else if(H==="once"){let C=e4(N);if(C)B=C}}if(H==="once"&&!B){let N=new Date,[M,C]=U.split(":").map(Number),F=new Date(N);if(F.setHours(M,C,0,0),F<=N)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 N=await i4(G,H,U,"toast",G,B);Z.tui.showSystem(`Tarefa "${N.name}" agendada para ${m6(N).split(`
756
+ `).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(N){Z.tui.showError(`Erro ao agendar: ${N instanceof Error?N.message:String(N)}`)}break}case"agendamentos":case"schedules":{let J=t2(z[0]==="all"||z[0]==="todos");Z.tui.showSystem(e2(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=Z8("entrada",J,X,K);if(!G.allowed){Z.tui.showError(G.blocked);break}let V=$8("entrada",J,X,K);Y8("entrada",J,X);let U=Q8(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=Z8("saida",J,X,K);if(!G.allowed){Z.tui.showError(G.blocked);break}let V=$8("saida",J,X,K);Y8("saida",J,X);let U=Q8(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(d6());else Z.tui.showSystem(Y5()+`
747
757
 
748
- `+v6(5));break}case"decisions":case"decisoes":{let J=z.join(" ");if(J){let X=Z$(J);Z.tui.showSystem(x$(X))}else Z.tui.showSystem(x$(z5()));break}case"investigar":case"investigate":case"investigacoes":{let J=z.join(" ");if(J){let{searchInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (z8(),a6));Z.tui.showSystem(K(X(J)))}else{let{listInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (z8(),a6));Z.tui.showSystem(K(X()))}break}case"email":case"rascunho":{if(!z.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
758
+ `+d6(5));break}case"decisions":case"decisoes":{let J=z.join(" ");if(J){let X=Y$(J);Z.tui.showSystem(v$(X))}else Z.tui.showSystem(v$(X5()));break}case"investigar":case"investigate":case"investigacoes":{let J=z.join(" ");if(J){let{searchInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (J8(),YZ));Z.tui.showSystem(K(X(J)))}else{let{listInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (J8(),YZ));Z.tui.showSystem(K(X()))}break}case"email":case"rascunho":{if(!z.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
749
759
  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>
750
- Use | para separar assunto do corpo.`);break}let V=K.slice(0,G).trim(),q=K.slice(G+1).trim();if(!V||!q){Z.tui.showError("Assunto e corpo sao obrigatorios.");break}let U={to:X,subject:V,body:q};Z.tui.showSystem(m4(U)),Z.tui.disableInput();try{let H=await u4(U);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=a2();Z.tui.showSystem($$(G));break}let X=h4(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=g4(J);Z.tui.showSystem($$(X))}else{let X=a2();Z.tui.showSystem($$(X))}break}case"memotags":case"tags":{Z.tui.showSystem(xQ());break}case"rmmemo":case"rmnota":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmemo <id>");break}if(_Q(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 U=g$(10);Z.tui.showSystem(f1(U));break}if(/^[a-z0-9]{6}$/.test(J)){let U=Az(J);if(U)Z.tui.showSystem(Iz(U));else Z.tui.showError(`Material nao encontrado: ${J}`);break}let X=J.indexOf("|");if(X===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
751
- 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=N5(K,G),q=V.tags.length>0?` [${V.tags.map((U)=>"#"+U).join(" ")}]`:"";Z.tui.showSystem(`Material salvo: "${V.title}" (${V.category})${q} {${V.id}}`);break}case"materials":case"materiais":{let J=z.join(" ");if(J){let X=h$(J);Z.tui.showSystem(f1(X))}else{let X=g$();Z.tui.showSystem(f1(X))}break}case"matcats":case"categorias":{Z.tui.showSystem(Sz());break}case"rmmat":case"rmmaterial":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmat <id>");break}if(O5(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 c$();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=Y7();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=Q7(J);Z.tui.showSystem(z7(X))}else{let X=Z7(),K=X.builtAt?new Date(X.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
760
+ 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(d4(q)),Z.tui.disableInput();try{let H=await p4(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=s2();Z.tui.showSystem(Z$(G));break}let X=u4(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=m4(J);Z.tui.showSystem(Z$(X))}else{let X=s2();Z.tui.showSystem(Z$(X))}break}case"memotags":case"tags":{Z.tui.showSystem(cQ());break}case"rmmemo":case"rmnota":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmemo <id>");break}if(dQ(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=u$(10);Z.tui.showSystem(b1(q));break}if(/^[a-z0-9]{6}$/.test(J)){let q=bz(J);if(q)Z.tui.showSystem(xz(q));else Z.tui.showError(`Material nao encontrado: ${J}`);break}let X=J.indexOf("|");if(X===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
761
+ 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=M5(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=g$(J);Z.tui.showSystem(b1(X))}else{let X=u$();Z.tui.showSystem(b1(X))}break}case"matcats":case"categorias":{Z.tui.showSystem(vz());break}case"rmmat":case"rmmaterial":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmat <id>");break}if(C5(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 l$();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=X7();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=K7(J);Z.tui.showSystem(G7(X))}else{let X=J7(),K=X.builtAt?new Date(X.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
752
762
  Chunks: ${X.chunks}
753
763
  Fontes: ${X.sources}
754
- Ultima indexacao: ${K}`)}break}case"vault":{let J=z[0]?.toLowerCase();if(!J||J==="status")Z.tui.showSystem(l8(c8()));else if(J==="backup"){Z.tui.showSystem("Realizando backup...");let X=z.slice(1).join(" ")||void 0,K=await C$(X);Z.tui.showSystem(K)}else if(J==="sync"||J==="push"){Z.tui.showSystem("Sincronizando com remote...");let X=await i8();Z.tui.showSystem(X)}else if(J==="init"){let X=await o8();Z.tui.showSystem(X),BY(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 C$();Z.tui.showSystem(J);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let J=await b5();switch(J.type){case"text":Z.tui.showSystem(`Clipboard (texto):
755
- ${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 y5();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 V8(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(`
756
- `));break}case"projeto":case"project":{let J=z.join(" ");if(J){let X=E5(J);if(X)p$(X.id),Z.tui.showSystem(A5(X));else if(J==="auto"){let K=I5(process.cwd());if(K)p$(K.id),Z.tui.showSystem(`Projeto detectado: ${A5(K)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${J}"`)}else{let X=y1();if(X)Z.tui.showSystem(A5(X));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(P5(m$()));break}case"sessao":case"session":{let J=z[0],X=y1();if(!X){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(J==="start"||J==="iniciar"){let K=z.slice(1).join(" "),G=R5(X.id,K);if(G)Z.tui.showSystem(`Sessao iniciada para "${X.name}" [${G.id}]`)}else if(J==="stop"||J==="parar"){let K=_1(X.id);if(K){let G=F5(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=_1(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=y1();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 j5(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=L5(J);Z.tui.showSystem(D5(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=V5(X);Z.tui.showSystem(U5(K));break}case"person":case"pessoa":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /person <nome>");break}let X=J1(J);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${J}"`);break}Z.tui.showSystem(H5(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]
757
- 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(","),q=V.join(",").trim()||void 0,U=G5(G.trim(),J,q);Z.tui.showSystem(`Adicionado: ${U.name} (${J}) [${U.id}]`);break}case"delegate":case"delegar":{let J=z[0];if(!J||z.length<2){Z.tui.showSystem(`Uso: /delegate <pessoa> <tarefa>
758
- Ex: /delegate Joao revisar relatorio`);break}let X=z.slice(1).join(" "),K=q5(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=Y$(J);Z.tui.showSystem(W5(X));break}case"followups":{let J=v$();Z.tui.showSystem(B5(J));break}case"dashboard":case"painel":{let J=await j9(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 q=z1();Z.tui.showSystem(e1(q));break}let X=y$(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=x4(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=z1(J);Z.tui.showSystem(e1(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=v4(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(IQ(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 j9($){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=z1(),X=J.filter((U)=>{if(!U.dueAt)return!0;let H=new Date(U.dueAt),B=new Date;return H.toDateString()===B.toDateString()});if(X.length>0||J.length>0){let U=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)U.push(`... +${J.length-X.length} outras`);Z.push({id:"tasks",title:`${Q}! Tarefas (${X.length})`,content:U.length>0?U:["Nenhuma tarefa para hoje"]})}let K=v$();if(K.length>0){let U=K.slice(0,6).map((H)=>{let B=H.person.name||"Alguem",N=H.interaction.summary||"Follow-up pendente";return`${B}: ${N.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${K.length})`,content:U})}let V=Y$().filter((U)=>U.status==="atrasado");if(V.length>0){let U=V.slice(0,5).map((H)=>{return`${J1(H.personId)?.name||"Alguem"}: ${H.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${V.length})`,content:U})}try{let H=(await i0()).split(`
759
- `).filter((N)=>N.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]]}),g.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(U){g.debug("Calendar unavailable for dashboard",{error:U}),Z.push({id:"calendar",title:"Agenda",content:["Erro ao acessar Outlook"]})}let q=T5();if(q){let U=q.split(`
760
- `).filter((H)=>H.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:U})}try{let H=(await I1(["finance","business","tech"],2)).split(`
761
- `).filter((B)=>B.trim()).slice(0,6);if(H.length>0)Z.push({id:"news",title:"Noticias",content:H})}catch(U){g.debug("News fetch failed for dashboard",{error:U})}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 SN($){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 bK($,Z,Y,Q,z,J,X,K,G,V){let q=new V9(Y.model),U=new G9(Y.model,Z.session.name,RY(Q.auth),Y.dataDir),H="default",B=X;FK(Y.dataDir,U,Z);let N=null;try{N=await A8(Y.dataDir),U.setTimeContext(N)}catch(D){g.debug("Time context init failed, using productivity mode",{error:D}),U.setPersonaMode("productivity")}if(oX(Q.auth,{onRefreshed:(D)=>{if(Q.auth=D,"updateToken"in $)$.updateToken(D.token)},onRefreshFailed:(D)=>{U.showError(`Auto-refresh: ${D}`)}}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(D,k,h)=>{if(D==="edit_file"&&k.old_text&&k.new_text){let q0=$X(String(k.old_text),String(k.new_text));for(let c of q0)U.showSystem(c)}let Y0=e3(D,k),y=await U.promptApproval(Y0);if(U._approveAllRequested)$.setAutoApproveAll?.(!0),U._approveAllRequested=!1;return y});for(let D of Z.messages)if(D.role==="user")U.addUserMessage(D.content);else U.addAssistantMessage(D.content);let C=null;async function M(D){if(D.startsWith("/")){await fK(D,w);return}if(Y.maxSessionCost>0){let _=q.totals.costCents;if(_>=Y.maxSessionCost){U.showError(`Budget exceeded (~$${(_/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(_>=Y.maxSessionCost*0.8)U.showSystem(`Budget: ${Math.round(_/Y.maxSessionCost*100)}% used`)}let{text:k,images:h}=TX(D),{text:Y0,files:y}=IX(k),q0=Y0;if(y.length>0)q0=`${y.map((_8)=>`<file name="${_8.name}" path="${_8.path}" size="${_8.size}">
762
- ${_8.content}
764
+ Ultima indexacao: ${K}`)}break}case"vault":{let J=z[0]?.toLowerCase();if(!J||J==="status")Z.tui.showSystem(i8(o8()));else if(J==="backup"){Z.tui.showSystem("Realizando backup...");let X=z.slice(1).join(" ")||void 0,K=await C$(X);Z.tui.showSystem(K)}else if(J==="sync"||J==="push"){Z.tui.showSystem("Sincronizando com remote...");let X=await r8();Z.tui.showSystem(X)}else if(J==="init"){let X=await n8();Z.tui.showSystem(X),LY(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 C$();Z.tui.showSystem(J);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let J=await _5();switch(J.type){case"text":Z.tui.showSystem(`Clipboard (texto):
765
+ ${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 x5();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 U8(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(`
766
+ `));break}case"projeto":case"project":{let J=z.join(" ");if(J){let X=F5(J);if(X)d$(X.id),Z.tui.showSystem(D5(X));else if(J==="auto"){let K=w5(process.cwd());if(K)d$(K.id),Z.tui.showSystem(`Projeto detectado: ${D5(K)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${J}"`)}else{let X=_1();if(X)Z.tui.showSystem(D5(X));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(T5(p$()));break}case"sessao":case"session":{let J=z[0],X=_1();if(!X){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(J==="start"||J==="iniciar"){let K=z.slice(1).join(" "),G=L5(X.id,K);if(G)Z.tui.showSystem(`Sessao iniciada para "${X.name}" [${G.id}]`)}else if(J==="stop"||J==="parar"){let K=x1(X.id);if(K){let G=j5(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=x1(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=_1();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 A5(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=P5(J);Z.tui.showSystem(I5(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=q5(X);Z.tui.showSystem(W5(K));break}case"person":case"pessoa":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /person <nome>");break}let X=X1(J);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${J}"`);break}Z.tui.showSystem(B5(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]
767
+ 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=U5(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>
768
+ Ex: /delegate Joao revisar relatorio`);break}let X=z.slice(1).join(" "),K=H5(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=Q$(J);Z.tui.showSystem(N5(X));break}case"followups":{let J=h$();Z.tui.showSystem(O5(J));break}case"dashboard":case"painel":{let J=await k9(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=J1();Z.tui.showSystem($$(U));break}let X=_$(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=h4(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=J1(J);Z.tui.showSystem($$(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=g4(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(xQ(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 k9($){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=J1(),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=h$();if(K.length>0){let q=K.slice(0,6).map((H)=>{let B=H.person.name||"Alguem",N=H.interaction.summary||"Follow-up pendente";return`${B}: ${N.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${K.length})`,content:q})}let V=Q$().filter((q)=>q.status==="atrasado");if(V.length>0){let q=V.slice(0,5).map((H)=>{return`${X1(H.personId)?.name||"Alguem"}: ${H.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${V.length})`,content:q})}try{let H=(await n0()).split(`
769
+ `).filter((N)=>N.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=S5();if(U){let q=U.split(`
770
+ `).filter((H)=>H.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:q})}try{let H=(await S1(["finance","business","tech"],2)).split(`
771
+ `).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 ZO($){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 $G($,Z,Y,Q,z,J,X,K,G,V){let U=new M9(Y.model),q=new O9(Y.model,Z.session.name,IY(Q.auth),Y.dataDir),H="default",B=X;pK(Y.dataDir,q,Z);let N=null;try{N=await D8(Y.dataDir),q.setTimeContext(N)}catch(T){m.debug("Time context init failed, using productivity mode",{error:T}),q.setPersonaMode("productivity")}if(WK(Q.auth,{onRefreshed:(T)=>{if(Q.auth=T,"updateToken"in $)$.updateToken(T.token)},onRefreshFailed:(T)=>{q.showError(`Auto-refresh: ${T}`)}}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(T,f,g)=>{if(T==="edit_file"&&f.old_text&&f.new_text){let q0=FX(String(f.old_text),String(f.new_text));for(let l of q0)q.showSystem(l)}let Q0=RX(T,f),_=await q.promptApproval(Q0);if(q._approveAllRequested)$.setAutoApproveAll?.(!0),q._approveAllRequested=!1;return _});for(let T of Z.messages)if(T.role==="user")q.addUserMessage(T.content);else q.addAssistantMessage(T.content);let M=null;async function C(T){if(T.startsWith("/")){await eK(T,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}=nX(T),{text:Q0,files:_}=rX(f),q0=Q0;if(_.length>0)q0=`${_.map((v8)=>`<file name="${v8.name}" path="${v8.path}" size="${v8.size}">
772
+ ${v8.content}
763
773
  </file>`).join(`
764
774
 
765
775
  `)}
766
776
 
767
- ${Y0}`;let c={role:"user",content:q0,images:h.length>0?h.map((_)=>({mediaType:_.mediaType,base64:_.base64})):void 0,files:y.length>0?y:void 0,timestamp:Date.now()};Z.addMessage(c);let U0=[];if(h.length>0)U0.push(`${h.length} image${h.length>1?"s":""}`);if(y.length>0)U0.push(`${y.length} file${y.length>1?"s":""}`);let g0=U0.length>0?`${Y0} (${U0.join(", ")})`:Y0;U.addUserMessage(g0),U.disableInput(),U.startStream();let P0="",M0=[],b7={},s$=0,y8=0;C=new AbortController;try{for await(let _ of $.chat(Z.messages,B,K)){if(C.signal.aborted)break;switch(_.type){case"text":U.appendStream(_.text),P0+=_.text;break;case"tool_call":U.flushStream(),U.showToolCall(_.name,_.input),b7=_.input;break;case"tool_result":U.showToolResult(_.name,_.result),M0.push({id:_.id,name:_.name,input:b7,result:_.result}),b7={},U.resetStreamBuffer();break;case"tool_blocked":U.showError(_.reason);break;case"usage":s$+=_.inputTokens,y8+=_.outputTokens;break;case"error":U.showError(_.error);break;case"done":break}}}catch(_){if(!C.signal.aborted)U.showError(_ instanceof Error?_.message:String(_))}C=null,U.endStream();let m9={inputTokens:s$,outputTokens:y8},UG=q.add(m9);if(s$>0||y8>0)U.showUsage(q.formatUsage(m9)),U.updateSessionCost(`~$${(q.totals.costCents/100).toFixed(4)}`);let HG={role:"assistant",content:P0,toolCalls:M0.length>0?M0:void 0,usage:s$>0?{inputTokens:s$,outputTokens:y8,costCents:UG.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(HG),Z.trimHistory(Y.maxHistory),U.enableInput()}function F(){Z.saveLastSession(),TQ(),gX(),lX(),lQ(),l7(),B9(),A3().catch(()=>{}),c$().catch(()=>{}),U.stop(),process.exit(0)}let w={tui:U,sessions:Z,claude:$,config:Y,auth:Q,skills:z,tracker:q,plugins:G,systemPrompt:J,activeSystemPrompt:B,setActiveSystemPrompt:(D)=>{B=D,w.activeSystemPrompt=D},currentPersona:H,setCurrentPersona:(D)=>{H=D,w.currentPersona=D},timeContext:N,setTimeContext:(D)=>{N=D,w.timeContext=D},handleSubmit:M,cleanup:F};process.on("SIGINT",F),process.on("SIGTERM",F),U.start({onSubmit:M,onCancel:()=>{C?.abort(),U.endStream(),U.showSystem("Cancelled."),U.enableInput()},onExit:F});let d=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(U.showSystem(`smolerclaw v${e$()} \u2014 the micro AI assistant.
777
+ ${Q0}`;let l={role:"user",content:q0,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(l);let H0=[];if(g.length>0)H0.push(`${g.length} image${g.length>1?"s":""}`);if(_.length>0)H0.push(`${_.length} file${_.length>1?"s":""}`);let u0=H0.length>0?`${Q0} (${H0.join(", ")})`:Q0;q.addUserMessage(u0),q.disableInput(),q.startStream();let A0="",E0=[],v7={},t$=0,x8=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),A0+=x.text;break;case"tool_call":q.flushStream(),q.showToolCall(x.name,x.input),v7=x.input;break;case"tool_result":q.showToolResult(x.name,x.result),E0.push({id:x.id,name:x.name,input:v7,result:x.result}),v7={},q.resetStreamBuffer();break;case"tool_blocked":q.showError(x.reason);break;case"usage":t$+=x.inputTokens,x8+=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 r9={inputTokens:t$,outputTokens:x8},fG=U.add(r9);if(t$>0||x8>0)q.showUsage(U.formatUsage(r9)),q.updateSessionCost(`~$${(U.totals.costCents/100).toFixed(4)}`);let bG={role:"assistant",content:A0,toolCalls:E0.length>0?E0:void 0,usage:t$>0?{inputTokens:t$,outputTokens:x8,costCents:fG.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(bG),Z.trimHistory(Y.maxHistory),q.enableInput()}function F(){Z.saveLastSession(),_Q(),XK(),HK(),eQ(),r7(),L9(),o3().catch(()=>{}),l$().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:(T)=>{B=T,k.activeSystemPrompt=T},currentPersona:H,setCurrentPersona:(T)=>{H=T,k.currentPersona=T},timeContext:N,setTimeContext:(T)=>{N=T,k.timeContext=T},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 c=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(q.showSystem(`smolerclaw v${$2()} \u2014 the micro AI assistant.
768
778
  Criado por Aldeia Viva - Impactando Vida (aldeia-viva.com.br)
769
- ${d}
770
- Type /ajuda for commands.`),tX(Y.dataDir))try{let D=await j9(Y.dataDir);if(D.panels.length>0){U.enterDashboardMode(D);let k=()=>{U.enterChatMode(),U.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",k)};setTimeout(()=>{if(U.getViewMode()==="dashboard")U.enterChatMode()},30000),process.stdin.once("data",()=>{if(U.getViewMode()==="dashboard")U.enterChatMode()})}else{let k=await $K();U.showSystem(k)}eX()}catch(D){g.debug("Morning briefing failed at startup",{error:D})}if(V)await M(V)}import{exec as KO}from"child_process";var P9=($,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,q;if($[K])q=$[K][0][0],Q.req.routeIndex=K;else q=K===$.length&&z||void 0;if(q)try{G=await q(Q,()=>X(K+1))}catch(U){if(U instanceof Error&&Z)Q.error=U,G=await Z(U,Q),V=!0;else throw U}else if(Q.finalized===!1&&Y)G=await Y(Q);if(G&&(Q.finalized===!1||V))Q.res=G;return Q}}};var yK=Symbol();var _K=async($,Z=Object.create(null))=>{let{all:Y=!1,dot:Q=!1}=Z,J=($ instanceof j7?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return wN($,{all:Y,dot:Q});return{}};async function wN($,Z){let Y=await $.formData();if(Y)return kN(Y,Z);return{}}function kN($,Z){let Y=Object.create(null);if($.forEach((Q,z)=>{if(!(Z.all||z.endsWith("[]")))Y[z]=Q;else fN(Y,z,Q)}),Z.dot)Object.entries(Y).forEach(([Q,z])=>{if(Q.includes("."))bN(Y,Q,z),delete Y[Q]});return Y}var fN=($,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]},bN=($,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 D9=($)=>{let Z=$.split("/");if(Z[0]==="")Z.shift();return Z},xK=($)=>{let{groups:Z,path:Y}=yN($),Q=D9(Y);return _N(Q,Z)},yN=($)=>{let Z=[];return $=$.replace(/\{[^}]+\}/g,(Y,Q)=>{let z=`@${Q}`;return Z.push([z,Y]),z}),{groups:Z,path:$}},_N=($,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 $},P7={},vK=($,Z)=>{if($==="*")return"*";let Y=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let Q=`${$}#${Z}`;if(!P7[Q])if(Y[2])P7[Q]=Z&&Z[0]!==":"&&Z[0]!=="*"?[Q,Y[1],new RegExp(`^${Y[2]}(?=/${Z})`)]:[$,Y[1],new RegExp(`^${Y[2]}$`)];else P7[Q]=[$,Y[1],!0];return P7[Q]}return null},A7=($,Z)=>{try{return Z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return Z(Y)}catch{return Y}})}},T9=($)=>A7($,decodeURI),I9=($)=>{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 T9(G.includes("%25")?G.replace(/%25/g,"%2525"):G)}else if(z===63||z===35)break}return Z.slice(Y,Q)};var hK=($)=>{let Z=I9($);return Z.length>1&&Z.at(-1)==="/"?Z.slice(0,-1):Z},H$=($,Z,...Y)=>{if(Y.length)Z=H$(Z,...Y);return`${$?.[0]==="/"?"":"/"}${$}${Z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${Z?.[0]==="/"?Z.slice(1):Z}`}`},D7=($)=>{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)},A9=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?A7($,S9):$},gK=($,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 A9($.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=A9(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=A9(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},uK=gK,mK=($,Z)=>{return gK($,Z,!0)},S9=decodeURIComponent;var pK=($)=>A7($,S9),j7=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)?pK(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)?pK(Q):Q}return $}#z($){return this.#Z[1]?this.#Z[1][$]:$}query($){return uK(this.url,$)}queries($){return mK(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 _K(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[yK](){return this.#Z}get matchedRoutes(){return this.#Z[0].map(([[,$]])=>$)}get routePath(){return this.#Z[0].map(([[,$]])=>$)[this.routeIndex].path}};var dK={Stringify:1,BeforeStream:2,Stream:3},cK=($,Z)=>{let Y=new String($);return Y.isEscaped=!0,Y.callbacks=Z,Y};var w9=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)=>w9(G,Z,!1,Q,z))).then(()=>z[0]));if(Y)return cK(await X,J);else return X};var xN="text/plain; charset=UTF-8",k9=($,Z)=>{return{"Content-Type":$,...Z}},S8=($,Z)=>new Response($,Z),lK=class{#$;#Z;env={};#Y;finalized=!1;error;#J;#z;#Q;#q;#G;#V;#K;#U;#H;constructor($,Z){if(this.#$=$,Z)this.#z=Z.executionCtx,this.env=Z.env,this.#V=Z.notFoundHandler,this.#H=Z.path,this.#U=Z.matchResult}get req(){return this.#Z??=new j7(this.#$,this.#H,this.#U),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||=S8(null,{headers:this.#K??=new Headers})}set res($){if(this.#Q&&$){$=S8($.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.#q=$;getLayout=()=>this.#q;setRenderer=($)=>{this.#G=$};header=($,Z,Y)=>{if(this.finalized)this.#Q=S8(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 S8($,{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,k9(xN,Y))};json=($,Z,Y)=>{return this.#X(JSON.stringify($),Z,k9("application/json",Y))};html=($,Z,Y)=>{let Q=(z)=>this.#X(z,Z,k9("text/html; charset=UTF-8",Y));return typeof $==="object"?w9($,dK.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??=()=>S8(),this.#V(this)}};var x="ALL",oK="all",iK=["get","post","put","delete","options","patch"],T7="Can not add a route since the matcher is already built.",I7=class extends Error{};var f9="__COMPOSED_HANDLER";var vN=($)=>{return $.text("404 Not Found",404)},rK=($,Z)=>{if("getResponse"in $){let Y=$.getResponse();return Z.newResponse(Y.body,Y)}return console.error($),Z.text("Internal Server Error",500)},nK=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...iK,oK].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((q)=>{this.#J(V.toUpperCase(),this.#$,q)})}return this},this.use=(J,...X)=>{if(typeof J==="string")this.#$=J;else this.#$="*",X.unshift(J);return X.forEach((K)=>{this.#J(x,this.#$,K)}),this};let{strict:Q,...z}=Z;Object.assign(this,z),this.getPath=Q??!0?Z.getPath??I9:hK}#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=vN;errorHandler=rK;route(Z,Y){let Q=this.basePath(Z);return Y.routes.map((z)=>{let J;if(Y.errorHandler===rK)J=z.handler;else J=async(X,K)=>(await P9([],Y.errorHandler)(X,()=>z.handler(X,K))).res,J[f9]=z.handler;Q.#J(z.method,z.path,J)}),this}basePath(Z){let Y=this.#Z();return Y._basePath=H$(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=H$(this._basePath,Z),V=G==="/"?0:G.length;return(q)=>{let U=new URL(q.url);return U.pathname=U.pathname.slice(V)||"/",new Request(U,q)}})();let K=async(G,V)=>{let q=await Y(z(G.req.raw),...X(G));if(q)return q;await V()};return this.#J(x,H$(Z,"*"),K),this}#J(Z,Y,Q){Z=Z.toUpperCase(),Y=H$(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 lK(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(q){return this.#z(q,K)}return V instanceof Promise?V.then((q)=>q||(K.finalized?K.res:this.#Y(K))).catch((q)=>this.#z(q,K)):V??this.#Y(K)}let G=P9(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${H$("/",Z)}`,Y),Q,z)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#Q(Z.request,Z,void 0,Z.request.method))})}};var w8=[];function S7($,Z){let Y=this.buildAllMatchers(),Q=(z,J)=>{let X=Y[z]||Y[x],K=X[2][J];if(K)return K;let G=J.match(X[0]);if(!G)return[[],w8];let V=G.indexOf("",1);return[X[1][V],G]};return this.match=Q,Q($,Z)}var w7="[^/]+",k8=".*",f8="(?:|/.*)",W$=Symbol(),hN=new Set(".\\+*[^]$()");function gN($,Z){if($.length===1)return Z.length===1?$<Z?-1:1:-1;if(Z.length===1)return 1;if($===k8||$===f8)return 1;else if(Z===k8||Z===f8)return-1;if($===w7)return 1;else if(Z===w7)return-1;return $.length===Z.length?$<Z?-1:1:Z.length-$.length}var aK=class ${#$;#Z;#Y=Object.create(null);insert(Z,Y,Q,z,J){if(Z.length===0){if(this.#$!==void 0)throw W$;if(J)return;this.#$=Y;return}let[X,...K]=Z,G=X==="*"?K.length===0?["","",k8]:["","",w7]:X==="/*"?["","",f8]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),V;if(G){let q=G[1],U=G[2]||w7;if(q&&G[2]){if(U===".*")throw W$;if(U=U.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(U))throw W$}if(V=this.#Y[U],!V){if(Object.keys(this.#Y).some((H)=>H!==k8&&H!==f8))throw W$;if(J)return;if(V=this.#Y[U]=new $,q!=="")V.#Z=z.varIndex++}if(!J&&q!=="")Q.push([q,V.#Z])}else if(V=this.#Y[X],!V){if(Object.keys(this.#Y).some((q)=>q.length>1&&q!==k8&&q!==f8))throw W$;if(J)return;V=this.#Y[X]=new $}V.insert(K,Y,Q,z,J)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(gN).map((Q)=>{let z=this.#Y[Q];return(typeof z.#Z==="number"?`(${Q})@${z.#Z}`:hN.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 sK=class{#$={varIndex:0};#Z=new aK;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 uN=[/^$/,[],Object.create(null)],tK=Object.create(null);function eK($){return tK[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function mN(){tK=Object.create(null)}function pN($){let Z=new sK,Y=[];if($.length===0)return uN;let Q=$.map((V)=>[!/\*|\/:/.test(V[0]),...V]).sort(([V,q],[U,H])=>V?1:U?-1:q.length-H.length),z=Object.create(null);for(let V=0,q=-1,U=Q.length;V<U;V++){let[H,B,N]=Q[V];if(H)z[B]=[N.map(([M])=>[M,Object.create(null)]),w8];else q++;let C;try{C=Z.insert(B,q,H)}catch(M){throw M===W$?new I7(B):M}if(H)continue;Y[q]=N.map(([M,F])=>{let w=Object.create(null);F-=1;for(;F>=0;F--){let[d,D]=C[F];w[d]=D}return[M,w]})}let[J,X,K]=Z.buildRegExp();for(let V=0,q=Y.length;V<q;V++)for(let U=0,H=Y[V].length;U<H;U++){let B=Y[V][U]?.[1];if(!B)continue;let N=Object.keys(B);for(let C=0,M=N.length;C<M;C++)B[N[C]]=K[B[N[C]]]}let G=[];for(let V in X)G[V]=Y[X[V]];return[J,G,z]}function a$($,Z){if(!$)return;for(let Y of Object.keys($).sort((Q,z)=>z.length-Q.length))if(eK(Y).test(Z))return[...$[Y]];return}var k7=class{name="RegExpRouter";#$;#Z;constructor(){this.#$={[x]:Object.create(null)},this.#Z={[x]:Object.create(null)}}add($,Z,Y){let Q=this.#$,z=this.#Z;if(!Q||!z)throw Error(T7);if(!Q[$])[Q,z].forEach((K)=>{K[$]=Object.create(null),Object.keys(K[x]).forEach((G)=>{K[$][G]=[...K[x][G]]})});if(Z==="/*")Z="*";let J=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let K=eK(Z);if($===x)Object.keys(Q).forEach((G)=>{Q[G][Z]||=a$(Q[G],Z)||a$(Q[x],Z)||[]});else Q[$][Z]||=a$(Q[$],Z)||a$(Q[x],Z)||[];Object.keys(Q).forEach((G)=>{if($===x||$===G)Object.keys(Q[G]).forEach((V)=>{K.test(V)&&Q[G][V].push([Y,J])})}),Object.keys(z).forEach((G)=>{if($===x||$===G)Object.keys(z[G]).forEach((V)=>K.test(V)&&z[G][V].push([Y,J]))});return}let X=D7(Z)||[Z];for(let K=0,G=X.length;K<G;K++){let V=X[K];Object.keys(z).forEach((q)=>{if($===x||$===q)z[q][V]||=[...a$(Q[q],V)||a$(Q[x],V)||[]],z[q][V].push([Y,J-G+K+1])})}}match=S7;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,mN(),$}#Y($){let Z=[],Y=$===x;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($!==x)Z.push(...Object.keys(Q[x]).map((J)=>[J,Q[x][J]]))}),!Y)return null;else return pN(Z)}};var dN=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.#$[x],J={};for(let X in z[2])J[X]=[z[2][X][0].slice(),w8];this.#$[$]=[z[0],z[1].map((X)=>Array.isArray(X)?X.slice():0),J]}if(Z==="/*"||Z==="*"){let z=[Y,{}];if($===x)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($===x)for(let X in this.#$)this.#J(X,Z,Y,z,J);else this.#J($,Z,Y,z,J)}buildAllMatchers(){return this.#$}match=S7};var b9=class{name="SmartRouter";#$=[];#Z=[];constructor($){this.#$=$.routers}add($,Z,Y){if(!this.#Z)throw Error(T7);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 I7)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 b8=Object.create(null),cN=($)=>{for(let Z in $)return!0;return!1},$G=class ${#$;#Z;#Y;#J=0;#z=b8;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=xK(Y),X=[];for(let K=0,G=J.length;K<G;K++){let V=J[K],q=J[K+1],U=vK(V,q),H=Array.isArray(U)?U[0]:V;if(H in z.#Z){if(z=z.#Z[H],U)X.push(U[1]);continue}if(z.#Z[H]=new $,U)z.#Y.push(U),X.push(U[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[x],q={};if(V!==void 0){if(V.params=Object.create(null),Z.push(V),z!==b8||J&&J!==b8)for(let U=0,H=V.possibleKeys.length;U<H;U++){let B=V.possibleKeys[U],N=q[V.score];V.params[B]=J?.[B]&&!N?J[B]:z[B]??J?.[B],q[V.score]=!0}}}}search(Z,Y){let Q=[];this.#z=b8;let J=[this],X=D9(Y),K=[],G=X.length,V=null;for(let q=0;q<G;q++){let U=X[q],H=q===G-1,B=[];for(let C=0,M=J.length;C<M;C++){let F=J[C],w=F.#Z[U];if(w)if(w.#z=F.#z,H){if(w.#Z["*"])this.#Q(Q,w.#Z["*"],Z,F.#z);this.#Q(Q,w,Z,F.#z)}else B.push(w);for(let d=0,D=F.#Y.length;d<D;d++){let k=F.#Y[d],h=F.#z===b8?{}:{...F.#z};if(k==="*"){let U0=F.#Z["*"];if(U0)this.#Q(Q,U0,Z,F.#z),U0.#z=h,B.push(U0);continue}let[Y0,y,q0]=k;if(!U&&!(q0 instanceof RegExp))continue;let c=F.#Z[Y0];if(q0 instanceof RegExp){if(V===null){V=Array(G);let P0=Y[0]==="/"?1:0;for(let M0=0;M0<G;M0++)V[M0]=P0,P0+=X[M0].length+1}let U0=Y.substring(V[q]),g0=q0.exec(U0);if(g0){if(h[y]=g0[0],this.#Q(Q,c,Z,F.#z,h),cN(c.#Z)){c.#z=h;let P0=g0[0].match(/\//)?.length??0;(K[P0]||=[]).push(c)}continue}}if(q0===!0||q0.test(U))if(h[y]=U,H){if(this.#Q(Q,c,Z,h,F.#z),c.#Z["*"])this.#Q(Q,c.#Z["*"],Z,h,F.#z)}else c.#z=h,B.push(c)}}let N=K.shift();J=N?B.concat(N):B}if(Q.length>1)Q.sort((q,U)=>{return q.score-U.score});return[Q.map(({handler:q,params:U})=>[q,U])]}};var y9=class{name="TrieRouter";#$;constructor(){this.#$=new $G}add($,Z,Y){let Q=D7(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 _9=class extends nK{constructor($={}){super($);this.router=$.router??new b9({routers:[new k7,new y9]})}};import{stat as nN}from"fs/promises";import{join as aN}from"path";var ZG=/^\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 x9=($,Z=oN)=>{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 lN={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"},oN=lN;var YG=(...$)=>{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 QG={br:".br",zstd:".zst",gzip:".gz"},iN=Object.keys(QG),rN="index.html",zG=($)=>{let Z=$.root??"./",Y=$.path,Q=$.join??YG;return async(z,J)=>{if(z.finalized)return J();let X;if($.path)X=$.path;else try{if(X=T9(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,rN);let G=$.getContent,V=await G(K,z);if(V instanceof Response)return z.newResponse(V.body,V);if(V){let q=$.mimes&&x9(K,$.mimes)||x9(K);if(z.header("Content-Type",q||"application/octet-stream"),$.precompressed&&(!q||ZG.test(q))){let U=new Set(z.req.header("Accept-Encoding")?.split(",").map((H)=>H.trim()));for(let H of iN){if(!U.has(H))continue;let B=await G(K+QG[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 v9=($)=>{return async function(Y,Q){return zG({...$,getContent:async(X)=>{let K=Bun.file(X);return await K.exists()?K:null},join:aN,isDir:async(X)=>{let K;try{K=(await nN(X)).isDirectory()}catch{}return K}})(Y,Q)}};var h9="x-hono-disable-ssg",Tk=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[h9]:"true"}})}catch{return null}})();var{write:Gf}=Bun;var eN=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 JG=($)=>{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 f7=($)=>("server"in $.env)?$.env.server:$.env;var $O=JG(($,Z)=>{let Y=f7($);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 XG=($)=>{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(q,U){X.res.headers.set(q,U)}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 q=await z(X.req.header("origin")||"",X);if(q.length)G("Access-Control-Allow-Methods",q.join(","));let U=Y.allowHeaders;if(!U?.length){let H=X.req.header("Access-Control-Request-Headers");if(H)U=H.split(/\s*,\s*/)}if(U?.length)G("Access-Control-Allow-Headers",U.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 ZO(){let{process:$,Deno:Z}=globalThis;return!(typeof Z?.noColor==="boolean"?Z.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}async function KG(){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}})():!ZO())}var YO=($)=>{let[Z,Y]=[",","."];return $.map((z)=>z.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Z)).join(Y)},QO=($)=>{let Z=Date.now()-$;return YO([Z<1000?Z+"ms":Math.round(Z/1000)+"s"])},zO=async($)=>{if(await KG())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 GG($,Z,Y,Q,z=0,J){let X=Z==="<--"?`${Z} ${Y} ${Q}`:`${Z} ${Y} ${Q} ${await zO(z)} ${J}`;$(X)}var VG=($=console.log)=>{return async function(Y,Q){let{method:z,url:J}=Y.req,X=J.slice(J.indexOf("/",8));await GG($,"<--",z,X);let K=Date.now();await Q(),await GG($,"-->",z,X,Y.res.status,QO(K))}};d0();class g9{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((q)=>q.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((q)=>q.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 q={role:"assistant",content:Q,toolCalls:z.map((U)=>({id:U.id,name:U.name,input:U.input,result:U.result||""})),usage:{inputTokens:J,outputTokens:X,costCents:this.calculateCost(J,X)},timestamp:Date.now()};if(this.messages.push(q),this.currentSessionName)this.sessionManager.addMessageTo(this.currentSessionName,q);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 JO={theme:"system",fontSize:"medium",showToolCalls:!0,showCosts:!0,autoScroll:!0,enableSounds:!1};function u9($){let Z=new _9,Y=new Map;Z.use("*",VG()),Z.use("*",XG()),Z.use("/static/*",v9({root:"./src/ui/web"})),Z.get("/",(K)=>{return K.html(XO(U3()))}),Z.get("/api/health",(K)=>K.json({status:"ok"}));function Q(K,G){let V=new g9({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,onApprovalRequired:async(B,N,C)=>{return J(K,{type:"tool_approval_required",payload:{toolCallId:`tool_${Date.now()}`,name:B,input:N,riskLevel:C}}),!0}}),q={chatService:V,settings:{...JO}};Y.set(G,q);let U=$.sessionManager.getCurrentName(),H=V.resumeSession(U)||V.newSession();return J(K,{type:"connected",payload:{sessionId:H.id}}),X(K,V,q.settings),q}async function z(K,G,V,q){switch(q.type){case"chat":{let U=`msg_${Date.now()}`;J(K,{type:"message_start",payload:{messageId:U}});for await(let H of G.chat(q.payload))switch(H.type){case"text":J(K,{type:"text_delta",payload:{messageId:U,text:H.data}});break;case"tool_call":let B=H.data;J(K,{type:"tool_call",payload:{messageId:U,id:B.id,name:B.name,input:B.input,status:"running"}});break;case"tool_result":let N=H.data;J(K,{type:"tool_result",payload:{messageId:U,toolCallId:N.id,result:N.result}});break;case"tool_blocked":let C=H.data;J(K,{type:"tool_blocked",payload:{messageId:U,toolCallId:C.id,reason:C.reason}});break;case"usage":let M=H.data;J(K,{type:"usage",payload:{messageId:U,...M}});break;case"done":J(K,{type:"message_complete",payload:{messageId:U}});break;case"error":J(K,{type:"error",payload:{error:H.data}});break}break}case"new_session":{let U=G.newSession(q.payload?.name);J(K,{type:"connected",payload:{sessionId:U.id}}),X(K,G,V);break}case"load_session":{G.loadSession(q.payload.sessionId),X(K,G,V);break}case"delete_session":{G.deleteSessionById(q.payload.sessionId),J(K,{type:"sessions_updated",payload:G.getSessions()});break}case"update_settings":{Object.assign(V,q.payload),X(K,G,V);break}}}function J(K,G){K.send(JSON.stringify(G))}function X(K,G,V){let q=G.getSessions(),U=q.find((N)=>N.isActive)||null,H=G.getMessages(),B={currentSession:U,sessions:q,messages:H,isStreaming:!1,model:"claude-sonnet-4-20250514",systemPrompt:$.systemPrompt,totalCostCents:H.reduce((N,C)=>N+(C.usage?.costCents||0),0),settings:V};J(K,{type:"state",payload:B})}return{app:Z,start:()=>{console.log(`
771
- ${O8("ui.running_at",{url:`http://localhost:${$.port}`})}
772
- `);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)}`,q=Q(G,V);K.set(G,{clientId:V,client:q})},async message(G,V){let q=K.get(G);if(!q)return;try{let U=JSON.parse(V.toString());await z(G,q.client.chatService,q.client.settings,U)}catch(U){J(G,{type:"error",payload:{error:U instanceof Error?U.message:"Unknown error"}})}},close(G){let V=K.get(G);if(V)Y.delete(V.clientId),K.delete(G)}}})}}}function XO($){let Z=(Y)=>$[Y]||Y;return`<!DOCTYPE html>
779
+ ${c}
780
+ Type /ajuda for commands.`),EK(Y.dataDir))try{let T=await k9(Y.dataDir);if(T.panels.length>0){q.enterDashboardMode(T);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 FK();q.showSystem(f)}RK()}catch(T){m.debug("Morning briefing failed at startup",{error:T})}if(V)await C(V)}import{exec as bO}from"child_process";var f9=($,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 ZG=Symbol();var YG=async($,Z=Object.create(null))=>{let{all:Y=!1,dot:Q=!1}=Z,J=($ instanceof D7?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return YO($,{all:Y,dot:Q});return{}};async function YO($,Z){let Y=await $.formData();if(Y)return QO(Y,Z);return{}}function QO($,Z){let Y=Object.create(null);if($.forEach((Q,z)=>{if(!(Z.all||z.endsWith("[]")))Y[z]=Q;else zO(Y,z,Q)}),Z.dot)Object.entries(Y).forEach(([Q,z])=>{if(Q.includes("."))JO(Y,Q,z),delete Y[Q]});return Y}var zO=($,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]},JO=($,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 y9=($)=>{let Z=$.split("/");if(Z[0]==="")Z.shift();return Z},QG=($)=>{let{groups:Z,path:Y}=XO($),Q=y9(Y);return KO(Q,Z)},XO=($)=>{let Z=[];return $=$.replace(/\{[^}]+\}/g,(Y,Q)=>{let z=`@${Q}`;return Z.push([z,Y]),z}),{groups:Z,path:$}},KO=($,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 $},I7={},zG=($,Z)=>{if($==="*")return"*";let Y=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let Q=`${$}#${Z}`;if(!I7[Q])if(Y[2])I7[Q]=Z&&Z[0]!==":"&&Z[0]!=="*"?[Q,Y[1],new RegExp(`^${Y[2]}(?=/${Z})`)]:[$,Y[1],new RegExp(`^${Y[2]}$`)];else I7[Q]=[$,Y[1],!0];return I7[Q]}return null},S7=($,Z)=>{try{return Z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return Z(Y)}catch{return Y}})}},_9=($)=>S7($,decodeURI),x9=($)=>{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 _9(G.includes("%25")?G.replace(/%25/g,"%2525"):G)}else if(z===63||z===35)break}return Z.slice(Y,Q)};var JG=($)=>{let Z=x9($);return Z.length>1&&Z.at(-1)==="/"?Z.slice(0,-1):Z},W$=($,Z,...Y)=>{if(Y.length)Z=W$(Z,...Y);return`${$?.[0]==="/"?"":"/"}${$}${Z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${Z?.[0]==="/"?Z.slice(1):Z}`}`},w7=($)=>{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)},b9=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?S7($,v9):$},XG=($,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 b9($.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=b9(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=b9(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},KG=XG,GG=($,Z)=>{return XG($,Z,!0)},v9=decodeURIComponent;var VG=($)=>S7($,v9),D7=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)?VG(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)?VG(Q):Q}return $}#z($){return this.#Z[1]?this.#Z[1][$]:$}query($){return KG(this.url,$)}queries($){return GG(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 YG(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[ZG](){return this.#Z}get matchedRoutes(){return this.#Z[0].map(([[,$]])=>$)}get routePath(){return this.#Z[0].map(([[,$]])=>$)[this.routeIndex].path}};var UG={Stringify:1,BeforeStream:2,Stream:3},qG=($,Z)=>{let Y=new String($);return Y.isEscaped=!0,Y.callbacks=Z,Y};var h9=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)=>h9(G,Z,!1,Q,z))).then(()=>z[0]));if(Y)return qG(await X,J);else return X};var GO="text/plain; charset=UTF-8",g9=($,Z)=>{return{"Content-Type":$,...Z}},k8=($,Z)=>new Response($,Z),HG=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 D7(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||=k8(null,{headers:this.#K??=new Headers})}set res($){if(this.#Q&&$){$=k8($.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=k8(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 k8($,{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,g9(GO,Y))};json=($,Z,Y)=>{return this.#X(JSON.stringify($),Z,g9("application/json",Y))};html=($,Z,Y)=>{let Q=(z)=>this.#X(z,Z,g9("text/html; charset=UTF-8",Y));return typeof $==="object"?h9($,UG.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??=()=>k8(),this.#V(this)}};var v="ALL",WG="all",BG=["get","post","put","delete","options","patch"],k7="Can not add a route since the matcher is already built.",f7=class extends Error{};var u9="__COMPOSED_HANDLER";var VO=($)=>{return $.text("404 Not Found",404)},NG=($,Z)=>{if("getResponse"in $){let Y=$.getResponse();return Z.newResponse(Y.body,Y)}return console.error($),Z.text("Internal Server Error",500)},OG=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...BG,WG].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??x9:JG}#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=VO;errorHandler=NG;route(Z,Y){let Q=this.basePath(Z);return Y.routes.map((z)=>{let J;if(Y.errorHandler===NG)J=z.handler;else J=async(X,K)=>(await f9([],Y.errorHandler)(X,()=>z.handler(X,K))).res,J[u9]=z.handler;Q.#J(z.method,z.path,J)}),this}basePath(Z){let Y=this.#Z();return Y._basePath=W$(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=W$(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,W$(Z,"*"),K),this}#J(Z,Y,Q){Z=Z.toUpperCase(),Y=W$(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 HG(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=f9(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${W$("/",Z)}`,Y),Q,z)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#Q(Z.request,Z,void 0,Z.request.method))})}};var f8=[];function b7($,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[[],f8];let V=G.indexOf("",1);return[X[1][V],G]};return this.match=Q,Q($,Z)}var y7="[^/]+",b8=".*",y8="(?:|/.*)",B$=Symbol(),UO=new Set(".\\+*[^]$()");function qO($,Z){if($.length===1)return Z.length===1?$<Z?-1:1:-1;if(Z.length===1)return 1;if($===b8||$===y8)return 1;else if(Z===b8||Z===y8)return-1;if($===y7)return 1;else if(Z===y7)return-1;return $.length===Z.length?$<Z?-1:1:Z.length-$.length}var MG=class ${#$;#Z;#Y=Object.create(null);insert(Z,Y,Q,z,J){if(Z.length===0){if(this.#$!==void 0)throw B$;if(J)return;this.#$=Y;return}let[X,...K]=Z,G=X==="*"?K.length===0?["","",b8]:["","",y7]:X==="/*"?["","",y8]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),V;if(G){let U=G[1],q=G[2]||y7;if(U&&G[2]){if(q===".*")throw B$;if(q=q.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(q))throw B$}if(V=this.#Y[q],!V){if(Object.keys(this.#Y).some((H)=>H!==b8&&H!==y8))throw B$;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!==b8&&U!==y8))throw B$;if(J)return;V=this.#Y[X]=new $}V.insert(K,Y,Q,z,J)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(qO).map((Q)=>{let z=this.#Y[Q];return(typeof z.#Z==="number"?`(${Q})@${z.#Z}`:UO.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 CG=class{#$={varIndex:0};#Z=new MG;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 HO=[/^$/,[],Object.create(null)],EG=Object.create(null);function RG($){return EG[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function WO(){EG=Object.create(null)}function BO($){let Z=new CG,Y=[];if($.length===0)return HO;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,N]=Q[V];if(H)z[B]=[N.map(([C])=>[C,Object.create(null)]),f8];else U++;let M;try{M=Z.insert(B,U,H)}catch(C){throw C===B$?new f7(B):C}if(H)continue;Y[U]=N.map(([C,F])=>{let k=Object.create(null);F-=1;for(;F>=0;F--){let[c,T]=M[F];k[c]=T}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 N=Object.keys(B);for(let M=0,C=N.length;M<C;M++)B[N[M]]=K[B[N[M]]]}let G=[];for(let V in X)G[V]=Y[X[V]];return[J,G,z]}function s$($,Z){if(!$)return;for(let Y of Object.keys($).sort((Q,z)=>z.length-Q.length))if(RG(Y).test(Z))return[...$[Y]];return}var _7=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(k7);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=RG(Z);if($===v)Object.keys(Q).forEach((G)=>{Q[G][Z]||=s$(Q[G],Z)||s$(Q[v],Z)||[]});else Q[$][Z]||=s$(Q[$],Z)||s$(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=w7(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]||=[...s$(Q[U],V)||s$(Q[v],V)||[]],z[U][V].push([Y,J-G+K+1])})}}match=b7;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,WO(),$}#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 BO(Z)}};var NO=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(),f8];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=b7};var m9=class{name="SmartRouter";#$=[];#Z=[];constructor($){this.#$=$.routers}add($,Z,Y){if(!this.#Z)throw Error(k7);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 f7)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 _8=Object.create(null),OO=($)=>{for(let Z in $)return!0;return!1},FG=class ${#$;#Z;#Y;#J=0;#z=_8;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=QG(Y),X=[];for(let K=0,G=J.length;K<G;K++){let V=J[K],U=J[K+1],q=zG(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!==_8||J&&J!==_8)for(let q=0,H=V.possibleKeys.length;q<H;q++){let B=V.possibleKeys[q],N=U[V.score];V.params[B]=J?.[B]&&!N?J[B]:z[B]??J?.[B],U[V.score]=!0}}}}search(Z,Y){let Q=[];this.#z=_8;let J=[this],X=y9(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 c=0,T=F.#Y.length;c<T;c++){let f=F.#Y[c],g=F.#z===_8?{}:{...F.#z};if(f==="*"){let H0=F.#Z["*"];if(H0)this.#Q(Q,H0,Z,F.#z),H0.#z=g,B.push(H0);continue}let[Q0,_,q0]=f;if(!q&&!(q0 instanceof RegExp))continue;let l=F.#Z[Q0];if(q0 instanceof RegExp){if(V===null){V=Array(G);let A0=Y[0]==="/"?1:0;for(let E0=0;E0<G;E0++)V[E0]=A0,A0+=X[E0].length+1}let H0=Y.substring(V[U]),u0=q0.exec(H0);if(u0){if(g[_]=u0[0],this.#Q(Q,l,Z,F.#z,g),OO(l.#Z)){l.#z=g;let A0=u0[0].match(/\//)?.length??0;(K[A0]||=[]).push(l)}continue}}if(q0===!0||q0.test(q))if(g[_]=q,H){if(this.#Q(Q,l,Z,g,F.#z),l.#Z["*"])this.#Q(Q,l.#Z["*"],Z,g,F.#z)}else l.#z=g,B.push(l)}}let N=K.shift();J=N?B.concat(N):B}if(Q.length>1)Q.sort((U,q)=>{return U.score-q.score});return[Q.map(({handler:U,params:q})=>[U,q])]}};var p9=class{name="TrieRouter";#$;constructor(){this.#$=new FG}add($,Z,Y){let Q=w7(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 d9=class extends OG{constructor($={}){super($);this.router=$.router??new m9({routers:[new _7,new p9]})}};import{stat as FO}from"fs/promises";import{join as LO}from"path";var LG=/^\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 c9=($,Z=CO)=>{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 MO={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"},CO=MO;var jG=(...$)=>{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 PG={br:".br",zstd:".zst",gzip:".gz"},EO=Object.keys(PG),RO="index.html",AG=($)=>{let Z=$.root??"./",Y=$.path,Q=$.join??jG;return async(z,J)=>{if(z.finalized)return J();let X;if($.path)X=$.path;else try{if(X=_9(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,RO);let G=$.getContent,V=await G(K,z);if(V instanceof Response)return z.newResponse(V.body,V);if(V){let U=$.mimes&&c9(K,$.mimes)||c9(K);if(z.header("Content-Type",U||"application/octet-stream"),$.precompressed&&(!U||LG.test(U))){let q=new Set(z.req.header("Accept-Encoding")?.split(",").map((H)=>H.trim()));for(let H of EO){if(!q.has(H))continue;let B=await G(K+PG[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 l9=($)=>{return async function(Y,Q){return AG({...$,getContent:async(X)=>{let K=Bun.file(X);return await K.exists()?K:null},join:LO,isDir:async(X)=>{let K;try{K=(await FO(X)).isDirectory()}catch{}return K}})(Y,Q)}};var o9="x-hono-disable-ssg",Xf=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[o9]:"true"}})}catch{return null}})();var{write:mf}=Bun;var AO=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 TG=($)=>{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 x7=($)=>("server"in $.env)?$.env.server:$.env;var TO=TG(($,Z)=>{let Y=x7($);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 DG=($)=>{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 DO(){let{process:$,Deno:Z}=globalThis;return!(typeof Z?.noColor==="boolean"?Z.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}async function IG(){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}})():!DO())}var IO=($)=>{let[Z,Y]=[",","."];return $.map((z)=>z.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Z)).join(Y)},SO=($)=>{let Z=Date.now()-$;return IO([Z<1000?Z+"ms":Math.round(Z/1000)+"s"])},wO=async($)=>{if(await IG())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 SG($,Z,Y,Q,z=0,J){let X=Z==="<--"?`${Z} ${Y} ${Q}`:`${Z} ${Y} ${Q} ${await wO(z)} ${J}`;$(X)}var wG=($=console.log)=>{return async function(Y,Q){let{method:z,url:J}=Y.req,X=J.slice(J.indexOf("/",8));await SG($,"<--",z,X);let K=Date.now();await Q(),await SG($,"-->",z,X,Y.res.status,SO(K))}};c0();class i9{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),e.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 kO={theme:"system",fontSize:"medium",showToolCalls:!0,showCosts:!0,autoScroll:!0,enableSounds:!1};function n9($){let Z=new d9,Y=new Map;Z.use("*",wG()),Z.use("*",DG()),Z.use("/static/*",l9({root:"./src/ui/web"})),Z.get("/",(K)=>{return K.html(fO(f3()))}),Z.get("/api/health",(K)=>K.json({status:"ok"}));function Q(K,G){let V=new i9({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,onApprovalRequired:async(B,N,M)=>{return J(K,{type:"tool_approval_required",payload:{toolCallId:`tool_${Date.now()}`,name:B,input:N,riskLevel:M}}),!0}}),U={chatService:V,settings:{...kO}};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 N=H.data;J(K,{type:"tool_result",payload:{messageId:q,toolCallId:N.id,result:N.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((N)=>N.isActive)||null,H=G.getMessages(),B={currentSession:q,sessions:U,messages:H,isStreaming:!1,model:"claude-sonnet-4-20250514",systemPrompt:$.systemPrompt,totalCostCents:H.reduce((N,M)=>N+(M.usage?.costCents||0),0),settings:V};J(K,{type:"state",payload:B})}return{app:Z,start:()=>{console.log(`
781
+ ${C8("ui.running_at",{url:`http://localhost:${$.port}`})}
782
+ `);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 fO($){let Z=(Y)=>$[Y]||Y;return`<!DOCTYPE html>
773
783
  <html lang="en">
774
784
  <head>
775
785
  <meta charset="UTF-8">
@@ -1880,6 +1890,6 @@ Type /ajuda for commands.`),tX(Y.dataDir))try{let D=await j9(Y.dataDir);if(D.pan
1880
1890
  document.getElementById('input').addEventListener('input', updateSendButton);
1881
1891
  </script>
1882
1892
  </body>
1883
- </html>`}function GO($){let Z=process.platform==="win32"?`start "" "${$}"`:process.platform==="darwin"?`open "${$}"`:`xdg-open "${$}"`;KO(Z,(Y)=>{if(Y)console.error(`Failed to open browser: ${$}`,Y.message)})}async function qG($){let Z=$.port||3847;console.log(`
1884
- ${O8("ui.starting_web")}
1885
- `),u9({port:Z,provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager}).start();let Q=`http://localhost:${Z}`;GO(Q),await new Promise(()=>{})}async function VO(){let $=d9(process.argv.slice(2));if($.help)c9(),process.exit(0);if($.version)console.log(`smolerclaw v${e$()}`),process.exit(0);let Z=CY();if(q3(Z.language),$.model)Z.model=s8($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=r7()}catch(H){console.error("smolerclaw:",H instanceof Error?H.message:H),process.exit(1)}let Q={auth:Y},z=YX(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:J,skills:X,systemPrompt:K,activeSystemPrompt:G,enableTools:V,plugins:q}=await WX(Z,$.session,$.noTools);if(L9(Z.dataDir,J),$.uiMode==="web"){await qG({provider:z,systemPrompt:K,enableTools:V,sessionManager:J,port:$.port});return}let U=!process.stdin.isTTY;if($.print||U)await BX(z,J,K,V,$.prompt,U),process.exit(0);await bK(z,J,Z,Q,X,K,G,V,q,$.prompt)}VO().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
1893
+ </html>`}function yO($){let Z=process.platform==="win32"?`start "" "${$}"`:process.platform==="darwin"?`open "${$}"`:`xdg-open "${$}"`;bO(Z,(Y)=>{if(Y)console.error(`Failed to open browser: ${$}`,Y.message)})}async function kG($){let Z=$.port||3847;console.log(`
1894
+ ${C8("ui.starting_web")}
1895
+ `),n9({port:Z,provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager}).start();let Q=`http://localhost:${Z}`;yO(Q),await new Promise(()=>{})}async function _O(){let $=s9(process.argv.slice(2));if($.help)t9(),process.exit(0);if($.version)console.log(`smolerclaw v${$2()}`),process.exit(0);let Z=AY();if(k3(Z.language),$.model)Z.model=e8($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=t7()}catch(H){console.error("smolerclaw:",H instanceof Error?H.message:H),process.exit(1)}let Q={auth:Y},z=jX(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:J,skills:X,systemPrompt:K,activeSystemPrompt:G,enableTools:V,plugins:U}=await yX(Z,$.session,$.noTools);if(w9(Z.dataDir,J),$.uiMode==="web"){await kG({provider:z,systemPrompt:K,enableTools:V,sessionManager:J,port:$.port});return}let q=!process.stdin.isTTY;if($.print||q)await _X(z,J,K,V,$.prompt,q),process.exit(0);await $G(z,J,Z,Q,X,K,G,V,U,$.prompt)}_O().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});