smolerclaw 1.9.0 → 1.9.1

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 +320 -316
  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 rW=Object.defineProperty;var aW=($)=>$;function sW($,Z){this[$]=aW.bind(null,Z)}var PZ=($,Z)=>{for(var Y in Z)rW($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:sW.bind(Z,Y)})};var Y1=($,Z)=>()=>($&&(Z=$($=0)),Z);var tW=import.meta.require;import{existsSync as YU,appendFileSync as QU,mkdirSync as CL,writeFileSync as zU,unlinkSync as JU}from"fs";import{join as DZ}from"path";import{tmpdir as XU,homedir as KU}from"os";import{randomBytes as VU}from"crypto";function L2($,Z,Y){if(!K8)return;let Q=new Date().toISOString(),z=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
3
+ var UU=Object.defineProperty;var qU=($)=>$;function BU($,Z){this[$]=qU.bind(null,Z)}var G8=($,Z)=>{for(var Y in Z)UU($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:BU.bind(Z,Y)})};var t0=($,Z)=>()=>($&&(Z=$($=0)),Z);var NU=import.meta.require;import{existsSync as EU,appendFileSync as FU,mkdirSync as sL,writeFileSync as LU,unlinkSync as RU}from"fs";import{join as kZ}from"path";import{tmpdir as jU,homedir as PU}from"os";import{randomBytes as AU}from"crypto";function j2($,Z,Y){if(!H8)return;let Q=new Date().toISOString(),z=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
4
4
  `:`[${Q}] [${$}] ${Z}
5
- `;try{QU(WU,z)}catch{}}function yz($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function vz($){let Z=$.replace(/\//g,"\\");return yz(Z)}async function V8($){let Z=X8.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(YU($)){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 q0(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 q0($,Z={}){let{timeout:Y=TZ,cwd:Q,debug:z=K8,sta:J=!1}=Z,X=performance.now(),K=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,V=["powershell",...bz];if(J)V.push("-STA");if(V.push("-Command",K),z)L2("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:Y,cwd:Q,sta:J});let G;try{G=Bun.spawn(V,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(U){let q={stdout:"",stderr:`Failed to spawn PowerShell: ${U instanceof Error?U.message:String(U)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1};if(z)L2("ERROR","Failed to spawn process",{error:q.stderr});return q}let H=!1,W=setTimeout(()=>{H=!0;try{G.kill()}catch{}},Y);try{let[U,q]=await Promise.all([G.stdout instanceof ReadableStream?new Response(G.stdout).text():"",G.stderr instanceof ReadableStream?new Response(G.stderr).text():""]),N=await G.exited;clearTimeout(W);let C=Math.round(performance.now()-X),M={stdout:Z5(U),stderr:Z5(q),exitCode:H?-1:N,duration:C,timedOut:H};if(z)L2(M.exitCode===0?"INFO":"WARN","Command completed",{exitCode:M.exitCode,duration:C,timedOut:H,stdoutLength:M.stdout.length,stderrLength:M.stderr.length});return M}catch(U){clearTimeout(W);let q={stdout:"",stderr:`Execution error: ${U instanceof Error?U.message:String(U)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:H};if(z)L2("ERROR","Execution failed",{error:q.stderr,timedOut:H});return q}}async function xz($,Z={}){let Q=`& ${vz($)}`;return q0(Q,Z)}async function _z($,Z={}){let{timeout:Y=TZ,cwd:Q,debug:z=K8,sta:J=!1}=Z,X=performance.now(),K=VU(4).toString("hex"),V=DZ(XU(),`smolerclaw-${K}.ps1`),G=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
6
- ${$}`;try{zU(V,G,"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)L2("INFO","Executing PowerShell via temp file",{tempPath:V,scriptLength:$.length,timeout:Y,sta:J});let H=["powershell",...bz];if(J)H.push("-STA");H.push("-File",V);let W;try{W=Bun.spawn(H,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(N){return AZ(V),{stdout:"",stderr:`Failed to spawn PowerShell: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let U=!1,q=setTimeout(()=>{U=!0;try{W.kill()}catch{}},Y);try{let[N,C]=await Promise.all([W.stdout instanceof ReadableStream?new Response(W.stdout).text():"",W.stderr instanceof ReadableStream?new Response(W.stderr).text():""]),M=await W.exited;clearTimeout(q),AZ(V);let F=Math.round(performance.now()-X),T={stdout:Z5(N),stderr:Z5(C),exitCode:U?-1:M,duration:F,timedOut:U};if(z)L2(T.exitCode===0?"INFO":"WARN","File command completed",{exitCode:T.exitCode,duration:F,timedOut:U});return T}catch(N){return clearTimeout(q),AZ(V),{stdout:"",stderr:`Execution error: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:U}}}function AZ($){try{JU($)}catch{}}async function IZ($,Z={}){let{timeout:Y=TZ,cwd:Q,debug:z=K8}=Z,J=performance.now();if(z)L2("INFO","Executing command",{args:$,timeout:Y,cwd:Q});let X;try{X=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(G){return{stdout:"",stderr:`Failed to spawn: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-J),timedOut:!1}}let K=!1,V=setTimeout(()=>{K=!0;try{X.kill()}catch{}},Y);try{let[G,H]=await Promise.all([X.stdout instanceof ReadableStream?new Response(X.stdout).text():"",X.stderr instanceof ReadableStream?new Response(X.stderr).text():""]),W=await X.exited;return clearTimeout(V),{stdout:Z5(G),stderr:Z5(H),exitCode:K?-1:W,duration:Math.round(performance.now()-J),timedOut:K}}catch(G){return clearTimeout(V),{stdout:"",stderr:`Execution error: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-J),timedOut:K}}}async function wZ($,Z={}){return q0($,{...Z,sta:!0})}async function O1($,Z,Y=[],Q={}){let z=["schtasks",`/${$}`,"/TN",Z,...Y],J=Q.timeout??1e4;return IZ(z,{...Q,timeout:J})}async function SZ($,Z,Y={}){let Q=yz($),z=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return q0(z,Y)}async function hz($,Z={}){let Y=vz($);return q0(`Invoke-Item ${Y}`,Z)}async function m1($,Z,Y={}){let Q=fz($),z=fz(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 q0(J,{...Y,timeout:X})}async function G8($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await q0(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function gz($=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 q0(Y,Z)}function Z5($){let Z=$.replace(GU,"");if(Z.length>kz)return Z.slice(0,kz)+`
7
- ... (truncated, ${Z.length} total chars)`;return Z}function fz($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function mz($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var TZ=15000,kz=1e5,GU,HU,WU,bz,K8=!1,X8;var Q1=Y1(()=>{GU=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,HU=DZ(KU(),".smolerclaw","logs"),WU=DZ(HU,"windows-executor.log"),bz=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];X8=new Map});import{existsSync as UU}from"fs";function Y5(){if(R)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&UU($))return[$,"-c"];return["bash","-c"]}function uz(){if(R)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function qU($){if(R)return(await V8($)).exists;try{return(await IZ(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function dz(){if(H8!==null)return H8;return H8=await qU("rg"),H8}function kZ($){let Z=$.replace(/\\/g,"/");return l5.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var R,pz,AL,H8=null,l5;var Z0=Y1(()=>{Q1();R=process.platform==="win32",pz=process.platform==="darwin",AL=process.platform==="linux";l5=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as BU}from"events";class cz{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new BU,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 p1($){if(!fZ)fZ=new cz($);return fZ}function G0($,Z){z0.emit($,Z)}var fZ=null,z0;var z1=Y1(()=>{z0=p1()});import{existsSync as C1,mkdirSync as bZ,readFileSync as U8,writeFileSync as o5,renameSync as lz,statSync as NU}from"fs";import{join as f0,dirname as oz,relative as OU}from"path";import{createHash as CU,randomUUID as iz}from"crypto";function tz($,Z){if(M1=$,sz=Z,B0=f0($,".backup"),EU(),vZ=!0,R2=C1(f0(B0,".git")),R2)yZ=RU()}function i5(){return vZ}function P($,Z){let Y=oz($);if(!C1(Y))bZ(Y,{recursive:!0});let Q=f0(Y,`.smolerclaw-${iz().slice(0,8)}.tmp`);o5(Q,Z),lz(Q,$);let z=!1;if(vZ){let X=LU($);if(X&&q8.includes(X))MU(X,Z),z=!0}let J={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:z,timestamp:Date.now()};z0.emit("file:saved",J)}function ez($){return CU("sha256").update($).digest("hex")}function MU($,Z){let Y=ez(Z),Q=new Date().toISOString(),z=Buffer.byteLength(Z,"utf-8");u1=[...u1.filter((J)=>J.file!==$),{file:$,sha256:Y,size:z,updatedAt:Q}],FU()}function EU(){let $=f0(M1,rz);if(!C1($)){u1=[];return}try{let Z=JSON.parse(U8($,"utf-8"));if(Z.version!==nz){u1=[];return}u1=Z.checksums||[]}catch{u1=[]}}function FU(){if(!M1)return;let $=f0(M1,rz),Z={checksums:u1,version:nz},Y=f0(M1,`.vault-${iz().slice(0,8)}.tmp`);o5(Y,JSON.stringify(Z,null,2)),lz(Y,$)}function LU($){try{let Z=OU(M1,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function B8(){let $=[],Z=0;for(let Y of q8){let Q=f0(M1,Y),z=C1(Q);if(!z){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let J=0,X="";try{let G=NU(Q);J=G.size,X=G.mtime.toISOString()}catch{}let K=u1.find((G)=>G.file===Y),V=null;if(K)try{let G=U8(Q,"utf-8");if(V=ez(G)===K.sha256,!V)Z++}catch{V=!1,Z++}$.push({file:Y,exists:z,checksumValid:V,size:J,lastModified:X})}return{files:$,lastBackup:yZ,backupEnabled:R2,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function N8($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${q8.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
5
+ `;try{FU(IU,z)}catch{}}function oz($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function iz($){let Z=$.replace(/\//g,"\\");return oz(Z)}async function U8($){let Z=W8.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(EU($)){let z={exists:!0,path:$};return W8.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 B0(Q,{timeout:5000});if(z.exitCode===0&&z.stdout.trim()){let X={exists:!0,path:z.stdout.trim()};return W8.set($.toLowerCase(),X),X}let J={exists:!1,error:`'${$}' not found in PATH or App Paths`};return W8.set($.toLowerCase(),J),J}catch(z){return{exists:!1,error:z instanceof Error?z.message:String(z)}}}async function B0($,Z={}){let{timeout:Y=fZ,cwd:Q,debug:z=H8,sta:J=!1}=Z,X=performance.now(),K=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,V=["powershell",...lz];if(J)V.push("-STA");if(V.push("-Command",K),z)j2("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:Y,cwd:Q,sta:J});let G;try{G=Bun.spawn(V,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(U){let q={stdout:"",stderr:`Failed to spawn PowerShell: ${U instanceof Error?U.message:String(U)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1};if(z)j2("ERROR","Failed to spawn process",{error:q.stderr});return q}let W=!1,H=setTimeout(()=>{W=!0;try{G.kill()}catch{}},Y);try{let[U,q]=await Promise.all([G.stdout instanceof ReadableStream?new Response(G.stdout).text():"",G.stderr instanceof ReadableStream?new Response(G.stderr).text():""]),N=await G.exited;clearTimeout(H);let C=Math.round(performance.now()-X),M={stdout:Q5(U),stderr:Q5(q),exitCode:W?-1:N,duration:C,timedOut:W};if(z)j2(M.exitCode===0?"INFO":"WARN","Command completed",{exitCode:M.exitCode,duration:C,timedOut:W,stdoutLength:M.stdout.length,stderrLength:M.stderr.length});return M}catch(U){clearTimeout(H);let q={stdout:"",stderr:`Execution error: ${U instanceof Error?U.message:String(U)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:W};if(z)j2("ERROR","Execution failed",{error:q.stderr,timedOut:W});return q}}async function nz($,Z={}){let Q=`& ${iz($)}`;return B0(Q,Z)}async function rz($,Z={}){let{timeout:Y=fZ,cwd:Q,debug:z=H8,sta:J=!1}=Z,X=performance.now(),K=AU(4).toString("hex"),V=kZ(jU(),`smolerclaw-${K}.ps1`),G=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
6
+ ${$}`;try{LU(V,G,"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)j2("INFO","Executing PowerShell via temp file",{tempPath:V,scriptLength:$.length,timeout:Y,sta:J});let W=["powershell",...lz];if(J)W.push("-STA");W.push("-File",V);let H;try{H=Bun.spawn(W,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(N){return wZ(V),{stdout:"",stderr:`Failed to spawn PowerShell: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let U=!1,q=setTimeout(()=>{U=!0;try{H.kill()}catch{}},Y);try{let[N,C]=await Promise.all([H.stdout instanceof ReadableStream?new Response(H.stdout).text():"",H.stderr instanceof ReadableStream?new Response(H.stderr).text():""]),M=await H.exited;clearTimeout(q),wZ(V);let F=Math.round(performance.now()-X),T={stdout:Q5(N),stderr:Q5(C),exitCode:U?-1:M,duration:F,timedOut:U};if(z)j2(T.exitCode===0?"INFO":"WARN","File command completed",{exitCode:T.exitCode,duration:F,timedOut:U});return T}catch(N){return clearTimeout(q),wZ(V),{stdout:"",stderr:`Execution error: ${N instanceof Error?N.message:String(N)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:U}}}function wZ($){try{RU($)}catch{}}async function bZ($,Z={}){let{timeout:Y=fZ,cwd:Q,debug:z=H8}=Z,J=performance.now();if(z)j2("INFO","Executing command",{args:$,timeout:Y,cwd:Q});let X;try{X=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(G){return{stdout:"",stderr:`Failed to spawn: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-J),timedOut:!1}}let K=!1,V=setTimeout(()=>{K=!0;try{X.kill()}catch{}},Y);try{let[G,W]=await Promise.all([X.stdout instanceof ReadableStream?new Response(X.stdout).text():"",X.stderr instanceof ReadableStream?new Response(X.stderr).text():""]),H=await X.exited;return clearTimeout(V),{stdout:Q5(G),stderr:Q5(W),exitCode:K?-1:H,duration:Math.round(performance.now()-J),timedOut:K}}catch(G){return clearTimeout(V),{stdout:"",stderr:`Execution error: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-J),timedOut:K}}}async function yZ($,Z={}){return B0($,{...Z,sta:!0})}async function M1($,Z,Y=[],Q={}){let z=["schtasks",`/${$}`,"/TN",Z,...Y],J=Q.timeout??1e4;return bZ(z,{...Q,timeout:J})}async function vZ($,Z,Y={}){let Q=oz($),z=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return B0(z,Y)}async function az($,Z={}){let Y=iz($);return B0(`Invoke-Item ${Y}`,Z)}async function u1($,Z,Y={}){let Q=cz($),z=cz(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 B0(J,{...Y,timeout:X})}async function q8($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await B0(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function sz($=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 B0(Y,Z)}function Q5($){let Z=$.replace(DU,"");if(Z.length>dz)return Z.slice(0,dz)+`
7
+ ... (truncated, ${Z.length} total chars)`;return Z}function cz($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function tz($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var fZ=15000,dz=1e5,DU,TU,IU,lz,H8=!1,W8;var J1=t0(()=>{DU=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,TU=kZ(PU(),".smolerclaw","logs"),IU=kZ(TU,"windows-executor.log"),lz=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];W8=new Map});import{existsSync as SU}from"fs";function z5(){if(R)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&SU($))return[$,"-c"];return["bash","-c"]}function $J(){if(R)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function wU($){if(R)return(await U8($)).exists;try{return(await bZ(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function ZJ(){if(B8!==null)return B8;return B8=await wU("rg"),B8}function xZ($){let Z=$.replace(/\\/g,"/");return i5.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var R,ez,JR,B8=null,i5;var Y0=t0(()=>{J1();R=process.platform==="win32",ez=process.platform==="darwin",JR=process.platform==="linux";i5=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as kU}from"events";class YJ{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new kU,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 d1($){if(!_Z)_Z=new YJ($);return _Z}function W0($,Z){J0.emit($,Z)}var _Z=null,J0;var X1=t0(()=>{J0=d1()});import{existsSync as E1,mkdirSync as hZ,readFileSync as O8,writeFileSync as n5,renameSync as QJ,statSync as fU}from"fs";import{join as y0,dirname as zJ,relative as bU}from"path";import{createHash as yU,randomUUID as JJ}from"crypto";function WJ($,Z){if(F1=$,GJ=Z,N0=y0($,".backup"),xU(),mZ=!0,P2=E1(y0(N0,".git")),P2)gZ=gU()}function r5(){return mZ}function j($,Z){let Y=zJ($);if(!E1(Y))hZ(Y,{recursive:!0});let Q=y0(Y,`.smolerclaw-${JJ().slice(0,8)}.tmp`);n5(Q,Z),QJ(Q,$);let z=!1;if(mZ){let X=hU($);if(X&&C8.includes(X))vU(X,Z),z=!0}let J={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:z,timestamp:Date.now()};J0.emit("file:saved",J)}function HJ($){return yU("sha256").update($).digest("hex")}function vU($,Z){let Y=HJ(Z),Q=new Date().toISOString(),z=Buffer.byteLength(Z,"utf-8");c1=[...c1.filter((J)=>J.file!==$),{file:$,sha256:Y,size:z,updatedAt:Q}],_U()}function xU(){let $=y0(F1,KJ);if(!E1($)){c1=[];return}try{let Z=JSON.parse(O8($,"utf-8"));if(Z.version!==XJ){c1=[];return}c1=Z.checksums||[]}catch{c1=[]}}function _U(){if(!F1)return;let $=y0(F1,KJ),Z={checksums:c1,version:XJ},Y=y0(F1,`.vault-${JJ().slice(0,8)}.tmp`);n5(Y,JSON.stringify(Z,null,2)),QJ(Y,$)}function hU($){try{let Z=bU(F1,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function M8(){let $=[],Z=0;for(let Y of C8){let Q=y0(F1,Y),z=E1(Q);if(!z){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let J=0,X="";try{let G=fU(Q);J=G.size,X=G.mtime.toISOString()}catch{}let K=c1.find((G)=>G.file===Y),V=null;if(K)try{let G=O8(Q,"utf-8");if(V=HJ(G)===K.sha256,!V)Z++}catch{V=!1,Z++}$.push({file:Y,exists:z,checksumValid:V,size:J,lastModified:X})}return{files:$,lastBackup:gZ,backupEnabled:P2,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function E8($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${C8.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(!M1)return"Error: vault not initialized.";if(!C1(B0))bZ(B0,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
10
- `);if(o5(f0(B0,".gitignore"),$),!C1(f0(B0,".git"))){let Z=await d1(["git","init","-b",az],B0);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await d1(["git","config","user.email","vault@smolerclaw.local"],B0),await d1(["git","config","user.name","smolerclaw-vault"],B0)}return R2=!0,"Shadow backup inicializado."}async function Q5($){if(!R2)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let K of q8){let V=f0(M1,K);if(!C1(V))continue;let G=f0(B0,K),H=oz(G);if(!C1(H))bZ(H,{recursive:!0});o5(G,U8(V,"utf-8"))}let Y=f0(sz,"config.json");if(C1(Y))o5(f0(B0,"config.json"),U8(Y,"utf-8"));if(await d1(["git","add","-A"],B0),!(await d1(["git","status","--porcelain"],B0)).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 z0.emit("task:completed",K),"Nenhuma mudanca para backup."}let z=$||`backup ${new Date().toISOString().slice(0,19)}`,J=await d1(["git","commit","-m",z],B0);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 z0.emit("task:completed",K),`Backup commit falhou: ${J.stderr}`}yZ=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 z0.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 z0.emit("task:completed",z),`Backup falhou: ${Q}`}}async function C8(){if(!R2)return"Backup nao ativado.";if(!(await d1(["git","remote","-v"],B0)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await d1(["git","push","-u","origin",az],B0);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function RU(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:B0,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function d1($,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 $J($=30){if(xZ(),!R2)return;W8=setInterval(()=>{Q5("auto-backup").catch(()=>{})},$*60*1000)}function xZ(){if(W8)clearInterval(W8),W8=null}var nz=1,rz="vault-checksums.json",az="smolerclaw-backup",q8,M1="",sz="",u1,B0="",R2=!1,yZ=null,vZ=!1,W8=null;var h=Y1(()=>{z1();q8=["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"],u1=[]});var d4={};PZ(d4,{searchInvestigations:()=>g4,openInvestigation:()=>b4,listInvestigations:()=>h4,initInvestigations:()=>f4,getInvestigation:()=>_4,generateReport:()=>m4,formatInvestigationList:()=>w6,formatInvestigationDetail:()=>p4,formatEvidenceDetail:()=>cB,collectEvidence:()=>y4,closeInvestigation:()=>x4,addFinding:()=>v4});import{existsSync as n7,mkdirSync as gB,readFileSync as mB}from"fs";import{join as pB}from"path";import{randomUUID as uB}from"crypto";function I6(){P(a7(),JSON.stringify(L0,null,2))}function dB(){let $=a7();if(!n7($)){L0=[];return}try{L0=JSON.parse(mB($,"utf-8"))}catch{L0=[]}}function f4($){if(r7=$,!n7($))gB($,{recursive:!0});dB()}function b4($,Z,Y,Q=[]){let z=new Date().toISOString(),J={id:u4(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((X)=>X.toLowerCase()),evidence:[],findings:[],created:z,updated:z};return L0=[...L0,J],I6(),J}function y4($,Z,Y,Q,z){let J=a$($);if(!J)return null;let X=Q.trim();if(X.length>i7)X=X.slice(0,i7)+`
11
- ...(truncated, ${Q.length} total chars)`;let K={id:u4(),source:Z,label:Y.trim(),content:X,path:z?.trim(),timestamp:new Date().toISOString()},V={...J,evidence:[...J.evidence,K],status:J.status==="aberta"?"em_andamento":J.status,updated:new Date().toISOString()};return L0=L0.map((G)=>G.id===J.id?V:G),I6(),K}function v4($,Z,Y,Q,z=[]){let J=a$($);if(!J)return null;let X=z.filter((G)=>J.evidence.some((H)=>H.id===G)),K={id:u4(),severity:Z,title:Y.trim(),description:Q.trim(),evidence_ids:X,timestamp:new Date().toISOString()},V={...J,findings:[...J.findings,K],updated:new Date().toISOString()};return L0=L0.map((G)=>G.id===J.id?V:G),I6(),K}function x4($,Z,Y){let Q=a$($);if(!Q)return null;let z={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return L0=L0.map((J)=>J.id===Q.id?z:J),I6(),z}function _4($){return a$($)}function h4($,Z,Y=20){let Q=[...L0];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 g4($){let Z=$.toLowerCase();return L0.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 m4($){let Z=a$($);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 V=X.content.length>2000?X.content.slice(0,2000)+`
12
- ... (truncado)`:X.content;Y.push("```"),Y.push(V),Y.push("```")}}if(Z.findings.length>0){let X=[...Z.findings].sort((K,V)=>(J[K.severity]??4)-(J[V.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let K of X){let V=t7(K.severity);if(Y.push(""),Y.push(`### ${V} ${K.title}`),Y.push(K.description),K.evidence_ids.length>0)Y.push(`- Evidencias: ${K.evidence_ids.join(", ")}`)}}if(Z.summary)Y.push(""),Y.push("## Resumo"),Y.push(Z.summary);if(Z.recommendations)Y.push(""),Y.push("## Recomendacoes"),Y.push(Z.recommendations);return Y.join(`
13
- `)}function w6($){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=s7(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 F8(){if(!F1)return"Error: vault not initialized.";if(!E1(N0))hZ(N0,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
10
+ `);if(n5(y0(N0,".gitignore"),$),!E1(y0(N0,".git"))){let Z=await l1(["git","init","-b",VJ],N0);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await l1(["git","config","user.email","vault@smolerclaw.local"],N0),await l1(["git","config","user.name","smolerclaw-vault"],N0)}return P2=!0,"Shadow backup inicializado."}async function J5($){if(!P2)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let K of C8){let V=y0(F1,K);if(!E1(V))continue;let G=y0(N0,K),W=zJ(G);if(!E1(W))hZ(W,{recursive:!0});n5(G,O8(V,"utf-8"))}let Y=y0(GJ,"config.json");if(E1(Y))n5(y0(N0,"config.json"),O8(Y,"utf-8"));if(await l1(["git","add","-A"],N0),!(await l1(["git","status","--porcelain"],N0)).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 J0.emit("task:completed",K),"Nenhuma mudanca para backup."}let z=$||`backup ${new Date().toISOString().slice(0,19)}`,J=await l1(["git","commit","-m",z],N0);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 J0.emit("task:completed",K),`Backup commit falhou: ${J.stderr}`}gZ=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 J0.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 J0.emit("task:completed",z),`Backup falhou: ${Q}`}}async function L8(){if(!P2)return"Backup nao ativado.";if(!(await l1(["git","remote","-v"],N0)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await l1(["git","push","-u","origin",VJ],N0);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function gU(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:N0,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function l1($,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 UJ($=30){if(pZ(),!P2)return;N8=setInterval(()=>{J5("auto-backup").catch(()=>{})},$*60*1000)}function pZ(){if(N8)clearInterval(N8),N8=null}var XJ=1,KJ="vault-checksums.json",VJ="smolerclaw-backup",C8,F1="",GJ="",c1,N0="",P2=!1,gZ=null,mZ=!1,N8=null;var g=t0(()=>{X1();C8=["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"],c1=[]});var n4={};G8(n4,{searchInvestigations:()=>c4,openInvestigation:()=>h4,listInvestigations:()=>d4,initInvestigations:()=>_4,getInvestigation:()=>u4,generateReport:()=>l4,formatInvestigationList:()=>b6,formatInvestigationDetail:()=>o4,formatEvidenceDetail:()=>KN,collectEvidence:()=>g4,closeInvestigation:()=>p4,addFinding:()=>m4});import{existsSync as XX,mkdirSync as YN,readFileSync as QN}from"fs";import{join as zN}from"path";import{randomUUID as JN}from"crypto";function f6(){j(VX(),JSON.stringify(R0,null,2))}function XN(){let $=VX();if(!XX($)){R0=[];return}try{R0=JSON.parse(QN($,"utf-8"))}catch{R0=[]}}function _4($){if(KX=$,!XX($))YN($,{recursive:!0});XN()}function h4($,Z,Y,Q=[]){let z=new Date().toISOString(),J={id:i4(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((X)=>X.toLowerCase()),evidence:[],findings:[],created:z,updated:z};return R0=[...R0,J],f6(),J}function g4($,Z,Y,Q,z){let J=t$($);if(!J)return null;let X=Q.trim();if(X.length>JX)X=X.slice(0,JX)+`
11
+ ...(truncated, ${Q.length} total chars)`;let K={id:i4(),source:Z,label:Y.trim(),content:X,path:z?.trim(),timestamp:new Date().toISOString()},V={...J,evidence:[...J.evidence,K],status:J.status==="aberta"?"em_andamento":J.status,updated:new Date().toISOString()};return R0=R0.map((G)=>G.id===J.id?V:G),f6(),K}function m4($,Z,Y,Q,z=[]){let J=t$($);if(!J)return null;let X=z.filter((G)=>J.evidence.some((W)=>W.id===G)),K={id:i4(),severity:Z,title:Y.trim(),description:Q.trim(),evidence_ids:X,timestamp:new Date().toISOString()},V={...J,findings:[...J.findings,K],updated:new Date().toISOString()};return R0=R0.map((G)=>G.id===J.id?V:G),f6(),K}function p4($,Z,Y){let Q=t$($);if(!Q)return null;let z={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return R0=R0.map((J)=>J.id===Q.id?z:J),f6(),z}function u4($){return t$($)}function d4($,Z,Y=20){let Q=[...R0];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 c4($){let Z=$.toLowerCase();return R0.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 l4($){let Z=t$($);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 V=X.content.length>2000?X.content.slice(0,2000)+`
12
+ ... (truncado)`:X.content;Y.push("```"),Y.push(V),Y.push("```")}}if(Z.findings.length>0){let X=[...Z.findings].sort((K,V)=>(J[K.severity]??4)-(J[V.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let K of X){let V=WX(K.severity);if(Y.push(""),Y.push(`### ${V} ${K.title}`),Y.push(K.description),K.evidence_ids.length>0)Y.push(`- Evidencias: ${K.evidence_ids.join(", ")}`)}}if(Z.summary)Y.push(""),Y.push("## Resumo"),Y.push(Z.summary);if(Z.recommendations)Y.push(""),Y.push("## Recomendacoes"),Y.push(Z.recommendations);return Y.join(`
13
+ `)}function b6($){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=GX(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 p4($){let Z=(z)=>new Date(z).toLocaleDateString("pt-BR"),Y=s7($.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 o4($){let Z=(z)=>new Date(z).toLocaleDateString("pt-BR"),Y=GX($.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(` ${t7(z.severity)} ${z.title}`);if($.summary)Q.push(`
17
+ Conclusoes: ${$.findings.length}`);for(let z of $.findings)Q.push(` ${WX(z.severity)} ${z.title}`);if($.summary)Q.push(`
18
18
  Resumo: ${$.summary}`);if($.recommendations)Q.push(`Recomendacoes: ${$.recommendations}`);return Q.join(`
19
- `)}function cB($){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 KN($){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 a$($){let Z=$.toLowerCase().trim(),Y=L0.find((z)=>z.id===Z);if(Y)return Y;return L0.filter((z)=>z.title.toLowerCase().includes(Z)).sort((z,J)=>new Date(J.updated).getTime()-new Date(z.updated).getTime())[0]||null}function s7($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function t7($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function u4(){return uB().slice(0,8)}var r7="",L0,a7=()=>pB(r7,"investigations.json"),i7=50000;var s$=Y1(()=>{h();L0=[]});var jK={};PZ(jK,{openUrl:()=>V1,openFile:()=>g2,openApp:()=>S1,getSystemInfo:()=>m2,getRunningApps:()=>Z3,getOutlookEvents:()=>G1,getKnownApps:()=>qY,getDateTimeInfo:()=>p2});function UY($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(AO.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function S1($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=WY[Y];if(!Q){let z=Object.keys(WY).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=UY(Z,"argument");if(z)return z}if(!R)return"Error: this command is only available on Windows.";if(!Q.includes(":")){let z=await V8(Q);if(!z.exists)return`Error: ${Q} not found. ${z.error||""}`}try{let z=await SZ(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 V1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=UY($,"URL");if(Z)return Z;if(!R)return"Error: this command is only available on Windows.";try{let Y=await SZ($);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 g2($){let Z=UY($,"file path");if(Z)return Z;if(!R)return"Error: this command is only available on Windows.";try{let Y=await hz($);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 Z3(){if(!R)return"Error: this command is only available on Windows.";try{let $=await gz(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 m2(){if(!R)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 q0($.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 p2(){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 V=$.getHours();if(V>=8&&V<18)Z.push("Status: horario comercial");else if(V>=18&&V<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
22
- `)}async function G1(){if(!R)return"Outlook integration only available on Windows.";let $=await DO();if($.success)return $.data;let Z=await TO();if(Z.success)return Z.data;return Z.data||$.data||"Calendario nao disponivel."}async function DO(){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 q0($,{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 TO(){try{let Z=await _z(`
21
+ `)}function t$($){let Z=$.toLowerCase().trim(),Y=R0.find((z)=>z.id===Z);if(Y)return Y;return R0.filter((z)=>z.title.toLowerCase().includes(Z)).sort((z,J)=>new Date(J.updated).getTime()-new Date(z.updated).getTime())[0]||null}function GX($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function WX($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function i4(){return JN().slice(0,8)}var KX="",R0,VX=()=>zN(KX,"investigations.json"),JX=50000;var e$=t0(()=>{g();R0=[]});var vK={};G8(vK,{openUrl:()=>W1,openFile:()=>p2,openApp:()=>f1,getSystemInfo:()=>u2,getRunningApps:()=>Q3,getOutlookEvents:()=>H1,getKnownApps:()=>MY,getDateTimeInfo:()=>d2});function CY($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(uO.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function f1($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=OY[Y];if(!Q){let z=Object.keys(OY).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=CY(Z,"argument");if(z)return z}if(!R)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 vZ(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 W1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=CY($,"URL");if(Z)return Z;if(!R)return"Error: this command is only available on Windows.";try{let Y=await vZ($);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 p2($){let Z=CY($,"file path");if(Z)return Z;if(!R)return"Error: this command is only available on Windows.";try{let Y=await az($);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 Q3(){if(!R)return"Error: this command is only available on Windows.";try{let $=await sz(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 u2(){if(!R)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 B0($.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 d2(){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 V=$.getHours();if(V>=8&&V<18)Z.push("Status: horario comercial");else if(V>=18&&V<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
22
+ `)}async function H1(){if(!R)return"Outlook integration only available on Windows.";let $=await dO();if($.success)return $.data;let Z=await cO();if(Z.success)return Z.data;return Z.data||$.data||"Calendario nao disponivel."}async function dO(){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 B0($,{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 cO(){try{let Z=await rz(`
24
24
  try {
25
25
  Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction Stop
26
26
 
@@ -88,8 +88,11 @@ 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 qY(){return Object.keys(WY)}var AO,WY;var J2=Y1(()=>{Z0();Q1();AO=/[";`$\n\r|&<>{}()]/;WY={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{existsSync as y3,readFileSync as CM}from"fs";import{join as U1}from"path";function LM(){let $=U1(process.cwd(),"node_modules",".bin"),Z=U1($,"gws.exe");if(y3(Z))return Z;let Y=U1($,"gws.cmd");if(y3(Y))return Y;let Q=U1($,"gws.bunx");if(y3(Q))return Q;let z=U1($,"gws");if(y3(z))return z;return"gws"}async function v3(){if(b3!==null)return b3;e9=LM();try{let $=Bun.spawn([e9,"--version"],{stdout:"pipe",stderr:"pipe",env:qQ()}),Z=setTimeout(()=>$.kill(),5000);await new Response($.stdout).text(),await $.exited,clearTimeout(Z),b3=$.exitCode===0}catch{b3=!1}return b3}async function I0($,Z={}){let Y=Z.timeout??MM;if(!await v3())return{success:!1,data:null,error:"GWS CLI not found. Run: npm install -g @googleworkspace/cli",raw:"",duration:0};let z=[e9,...$],J=performance.now();try{let X=Bun.spawn(z,{stdout:"pipe",stderr:"pipe",env:qQ()}),K=setTimeout(()=>X.kill(),Y),[V,G]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]);await X.exited,clearTimeout(K);let H=Math.round(performance.now()-J),W=V.trim().slice(0,EM);if(X.exitCode!==0){let U=G.trim()||W||"Unknown error";if(PM(U))return{success:!1,data:null,error:"Not logged in. Run /gws login first.",raw:U,duration:H};return{success:!1,data:null,error:U,raw:U,duration:H}}if(W)try{return{success:!0,data:JSON.parse(W),error:null,raw:W,duration:H}}catch{return{success:!0,data:W,error:null,raw:W,duration:H}}return{success:!0,data:null,error:null,raw:W,duration:H}}catch(X){let K=Math.round(performance.now()-J),V=X instanceof Error?X.message:String(X);return{success:!1,data:null,error:V.includes("timed out")||V.includes("killed")?`Command timed out after ${Y}ms`:V,raw:"",duration:K}}}async function $Z($,Z,Y=180000){if(!await v3())return{success:!1,exitCode:1,output:"GWS CLI not found."};let z=[e9,...$],J=[];try{let X=Bun.spawn(z,{stdout:"pipe",stderr:"pipe",env:qQ()}),K=setTimeout(()=>X.kill(),Y),V=new TextDecoder,G=(async()=>{let W=X.stderr.getReader();while(!0){let{done:U,value:q}=await W.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})(),H=(async()=>{let W=X.stdout.getReader();while(!0){let{done:U,value:q}=await W.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})();return await Promise.all([G,H]),await X.exited,clearTimeout(K),{success:X.exitCode===0,exitCode:X.exitCode??1,output:J.join("")}}catch{return{success:!1,exitCode:1,output:J.join("")}}}function RM(){if(W2!==void 0)return W2;let $=jM();for(let Z of $){if(!y3(Z))continue;try{let Y=CM(Z,"utf-8"),Q=JSON.parse(Y),z=Q.installed??Q.web;if(z?.client_id&&z?.client_secret)return W2={clientId:String(z.client_id),clientSecret:String(z.client_secret)},W2;if(Q.client_id&&Q.client_secret)return W2={clientId:String(Q.client_id),clientSecret:String(Q.client_secret)},W2}catch{}}return W2=null,null}function jM(){let $=[];if(process.platform==="win32"){let Q=process.env.APPDATA??U1(process.env.USERPROFILE??"","AppData","Roaming");$.push(U1(Q,"gws","client_secret.json"));let z=process.env.USERPROFILE??process.env.HOME??"";$.push(U1(z,".config","gws","client_secret.json"))}else{let Q=process.env.HOME??"/root";$.push(U1(Q,".config","gws","client_secret.json"))}let Z=process.env.GOOGLE_WORKSPACE_CLI_CONFIG_DIR;if(Z)$.push(U1(Z,"client_secret.json"));let Y=process.env.GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE;if(Y)$.push(Y);return $}function qQ(){let $={...process.env};if(!$.GOOGLE_WORKSPACE_CLI_CLIENT_ID||!$.GOOGLE_WORKSPACE_CLI_CLIENT_SECRET){let Z=RM();if(Z)$.GOOGLE_WORKSPACE_CLI_CLIENT_ID=Z.clientId,$.GOOGLE_WORKSPACE_CLI_CLIENT_SECRET=Z.clientSecret}if(!$.GOOGLE_WORKSPACE_CLI_TOKEN&&UQ)$.GOOGLE_WORKSPACE_CLI_TOKEN=UQ;return $}function BQ($){UQ=$}function x3(){W2=void 0}function PM($){return FM.some((Z)=>Z.test($))}var MM=30000,EM=200000,FM,b3=null,e9="gws",W2=void 0,UQ=null;var a2=Y1(()=>{FM=[/not authenticated/i,/no credentials/i,/token.*expired/i,/login required/i,/auth.*required/i]});var XG;var KG=Y1(()=>{XG={gmail:120000,calendar:300000,drive:300000,status:60000}});function y5($){let Z=U2.get($);if(!Z)return null;if(Date.now()>Z.expiresAt)return U2.delete($),null;return Z.data}function s2($,Z,Y,Q){let z=Q??XG[Y]??300000;U2.set($,{data:Z,expiresAt:Date.now()+z,key:$})}function _3(){U2.clear()}function NQ(){let $=Date.now();for(let[Z,Y]of U2)if($>Y.expiresAt)U2.delete(Z);return{size:U2.size,keys:[...U2.keys()]}}var U2;var t2=Y1(()=>{KG();U2=new Map});var HG={};PZ(HG,{searchDriveFiles:()=>x5,listDriveFiles:()=>h1,formatDriveFileList:()=>$1});function i0($,Z=""){if($===void 0||$===null)return Z;return String($)}function pM($){if($===0)return"-";let Z=["B","KB","MB","GB"],Y=Math.floor(Math.log($)/Math.log(1024));return`${($/Math.pow(1024,Y)).toFixed(1)} ${Z[Y]??"B"}`}async function h1($,Z={}){let Y=`drive:files:${$??"root"}`;if(!Z.fresh){let K=y5(Y);if(K)return{success:!0,data:K,error:null,raw:"",duration:0}}let Q=$?`'${$}' in parents and trashed = false`:"'root' in parents and trashed = false",z=await I0(["drive","files","list","--params",JSON.stringify({q:Q,pageSize:30,fields:"files(id,name,mimeType,size,modifiedTime,webViewLink,parents)",orderBy:"modifiedTime desc"})]);if(!z.success)return z;let X=((z.data&&typeof z.data==="object"&&"files"in z.data?z.data.files:Array.isArray(z.data)?z.data:[])??[]).map((K)=>{let V=K;return{id:i0(V.id),name:i0(V.name,"(unnamed)"),mimeType:i0(V.mimeType),size:typeof V.size==="number"?V.size:parseInt(i0(V.size,"0"),10),modifiedTime:i0(V.modifiedTime),webViewLink:i0(V.webViewLink),parents:Array.isArray(V.parents)?V.parents.map(String):[]}});return s2(Y,X,"drive"),{success:!0,data:X,error:null,raw:z.raw,duration:z.duration}}async function x5($){let Z=await I0(["drive","files","list","--params",JSON.stringify({q:`name contains '${$.replace(/'/g,"\\'")}' and trashed = false`,pageSize:20,fields:"files(id,name,mimeType,size,modifiedTime,webViewLink,parents)",orderBy:"modifiedTime desc"})]);if(!Z.success)return Z;return{success:!0,data:((Z.data&&typeof Z.data==="object"&&"files"in Z.data?Z.data.files:Array.isArray(Z.data)?Z.data:[])??[]).map((z)=>{let J=z;return{id:i0(J.id),name:i0(J.name,"(unnamed)"),mimeType:i0(J.mimeType),size:typeof J.size==="number"?J.size:parseInt(i0(J.size,"0"),10),modifiedTime:i0(J.modifiedTime),webViewLink:i0(J.webViewLink),parents:Array.isArray(J.parents)?J.parents.map(String):[]}}),error:null,raw:Z.raw,duration:Z.duration}}function $1($){if($.length===0)return"Nenhum arquivo encontrado.";let Z=["--- Drive ---"];for(let Y of $){let Q=Y.mimeType==="application/vnd.google-apps.folder",z=Q?"[D]":"[F]",J=Q?"":` (${pM(Y.size)})`,X=Y.modifiedTime?new Date(Y.modifiedTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${z} ${Y.name}${J} ${X}`)}return Z.push("--------------------"),Z.join(`
92
- `)}var _5=Y1(()=>{a2();t2()});import{readFileSync as eW}from"fs";import{join as $U,dirname as ZU}from"path";function wz($){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)d5("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)d5("--session requires a value");break;case"--max-tokens":let J=Number($[++Q]);if(!J||J<=0)d5("--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)d5("--port requires a valid port number (1-65535)");Z.port=X;break;default:if(z.startsWith("-"))d5(`Unknown option: ${z}. Try --help`);Y.push(z)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function c5(){return"1.9.0"}function Sz(){let $=c5();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 MY(){return Object.keys(OY)}var uO,OY;var K2=t0(()=>{Y0();J1();uO=/[";`$\n\r|&<>{}()]/;OY={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{existsSync as x3,readFileSync as yM}from"fs";import{join as B1}from"path";function hM(){let $=B1(process.cwd(),"node_modules",".bin"),Z=B1($,"gws.exe");if(x3(Z))return Z;let Y=B1($,"gws.cmd");if(x3(Y))return Y;let Q=B1($,"gws.bunx");if(x3(Q))return Q;let z=B1($,"gws");if(x3(z))return z;return"gws"}async function _3(){if(v3!==null)return v3;QZ=hM();try{let $=Bun.spawn([QZ,"--version"],{stdout:"pipe",stderr:"pipe",env:MQ()}),Z=setTimeout(()=>$.kill(),5000);await new Response($.stdout).text(),await $.exited,clearTimeout(Z),v3=$.exitCode===0}catch{v3=!1}return v3}async function S0($,Z={}){let Y=Z.timeout??vM;if(!await _3())return{success:!1,data:null,error:"GWS CLI not found. Run: npm install -g @googleworkspace/cli",raw:"",duration:0};let z=[QZ,...$],J=performance.now();try{let X=Bun.spawn(z,{stdout:"pipe",stderr:"pipe",env:MQ()}),K=setTimeout(()=>X.kill(),Y),[V,G]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]);await X.exited,clearTimeout(K);let W=Math.round(performance.now()-J),H=V.trim().slice(0,xM);if(X.exitCode!==0){let U=G.trim()||H||"Unknown error";if(pM(U))return{success:!1,data:null,error:"Not logged in. Run /gws login first.",raw:U,duration:W};return{success:!1,data:null,error:U,raw:U,duration:W}}if(H)try{return{success:!0,data:JSON.parse(H),error:null,raw:H,duration:W}}catch{return{success:!0,data:H,error:null,raw:H,duration:W}}return{success:!0,data:null,error:null,raw:H,duration:W}}catch(X){let K=Math.round(performance.now()-J),V=X instanceof Error?X.message:String(X);return{success:!1,data:null,error:V.includes("timed out")||V.includes("killed")?`Command timed out after ${Y}ms`:V,raw:"",duration:K}}}async function zZ($,Z,Y=180000){if(!await _3())return{success:!1,exitCode:1,output:"GWS CLI not found."};let z=[QZ,...$],J=[];try{let X=Bun.spawn(z,{stdout:"pipe",stderr:"pipe",env:MQ()}),K=setTimeout(()=>X.kill(),Y),V=new TextDecoder,G=(async()=>{let H=X.stderr.getReader();while(!0){let{done:U,value:q}=await H.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})(),W=(async()=>{let H=X.stdout.getReader();while(!0){let{done:U,value:q}=await H.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})();return await Promise.all([G,W]),await X.exited,clearTimeout(K),{success:X.exitCode===0,exitCode:X.exitCode??1,output:J.join("")}}catch{return{success:!1,exitCode:1,output:J.join("")}}}function gM(){if(q2!==void 0)return q2;let $=mM();for(let Z of $){if(!x3(Z))continue;try{let Y=yM(Z,"utf-8"),Q=JSON.parse(Y),z=Q.installed??Q.web;if(z?.client_id&&z?.client_secret)return q2={clientId:String(z.client_id),clientSecret:String(z.client_secret)},q2;if(Q.client_id&&Q.client_secret)return q2={clientId:String(Q.client_id),clientSecret:String(Q.client_secret)},q2}catch{}}return q2=null,null}function mM(){let $=[];if(process.platform==="win32"){let Q=process.env.APPDATA??B1(process.env.USERPROFILE??"","AppData","Roaming");$.push(B1(Q,"gws","client_secret.json"));let z=process.env.USERPROFILE??process.env.HOME??"";$.push(B1(z,".config","gws","client_secret.json"))}else{let Q=process.env.HOME??"/root";$.push(B1(Q,".config","gws","client_secret.json"))}let Z=process.env.GOOGLE_WORKSPACE_CLI_CONFIG_DIR;if(Z)$.push(B1(Z,"client_secret.json"));let Y=process.env.GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE;if(Y)$.push(Y);return $}function MQ(){let $={...process.env};if(!$.GOOGLE_WORKSPACE_CLI_CLIENT_ID||!$.GOOGLE_WORKSPACE_CLI_CLIENT_SECRET){let Z=gM();if(Z)$.GOOGLE_WORKSPACE_CLI_CLIENT_ID=Z.clientId,$.GOOGLE_WORKSPACE_CLI_CLIENT_SECRET=Z.clientSecret}if(!$.GOOGLE_WORKSPACE_CLI_TOKEN&&CQ)$.GOOGLE_WORKSPACE_CLI_TOKEN=CQ;return $}function EQ($){CQ=$}function h3(){q2=void 0}function pM($){return _M.some((Z)=>Z.test($))}var vM=30000,xM=200000,_M,v3=null,QZ="gws",q2=void 0,CQ=null;var t2=t0(()=>{_M=[/not authenticated/i,/no credentials/i,/token.*expired/i,/login required/i,/auth.*required/i]});var MG;var EG=t0(()=>{MG={gmail:120000,calendar:300000,drive:300000,status:60000}});function x5($){let Z=B2.get($);if(!Z)return null;if(Date.now()>Z.expiresAt)return B2.delete($),null;return Z.data}function e2($,Z,Y,Q){let z=Q??MG[Y]??300000;B2.set($,{data:Z,expiresAt:Date.now()+z,key:$})}function g3(){B2.clear()}function FQ(){let $=Date.now();for(let[Z,Y]of B2)if($>Y.expiresAt)B2.delete(Z);return{size:B2.size,keys:[...B2.keys()]}}var B2;var $5=t0(()=>{EG();B2=new Map});var RG={};G8(RG,{searchDriveFiles:()=>h5,listDriveFiles:()=>m1,formatDriveFileList:()=>Q1});function r0($,Z=""){if($===void 0||$===null)return Z;return String($)}function zE($){if($===0)return"-";let Z=["B","KB","MB","GB"],Y=Math.floor(Math.log($)/Math.log(1024));return`${($/Math.pow(1024,Y)).toFixed(1)} ${Z[Y]??"B"}`}async function m1($,Z={}){let Y=`drive:files:${$??"root"}`;if(!Z.fresh){let K=x5(Y);if(K)return{success:!0,data:K,error:null,raw:"",duration:0}}let Q=$?`'${$}' in parents and trashed = false`:"'root' in parents and trashed = false",z=await S0(["drive","files","list","--params",JSON.stringify({q:Q,pageSize:30,fields:"files(id,name,mimeType,size,modifiedTime,webViewLink,parents)",orderBy:"modifiedTime desc"})]);if(!z.success)return z;let X=((z.data&&typeof z.data==="object"&&"files"in z.data?z.data.files:Array.isArray(z.data)?z.data:[])??[]).map((K)=>{let V=K;return{id:r0(V.id),name:r0(V.name,"(unnamed)"),mimeType:r0(V.mimeType),size:typeof V.size==="number"?V.size:parseInt(r0(V.size,"0"),10),modifiedTime:r0(V.modifiedTime),webViewLink:r0(V.webViewLink),parents:Array.isArray(V.parents)?V.parents.map(String):[]}});return e2(Y,X,"drive"),{success:!0,data:X,error:null,raw:z.raw,duration:z.duration}}async function h5($){let Z=await S0(["drive","files","list","--params",JSON.stringify({q:`name contains '${$.replace(/'/g,"\\'")}' and trashed = false`,pageSize:20,fields:"files(id,name,mimeType,size,modifiedTime,webViewLink,parents)",orderBy:"modifiedTime desc"})]);if(!Z.success)return Z;return{success:!0,data:((Z.data&&typeof Z.data==="object"&&"files"in Z.data?Z.data.files:Array.isArray(Z.data)?Z.data:[])??[]).map((z)=>{let J=z;return{id:r0(J.id),name:r0(J.name,"(unnamed)"),mimeType:r0(J.mimeType),size:typeof J.size==="number"?J.size:parseInt(r0(J.size,"0"),10),modifiedTime:r0(J.modifiedTime),webViewLink:r0(J.webViewLink),parents:Array.isArray(J.parents)?J.parents.map(String):[]}}),error:null,raw:Z.raw,duration:Z.duration}}function Q1($){if($.length===0)return"Nenhum arquivo encontrado.";let Z=["--- Drive ---"];for(let Y of $){let Q=Y.mimeType==="application/vnd.google-apps.folder",z=Q?"[D]":"[F]",J=Q?"":` (${zE(Y.size)})`,X=Y.modifiedTime?new Date(Y.modifiedTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${z} ${Y.name}${J} ${X}`)}return Z.push("--------------------"),Z.join(`
92
+ `)}var g5=t0(()=>{t2();$5()});var TZ={};G8(TZ,{normalizeDomain:()=>jz,normalizeCnpj:()=>EH,normalizeCep:()=>LH,lookupDomain:()=>YL,lookupCnpj:()=>$L,lookupCep:()=>ZL,isBrDomain:()=>eF,initBrCompany:()=>Lz,getBrCompanyCacheStats:()=>WL,formatDomain:()=>VL,formatCompany:()=>XL,formatCnpj:()=>FH,formatCepInfo:()=>KL,formatCep:()=>Rz,clearBrCompanyCache:()=>GL});import{existsSync as CH,mkdirSync as nF,readFileSync as rF}from"fs";import{join as aF}from"path";function Lz($){if(Ez=$,!CH($))nF($,{recursive:!0});tF()}function tF(){let $=MH();if(!CH($)){f0={cnpj:{},cep:{},domain:{}};return}try{let Z=JSON.parse(rF($,"utf-8"));f0={cnpj:Z.cnpj||{},cep:Z.cep||{},domain:Z.domain||{}}}catch{f0={cnpj:{},cep:{},domain:{}}}}function DZ(){if(!Ez)return;try{j(MH(),JSON.stringify(f0,null,2))}catch{}}function EH($){let Z=($||"").replace(/\D/g,"");if(Z.length!==14)return null;if(/^(\d)\1{13}$/.test(Z))return null;return Z}function FH($){let Z=($||"").replace(/\D/g,"");if(Z.length!==14)return $;return`${Z.slice(0,2)}.${Z.slice(2,5)}.${Z.slice(5,8)}/${Z.slice(8,12)}-${Z.slice(12)}`}function LH($){let Z=($||"").replace(/\D/g,"");if(Z.length!==8)return null;return Z}function Rz($){let Z=($||"").replace(/\D/g,"");if(Z.length!==8)return $;return`${Z.slice(0,5)}-${Z.slice(5)}`}function jz($){if(!$)return null;let Z=$.trim().toLowerCase();if(Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split("/")[0],Z=Z.split("?")[0],!Z||!Z.includes("."))return null;if(!/^[a-z0-9.-]+$/.test(Z))return null;return Z}function eF($){let Z=jz($);if(!Z)return!1;return Z.endsWith(".br")}async function Pz($,Z="application/json"){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),sF);try{let z=await fetch($,{method:"GET",headers:{Accept:Z,"User-Agent":"smolerclaw/br-company (public-osint)"},signal:Y.signal});if(!z.ok){if(z.status===404)throw Error("not_found");if(z.status===429)throw Error("rate_limited");throw Error(`http_${z.status}`)}return await z.json()}finally{clearTimeout(Q)}}async function $L($,Z={}){let Y=EH($);if(!Y)throw Error("invalid_cnpj");if(!Z.refresh){let X=f0.cnpj[Y];if(X&&Date.now()-X.cachedAt<Fz)return X.data}let Q=`https://brasilapi.com.br/api/cnpj/v1/${Y}`,z=await Pz(Q),J=QL(Y,z);return f0.cnpj[Y]={cachedAt:Date.now(),data:J},DZ(),J}async function ZL($,Z={}){let Y=LH($);if(!Y)throw Error("invalid_cep");if(!Z.refresh){let X=f0.cep[Y];if(X&&Date.now()-X.cachedAt<Fz)return X.data}let Q=`https://brasilapi.com.br/api/cep/v2/${Y}`,z=await Pz(Q),J={cep:Y,estado:h(z.state),cidade:h(z.city),bairro:h(z.neighborhood),logradouro:h(z.street),servico:h(z.service),fetchedAt:Date.now(),source:"brasilapi"};return f0.cep[Y]={cachedAt:Date.now(),data:J},DZ(),J}async function YL($,Z={}){let Y=jz($);if(!Y)throw Error("invalid_domain");if(!Y.endsWith(".br"))throw Error("not_br_domain");if(!Z.refresh){let X=f0.domain[Y];if(X&&Date.now()-X.cachedAt<Fz)return X.data}let Q=`https://rdap.registro.br/domain/${Y}`,z=await Pz(Q,"application/rdap+json, application/json"),J=zL(Y,z);return f0.domain[Y]={cachedAt:Date.now(),data:J},DZ(),J}function QL($,Z){let Y=[],Q=Z.qsa;if(Array.isArray(Q))for(let z of Q){if(!z||typeof z!=="object")continue;let J=z;Y.push({nome:h(J.nome_socio)||"(sem nome)",qualificacao:h(J.qualificacao_socio),documento:h(J.cnpj_cpf_do_socio),entrada:h(J.data_entrada_sociedade)})}return{cnpj:$,razaoSocial:h(Z.razao_social)||"(sem razao social)",nomeFantasia:h(Z.nome_fantasia),situacaoCadastral:h(Z.descricao_situacao_cadastral)||h(Z.situacao_cadastral),dataSituacao:h(Z.data_situacao_cadastral),dataAbertura:h(Z.data_inicio_atividade),cnae:{codigo:h(Z.cnae_fiscal),descricao:h(Z.cnae_fiscal_descricao)},endereco:{logradouro:h(Z.logradouro),numero:h(Z.numero),complemento:h(Z.complemento),bairro:h(Z.bairro),municipio:h(Z.municipio),uf:h(Z.uf),cep:h(Z.cep)},telefone:h(Z.ddd_telefone_1),email:h(Z.email),capitalSocial:typeof Z.capital_social==="number"?Z.capital_social:void 0,naturezaJuridica:h(Z.natureza_juridica),porte:h(Z.porte),partners:Y,fetchedAt:Date.now(),source:"brasilapi"}}function zL($,Z){let Y=[];if(Array.isArray(Z.nameservers)){for(let X of Z.nameservers)if(X&&typeof X==="object"){let K=h(X.ldhName);if(K)Y.push(K.toLowerCase())}}let Q=[];if(Array.isArray(Z.events)){for(let X of Z.events)if(X&&typeof X==="object"){let K=X;Q.push({action:h(K.eventAction)||"(unknown)",date:h(K.eventDate)})}}let z=[];if(Array.isArray(Z.entities))for(let X of Z.entities){if(!X||typeof X!=="object")continue;let K=X,G=(Array.isArray(K.roles)?K.roles.filter((W)=>typeof W==="string"):[]).join(",")||"(unknown)";z.push({role:G,handle:h(K.handle),name:JL(K.vcardArray)})}let J=Array.isArray(Z.status)?Z.status.filter((X)=>typeof X==="string"):[];return{domain:$,status:J,nameservers:Y,events:Q,contacts:z,fetchedAt:Date.now(),source:"registro.br"}}function JL($){if(!Array.isArray($)||$.length<2)return;let Z=$[1];if(!Array.isArray(Z))return;for(let Y of Z)if(Array.isArray(Y)&&Y[0]==="fn"&&typeof Y[3]==="string")return Y[3];return}function XL($){let Z=[];if(Z.push(`--- ${$.razaoSocial} ---`),Z.push(`CNPJ: ${FH($.cnpj)}`),$.nomeFantasia)Z.push(`Fantasia: ${$.nomeFantasia}`);if($.situacaoCadastral){let Q=$.dataSituacao?` (desde ${$.dataSituacao})`:"";Z.push(`Situacao: ${$.situacaoCadastral}${Q}`)}if($.dataAbertura)Z.push(`Abertura: ${$.dataAbertura}`);if($.naturezaJuridica)Z.push(`Natureza: ${$.naturezaJuridica}`);if($.porte)Z.push(`Porte: ${$.porte}`);if(typeof $.capitalSocial==="number")Z.push(`Capital: R$ ${$.capitalSocial.toFixed(2)}`);if($.cnae?.codigo||$.cnae?.descricao){let Q=$.cnae.codigo?`[${$.cnae.codigo}] `:"";Z.push(`CNAE: ${Q}${$.cnae.descricao||""}`.trimEnd())}let Y=$.endereco;if(Y&&(Y.logradouro||Y.municipio)){let Q=[Y.logradouro,Y.numero].filter(Boolean).join(", "),z=[Y.complemento,Y.bairro].filter(Boolean).join(" - "),J=[Y.municipio,Y.uf].filter(Boolean).join("/"),X=Y.cep?Rz(Y.cep):"";if(Z.push("Endereco:"),Q)Z.push(` ${Q}`);if(z)Z.push(` ${z}`);if(J||X)Z.push(` ${J}${X?` \u2014 CEP ${X}`:""}`)}if($.telefone)Z.push(`Telefone: ${$.telefone}`);if($.email)Z.push(`Email: ${$.email}`);if($.partners.length>0){Z.push(""),Z.push(`Socios (${$.partners.length}):`);for(let Q of $.partners){let z=Q.documento?` ${Q.documento}`:"",J=Q.qualificacao?` \u2014 ${Q.qualificacao}`:"";Z.push(` - ${Q.nome}${z}${J}`)}}return Z.push(""),Z.push(`Fonte: BrasilAPI | Cache: ${Az($.fetchedAt)}`),Z.join(`
93
+ `)}function KL($){let Z=[];if(Z.push(`--- CEP ${Rz($.cep)} ---`),$.logradouro)Z.push(`Logradouro: ${$.logradouro}`);if($.bairro)Z.push(`Bairro: ${$.bairro}`);if($.cidade||$.estado)Z.push(`Cidade: ${[$.cidade,$.estado].filter(Boolean).join("/")}`);if($.servico)Z.push(`Servico: ${$.servico}`);return Z.push(""),Z.push(`Fonte: BrasilAPI | Cache: ${Az($.fetchedAt)}`),Z.join(`
94
+ `)}function VL($){let Z=[];if(Z.push(`--- ${$.domain} ---`),$.status&&$.status.length>0)Z.push(`Status: ${$.status.join(", ")}`);if($.events.length>0){Z.push("Eventos:");for(let Y of $.events){let Q=Y.date?` ${Y.date}`:"";Z.push(` ${Y.action.padEnd(18)}${Q}`)}}if($.nameservers.length>0){Z.push("Nameservers:");for(let Y of $.nameservers)Z.push(` ${Y}`)}if($.contacts.length>0){Z.push("Contatos:");for(let Y of $.contacts){let Q=Y.handle?` (${Y.handle})`:"",z=Y.name?` \u2014 ${Y.name}`:"";Z.push(` ${Y.role}${Q}${z}`)}}return Z.push(""),Z.push(`Fonte: Registro.br RDAP | Cache: ${Az($.fetchedAt)}`),Z.join(`
95
+ `)}function GL(){f0={cnpj:{},cep:{},domain:{}},DZ()}function WL(){return{cnpj:Object.keys(f0.cnpj).length,cep:Object.keys(f0.cep).length,domain:Object.keys(f0.domain).length}}function h($){if(typeof $==="string"){let Z=$.trim();return Z.length>0?Z:void 0}if(typeof $==="number")return String($);return}function Az($){let Z=Date.now()-$,Y=Math.floor(Z/60000);if(Y<1)return"agora";if(Y<60)return`${Y}min atras`;let Q=Math.floor(Y/60);if(Q<24)return`${Q}h atras`;return`${Math.floor(Q/24)}d atras`}var Ez="",f0,Fz=86400000,sF=1e4,MH=()=>aF(Ez,"br-company-cache.json");var Q8=t0(()=>{g();f0={cnpj:{},cep:{},domain:{}}});import{readFileSync as OU}from"fs";import{join as CU,dirname as MU}from"path";function pz($){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)l5("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)l5("--session requires a value");break;case"--max-tokens":let J=Number($[++Q]);if(!J||J<=0)l5("--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)l5("--port requires a valid port number (1-65535)");Z.port=X;break;default:if(z.startsWith("-"))l5(`Unknown option: ${z}. Try --help`);Y.push(z)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function o5(){return"1.9.1"}function uz(){let $=o5();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
93
96
 
94
97
  Usage:
95
98
  smolerclaw [command] [options] [prompt]
@@ -124,16 +127,16 @@ Commands (inside TUI):
124
127
  /briefing Daily briefing /news News radar
125
128
  /task Create task /tasks List tasks
126
129
  /open Open Windows app /calendar Outlook calendar
127
- /export Export markdown /exit Quit`)}function d5($){console.error(`smolerclaw: ${$}`),process.exit(2)}Z0();h();import{existsSync as J5,mkdirSync as jU,readFileSync as ZJ,readdirSync as YJ,copyFileSync as PU}from"fs";import{homedir as AU}from"os";import{join as A0}from"path";var n5=AU(),K5=R?A0(process.env.APPDATA||A0(n5,"AppData","Roaming"),"smolerclaw"):A0(n5,".config","smolerclaw"),_Z=R?A0(process.env.LOCALAPPDATA||A0(n5,"AppData","Local"),"smolerclaw"):A0(n5,".local","share","smolerclaw"),c1=A0(K5,"config.json"),z5={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:_Z,toolApproval:"auto",language:"auto",maxSessionCost:0};function X5($){if(!J5($))jU($,{recursive:!0})}function QJ(){if(X5(K5),X5(_Z),X5(A0(_Z,"sessions")),R)TU();if(!J5(c1))return P(c1,JSON.stringify(z5,null,2)),{...z5};let $;try{$=JSON.parse(ZJ(c1,"utf-8"))}catch{return P(c1,JSON.stringify(z5,null,2)),{...z5}}return DU({...z5,...$})}function DU($){let Z={...z5};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 M8($){X5(K5),P(c1,JSON.stringify($,null,2))}function E8(){return c1}function hZ(){return K5}function TU(){let $=A0(n5,".config","smolerclaw"),Z=A0($,"config.json");if(J5(Z)&&!J5(c1))try{let Y=ZJ(Z,"utf-8");X5(K5),P(c1,Y)}catch{}for(let Y of["plugins","materials"]){let Q=A0($,Y),z=A0(K5,Y);if(J5(Q)&&(!J5(z)||IU(z)))try{zJ(Q,z)}catch{}}}function IU($){try{return YJ($).length===0}catch{return!0}}function zJ($,Z){X5(Z);let Y=YJ($,{withFileTypes:!0});for(let Q of Y){let z=A0($,Q.name),J=A0(Z,Q.name);if(Q.isDirectory())zJ(z,J);else if(Q.isFile())PU(z,J)}}import{existsSync as wU,readFileSync as SU}from"fs";import{homedir as kU}from"os";import{join as fU}from"path";var JJ=fU(kU(),".claude",".credentials.json");function gZ(){let $=bU();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 bU(){if(!wU(JJ))return null;try{let Z=JSON.parse(SU(JJ,"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 j2(){try{return gZ()}catch{return null}}function XJ($){return`sub:${$.subscriptionType||"pro"}`}var F8=[{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 L8($){let Z=F8.find((J)=>J.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=F8.find((J)=>J.alias===Y);if(Q)return Q.id;let z=F8.find((J)=>J.id.includes(Y)||J.name.toLowerCase().includes(Y));if(z)return z.id;return $}function KJ($){let Z=["Available models:"];for(let Y of F8){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(`
128
- `)}function L($,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 mZ=function(){let{crypto:$}=globalThis;if($?.randomUUID)return mZ=$.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 E1($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var r5=($)=>{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 X0 extends j{constructor($,Z,Y,Q){super(`${X0.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 P2({message:Y,cause:r5(Z)});let z=Z;if($===400)return new s5($,z,Y,Q);if($===401)return new t5($,z,Y,Q);if($===403)return new e5($,z,Y,Q);if($===404)return new $$($,z,Y,Q);if($===409)return new Z$($,z,Y,Q);if($===422)return new Y$($,z,Y,Q);if($===429)return new Q$($,z,Y,Q);if($>=500)return new z$($,z,Y,Q);return new X0($,z,Y,Q)}}class E0 extends X0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class P2 extends X0{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class a5 extends P2{constructor({message:$}={}){super({message:$??"Request timed out."})}}class s5 extends X0{}class t5 extends X0{}class e5 extends X0{}class $$ extends X0{}class Z$ extends X0{}class Y$ extends X0{}class Q$ extends X0{}class z$ extends X0{}var vU=/^[a-z][a-z0-9+.-]*:/i,VJ=($)=>{return vU.test($)},pZ=($)=>(pZ=Array.isArray,pZ($)),uZ=pZ;function R8($){if(typeof $!=="object")return{};return $??{}}function dZ($){if(!$)return!0;for(let Z in $)return!1;return!0}function GJ($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var HJ=($,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 j8=($)=>{try{return JSON.parse($)}catch(Z){return}};var WJ=($)=>new Promise((Z)=>setTimeout(Z,$));var l1="0.80.0";var NJ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function xU(){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 _U=()=>{let $=xU();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l1,"X-Stainless-OS":qJ(Deno.build.os),"X-Stainless-Arch":UJ(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":qJ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":UJ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=hU();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 hU(){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 UJ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},qJ=($)=>{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"},BJ,OJ=()=>{return BJ??(BJ=_U())};function CJ(){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 cZ(...$){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 P8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return cZ({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 J$($){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 MJ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var EJ=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function FJ($){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 jJ($){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 LJ;function X$($){let Z;return(LJ??(Z=new globalThis.TextEncoder,LJ=Z.encode.bind(Z)))($)}var RJ;function lZ($){let Z;return(RJ??(Z=new globalThis.TextDecoder,RJ=Z.decode.bind(Z)))($)}var b0,y0;class o1{constructor(){b0.set(this,void 0),y0.set(this,void 0),L(this,b0,new Uint8Array,"f"),L(this,y0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?X$($):$;L(this,b0,jJ([O(this,b0,"f"),Z]),"f");let Y=[],Q;while((Q=pU(O(this,b0,"f"),O(this,y0,"f")))!=null){if(Q.carriage&&O(this,y0,"f")==null){L(this,y0,Q.index,"f");continue}if(O(this,y0,"f")!=null&&(Q.index!==O(this,y0,"f")+1||Q.carriage)){Y.push(lZ(O(this,b0,"f").subarray(0,O(this,y0,"f")-1))),L(this,b0,O(this,b0,"f").subarray(O(this,y0,"f")),"f"),L(this,y0,null,"f");continue}let z=O(this,y0,"f")!==null?Q.preceding-1:Q.preceding,J=lZ(O(this,b0,"f").subarray(0,z));Y.push(J),L(this,b0,O(this,b0,"f").subarray(Q.index),"f"),L(this,y0,null,"f")}return Y}flush(){if(!O(this,b0,"f").length)return[];return this.decode(`
129
- `)}}b0=new WeakMap,y0=new WeakMap;o1.NEWLINE_CHARS=new Set([`
130
- `,"\r"]);o1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function pU($,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 PJ($){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 D8={off:0,error:200,warn:300,info:400,debug:500},oZ=($,Z,Y)=>{if(!$)return;if(GJ(D8,$))return $;H0(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(D8))}`);return};function K$(){}function A8($,Z,Y){if(!Z||D8[$]>D8[Y])return K$;else return Z[$].bind(Z)}var uU={error:K$,warn:K$,info:K$,debug:K$},AJ=new WeakMap;function H0($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return uU;let Q=AJ.get(Z);if(Q&&Q[0]===Y)return Q[1];let z={error:A8("error",Z,Y),warn:A8("warn",Z,Y),info:A8("info",Z,Y),debug:A8("debug",Z,Y)};return AJ.set(Z,[Y,z]),z}var F1=($)=>{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 V$;class v0{constructor($,Z,Y){this.iterator=$,V$.set(this,void 0),this.controller=Z,L(this,V$,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,z=Y?H0(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 dU($,Z)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(V){throw z.error("Could not parse message into JSON:",K.data),z.error("From chunk:",K.raw),V}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(V){throw z.error("Could not parse message into JSON:",K.data),z.error("From chunk:",K.raw),V}if(K.event==="ping")continue;if(K.event==="error")throw new X0(void 0,j8(K.data)??K.data,void 0,$.headers)}X=!0}catch(K){if(E1(K))return;throw K}finally{if(!X)Z.abort()}}return new v0(J,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*z(){let X=new o1,K=J$($);for await(let V of K)for(let G of X.decode(V))yield G;for(let V of X.flush())yield V}async function*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(E1(K))return;throw K}finally{if(!X)Z.abort()}}return new v0(J,Z,Y)}[(V$=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 v0(()=>Q($),this.controller,O(this,V$,"f")),new v0(()=>Q(Z),this.controller,O(this,V$,"f"))]}toReadableStream(){let $=this,Z;return cZ({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:z}=await Z.next();if(z)return Y.close();let J=X$(JSON.stringify(Q)+`
131
- `);Y.enqueue(J)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*dU($,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 DJ,Q=new o1,z=J$($.body);for await(let J of cU(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*cU($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?X$(Y):Y,z=new Uint8Array(Z.length+Q.length);z.set(Z),z.set(Q,Z.length),Z=z;let J;while((J=PJ(Z))!==-1)yield Z.slice(0,J),Z=Z.slice(J)}if(Z.length>0)yield Z}class DJ{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(`
132
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],z}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=lU($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function lU($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function T8($,Z){let{response:Y,requestLogID:Q,retryOfRequestLogID:z,startTime:J}=Z,X=await(async()=>{if(Z.options.stream){if(H0($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return v0.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let V=Y.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let U=await Y.json();return iZ(U,Y)}return await Y.text()})();return H0($).debug(`[${Q}] response parsed`,F1({retryOfRequestLogID:z,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-J})),X}function iZ($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var G$;class A2 extends Promise{constructor($,Z,Y=T8){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,G$.set(this,void 0),L(this,G$,$,"f")}_thenUnwrap($){return new A2(O(this,G$,"f"),this.responsePromise,async(Z,Y)=>iZ($(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,G$,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}G$=new WeakMap;var I8;class nZ{constructor($,Z,Y,Q){I8.set(this,void 0),L(this,I8,$,"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,I8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(I8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class w8 extends A2{constructor($,Z,Y){super($,Z,async(Q,z)=>new Y(Q,z.response,await T8(Q,z),z.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class a0 extends nZ{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:{...R8(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...R8(this.options.query),after_id:$}}}}class H$ extends nZ{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:{...R8(this.options.query),page:$}}}}var aZ=()=>{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 D2($,Z,Y){return aZ(),new File($,Z??"unknown_file",Y)}function W$($,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 sZ=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var V5=async($,Z,Y=!0)=>{return{...$,body:await nU($.body,Z,Y)}},TJ=new WeakMap;function iU($){let Z=typeof $==="function"?$:$.fetch,Y=TJ.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 TJ.set(Z,Q),Q}var nU=async($,Z,Y=!0)=>{if(!await iU(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])=>rZ(Q,z,J,Y))),Q},rU=($)=>$ instanceof Blob&&("name"in $);var rZ=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,D2([await Y.blob()],W$(Y,Q),z))}else if(sZ(Y))$.append(Z,D2([await new Response(P8(Y)).blob()],W$(Y,Q)));else if(rU(Y))$.append(Z,D2([Y],W$(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((z)=>rZ($,Z+"[]",z,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([z,J])=>rZ($,`${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 IJ=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",aU=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&IJ($),sU=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function S8($,Z,Y){if(aZ(),$=await $,Z||(Z=W$($,!0)),aU($)){if($ instanceof File&&Z==null&&Y==null)return $;return D2([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(sU($)){let z=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),D2(await tZ(z),Z,Y)}let Q=await tZ($);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 D2(Q,Z,Y)}async function tZ($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(IJ($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(sZ($))for await(let Y of $)Z.push(...await tZ(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${tU($)}`)}return Z}function tU($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class s{constructor($){this._client=$}}var wJ=Symbol.for("brand.privateNullableHeaders");function*$q($){if(!$)return;if(wJ 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(uZ($))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=uZ(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 I=($)=>{let Z=new Headers,Y=new Set;for(let Q of $){let z=new Set;for(let[J,X]of $q(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{[wJ]:!0,values:Z,nulls:Y}};var U$=Symbol("anthropic.sdk.stainlessHelper");function k8($){return typeof $==="object"&&$!==null&&U$ in $}function eZ($,Z){let Y=new Set;if($){for(let Q of $)if(k8(Q))Y.add(Q[U$])}if(Z)for(let Q of Z){if(k8(Q))Y.add(Q[U$]);if(Array.isArray(Q.content)){for(let z of Q.content)if(k8(z))Y.add(z[U$])}}return Array.from(Y)}function f8($,Z){let Y=eZ($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function SJ($){if(k8($))return{"x-stainless-helper":$[U$]};return{}}function fJ($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var kJ=Object.freeze(Object.create(null)),Zq=($=fJ)=>function(Y,...Q){if(Y.length===1)return Y[0];let z=!1,J=[],X=Y.reduce((H,W,U)=>{if(/[?#]/.test(W))z=!0;let q=Q[U],N=(z?encodeURIComponent:$)(""+q);if(U!==Q.length&&(q==null||typeof q==="object"&&q.toString===Object.getPrototypeOf(Object.getPrototypeOf(q.hasOwnProperty??kJ)??kJ)?.toString))N=q+"",J.push({start:H.length+W.length,length:N.length,error:`Value of type ${Object.prototype.toString.call(q).slice(8,-1)} is not a valid path parameter`});return H+W+(U===Q.length?"":N)},""),K=X.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,G;while((G=V.exec(K))!==null)J.push({start:G.index,length:G[0].length,error:`Value "${G[0]}" can't be safely passed as a path parameter`});if(J.sort((H,W)=>H.start-W.start),J.length>0){let H=0,W=J.reduce((U,q)=>{let N=" ".repeat(q.start-H),C="^".repeat(q.length);return H=q.start+q.length,U+N+C},"");throw new j(`Path parameters result in path with invalid segments:
130
+ /export Export markdown /exit Quit`)}function l5($){console.error(`smolerclaw: ${$}`),process.exit(2)}Y0();g();import{existsSync as K5,mkdirSync as mU,readFileSync as qJ,readdirSync as BJ,copyFileSync as pU}from"fs";import{homedir as uU}from"os";import{join as D0}from"path";var a5=uU(),G5=R?D0(process.env.APPDATA||D0(a5,"AppData","Roaming"),"smolerclaw"):D0(a5,".config","smolerclaw"),uZ=R?D0(process.env.LOCALAPPDATA||D0(a5,"AppData","Local"),"smolerclaw"):D0(a5,".local","share","smolerclaw"),o1=D0(G5,"config.json"),X5={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:uZ,toolApproval:"auto",language:"auto",maxSessionCost:0};function V5($){if(!K5($))mU($,{recursive:!0})}function NJ(){if(V5(G5),V5(uZ),V5(D0(uZ,"sessions")),R)cU();if(!K5(o1))return j(o1,JSON.stringify(X5,null,2)),{...X5};let $;try{$=JSON.parse(qJ(o1,"utf-8"))}catch{return j(o1,JSON.stringify(X5,null,2)),{...X5}}return dU({...X5,...$})}function dU($){let Z={...X5};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($){V5(G5),j(o1,JSON.stringify($,null,2))}function j8(){return o1}function dZ(){return G5}function cU(){let $=D0(a5,".config","smolerclaw"),Z=D0($,"config.json");if(K5(Z)&&!K5(o1))try{let Y=qJ(Z,"utf-8");V5(G5),j(o1,Y)}catch{}for(let Y of["plugins","materials"]){let Q=D0($,Y),z=D0(G5,Y);if(K5(Q)&&(!K5(z)||lU(z)))try{OJ(Q,z)}catch{}}}function lU($){try{return BJ($).length===0}catch{return!0}}function OJ($,Z){V5(Z);let Y=BJ($,{withFileTypes:!0});for(let Q of Y){let z=D0($,Q.name),J=D0(Z,Q.name);if(Q.isDirectory())OJ(z,J);else if(Q.isFile())pU(z,J)}}import{existsSync as oU,readFileSync as iU}from"fs";import{homedir as nU}from"os";import{join as rU}from"path";var CJ=rU(nU(),".claude",".credentials.json");function cZ(){let $=aU();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 aU(){if(!oU(CJ))return null;try{let Z=JSON.parse(iU(CJ,"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 A2(){try{return cZ()}catch{return null}}function MJ($){return`sub:${$.subscriptionType||"pro"}`}var P8=[{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 A8($){let Z=P8.find((J)=>J.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=P8.find((J)=>J.alias===Y);if(Q)return Q.id;let z=P8.find((J)=>J.id.includes(Y)||J.name.toLowerCase().includes(Y));if(z)return z.id;return $}function EJ($){let Z=["Available models:"];for(let Y of P8){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(`
131
+ `)}function L($,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 lZ=function(){let{crypto:$}=globalThis;if($?.randomUUID)return lZ=$.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 L1($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var s5=($)=>{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 P extends Error{}class K0 extends P{constructor($,Z,Y,Q){super(`${K0.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 D2({message:Y,cause:s5(Z)});let z=Z;if($===400)return new e5($,z,Y,Q);if($===401)return new $$($,z,Y,Q);if($===403)return new Z$($,z,Y,Q);if($===404)return new Y$($,z,Y,Q);if($===409)return new Q$($,z,Y,Q);if($===422)return new z$($,z,Y,Q);if($===429)return new J$($,z,Y,Q);if($>=500)return new X$($,z,Y,Q);return new K0($,z,Y,Q)}}class F0 extends K0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class D2 extends K0{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class t5 extends D2{constructor({message:$}={}){super({message:$??"Request timed out."})}}class e5 extends K0{}class $$ extends K0{}class Z$ extends K0{}class Y$ extends K0{}class Q$ extends K0{}class z$ extends K0{}class J$ extends K0{}class X$ extends K0{}var tU=/^[a-z][a-z0-9+.-]*:/i,FJ=($)=>{return tU.test($)},oZ=($)=>(oZ=Array.isArray,oZ($)),iZ=oZ;function D8($){if(typeof $!=="object")return{};return $??{}}function nZ($){if(!$)return!0;for(let Z in $)return!1;return!0}function LJ($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var RJ=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new P(`${$} must be an integer`);if(Z<0)throw new P(`${$} must be a positive integer`);return Z};var T8=($)=>{try{return JSON.parse($)}catch(Z){return}};var jJ=($)=>new Promise((Z)=>setTimeout(Z,$));var i1="0.80.0";var TJ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function eU(){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 $q=()=>{let $=eU();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i1,"X-Stainless-OS":AJ(Deno.build.os),"X-Stainless-Arch":PJ(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":i1,"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":i1,"X-Stainless-OS":AJ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":PJ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=Zq();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i1,"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":i1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Zq(){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 PJ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},AJ=($)=>{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"},DJ,IJ=()=>{return DJ??(DJ=$q())};function SJ(){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 rZ(...$){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 I8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return rZ({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 K$($){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 wJ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var kJ=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function fJ($){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 P(`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 vJ($){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 bJ;function V$($){let Z;return(bJ??(Z=new globalThis.TextEncoder,bJ=Z.encode.bind(Z)))($)}var yJ;function aZ($){let Z;return(yJ??(Z=new globalThis.TextDecoder,yJ=Z.decode.bind(Z)))($)}var v0,x0;class n1{constructor(){v0.set(this,void 0),x0.set(this,void 0),L(this,v0,new Uint8Array,"f"),L(this,x0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?V$($):$;L(this,v0,vJ([O(this,v0,"f"),Z]),"f");let Y=[],Q;while((Q=zq(O(this,v0,"f"),O(this,x0,"f")))!=null){if(Q.carriage&&O(this,x0,"f")==null){L(this,x0,Q.index,"f");continue}if(O(this,x0,"f")!=null&&(Q.index!==O(this,x0,"f")+1||Q.carriage)){Y.push(aZ(O(this,v0,"f").subarray(0,O(this,x0,"f")-1))),L(this,v0,O(this,v0,"f").subarray(O(this,x0,"f")),"f"),L(this,x0,null,"f");continue}let z=O(this,x0,"f")!==null?Q.preceding-1:Q.preceding,J=aZ(O(this,v0,"f").subarray(0,z));Y.push(J),L(this,v0,O(this,v0,"f").subarray(Q.index),"f"),L(this,x0,null,"f")}return Y}flush(){if(!O(this,v0,"f").length)return[];return this.decode(`
132
+ `)}}v0=new WeakMap,x0=new WeakMap;n1.NEWLINE_CHARS=new Set([`
133
+ `,"\r"]);n1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zq($,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 xJ($){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 w8={off:0,error:200,warn:300,info:400,debug:500},sZ=($,Z,Y)=>{if(!$)return;if(LJ(w8,$))return $;H0(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(w8))}`);return};function G$(){}function S8($,Z,Y){if(!Z||w8[$]>w8[Y])return G$;else return Z[$].bind(Z)}var Jq={error:G$,warn:G$,info:G$,debug:G$},_J=new WeakMap;function H0($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return Jq;let Q=_J.get(Z);if(Q&&Q[0]===Y)return Q[1];let z={error:S8("error",Z,Y),warn:S8("warn",Z,Y),info:S8("info",Z,Y),debug:S8("debug",Z,Y)};return _J.set(Z,[Y,z]),z}var R1=($)=>{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 W$;class _0{constructor($,Z,Y){this.iterator=$,W$.set(this,void 0),this.controller=Z,L(this,W$,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,z=Y?H0(Y):console;async function*J(){if(Q)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let X=!1;try{for await(let K of Xq($,Z)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(V){throw z.error("Could not parse message into JSON:",K.data),z.error("From chunk:",K.raw),V}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(V){throw z.error("Could not parse message into JSON:",K.data),z.error("From chunk:",K.raw),V}if(K.event==="ping")continue;if(K.event==="error")throw new K0(void 0,T8(K.data)??K.data,void 0,$.headers)}X=!0}catch(K){if(L1(K))return;throw K}finally{if(!X)Z.abort()}}return new _0(J,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*z(){let X=new n1,K=K$($);for await(let V of K)for(let G of X.decode(V))yield G;for(let V of X.flush())yield V}async function*J(){if(Q)throw new P("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(L1(K))return;throw K}finally{if(!X)Z.abort()}}return new _0(J,Z,Y)}[(W$=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 _0(()=>Q($),this.controller,O(this,W$,"f")),new _0(()=>Q(Z),this.controller,O(this,W$,"f"))]}toReadableStream(){let $=this,Z;return rZ({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:z}=await Z.next();if(z)return Y.close();let J=V$(JSON.stringify(Q)+`
134
+ `);Y.enqueue(J)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*Xq($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new P("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 P("Attempted to iterate over a response with no body")}let Y=new hJ,Q=new n1,z=K$($.body);for await(let J of Kq(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*Kq($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?V$(Y):Y,z=new Uint8Array(Z.length+Q.length);z.set(Z),z.set(Q,Z.length),Z=z;let J;while((J=xJ(Z))!==-1)yield Z.slice(0,J),Z=Z.slice(J)}if(Z.length>0)yield Z}class hJ{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(`
135
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],z}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=Vq($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function Vq($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function k8($,Z){let{response:Y,requestLogID:Q,retryOfRequestLogID:z,startTime:J}=Z,X=await(async()=>{if(Z.options.stream){if(H0($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return _0.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let V=Y.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let U=await Y.json();return tZ(U,Y)}return await Y.text()})();return H0($).debug(`[${Q}] response parsed`,R1({retryOfRequestLogID:z,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-J})),X}function tZ($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var H$;class T2 extends Promise{constructor($,Z,Y=k8){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,H$.set(this,void 0),L(this,H$,$,"f")}_thenUnwrap($){return new T2(O(this,H$,"f"),this.responsePromise,async(Z,Y)=>tZ($(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,H$,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}H$=new WeakMap;var f8;class eZ{constructor($,Z,Y,Q){f8.set(this,void 0),L(this,f8,$,"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 P("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await O(this,f8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(f8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class b8 extends T2{constructor($,Z,Y){super($,Z,async(Q,z)=>new Y(Q,z.response,await k8(Q,z),z.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class e0 extends eZ{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:{...D8(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...D8(this.options.query),after_id:$}}}}class U$ extends eZ{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:{...D8(this.options.query),page:$}}}}var Z4=()=>{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 I2($,Z,Y){return Z4(),new File($,Z??"unknown_file",Y)}function q$($,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 Y4=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var W5=async($,Z,Y=!0)=>{return{...$,body:await Hq($.body,Z,Y)}},gJ=new WeakMap;function Wq($){let Z=typeof $==="function"?$:$.fetch,Y=gJ.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 gJ.set(Z,Q),Q}var Hq=async($,Z,Y=!0)=>{if(!await Wq(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])=>$4(Q,z,J,Y))),Q},Uq=($)=>$ instanceof Blob&&("name"in $);var $4=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,I2([await Y.blob()],q$(Y,Q),z))}else if(Y4(Y))$.append(Z,I2([await new Response(I8(Y)).blob()],q$(Y,Q)));else if(Uq(Y))$.append(Z,I2([Y],q$(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((z)=>$4($,Z+"[]",z,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([z,J])=>$4($,`${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 mJ=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",qq=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&mJ($),Bq=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function y8($,Z,Y){if(Z4(),$=await $,Z||(Z=q$($,!0)),qq($)){if($ instanceof File&&Z==null&&Y==null)return $;return I2([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(Bq($)){let z=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),I2(await Q4(z),Z,Y)}let Q=await Q4($);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 I2(Q,Z,Y)}async function Q4($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(mJ($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(Y4($))for await(let Y of $)Z.push(...await Q4(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${Nq($)}`)}return Z}function Nq($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class t{constructor($){this._client=$}}var pJ=Symbol.for("brand.privateNullableHeaders");function*Cq($){if(!$)return;if(pJ 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(iZ($))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=iZ(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 I=($)=>{let Z=new Headers,Y=new Set;for(let Q of $){let z=new Set;for(let[J,X]of Cq(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{[pJ]:!0,values:Z,nulls:Y}};var B$=Symbol("anthropic.sdk.stainlessHelper");function v8($){return typeof $==="object"&&$!==null&&B$ in $}function z4($,Z){let Y=new Set;if($){for(let Q of $)if(v8(Q))Y.add(Q[B$])}if(Z)for(let Q of Z){if(v8(Q))Y.add(Q[B$]);if(Array.isArray(Q.content)){for(let z of Q.content)if(v8(z))Y.add(z[B$])}}return Array.from(Y)}function x8($,Z){let Y=z4($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function uJ($){if(v8($))return{"x-stainless-helper":$[B$]};return{}}function cJ($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var dJ=Object.freeze(Object.create(null)),Mq=($=cJ)=>function(Y,...Q){if(Y.length===1)return Y[0];let z=!1,J=[],X=Y.reduce((W,H,U)=>{if(/[?#]/.test(H))z=!0;let q=Q[U],N=(z?encodeURIComponent:$)(""+q);if(U!==Q.length&&(q==null||typeof q==="object"&&q.toString===Object.getPrototypeOf(Object.getPrototypeOf(q.hasOwnProperty??dJ)??dJ)?.toString))N=q+"",J.push({start:W.length+H.length,length:N.length,error:`Value of type ${Object.prototype.toString.call(q).slice(8,-1)} is not a valid path parameter`});return W+H+(U===Q.length?"":N)},""),K=X.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,G;while((G=V.exec(K))!==null)J.push({start:G.index,length:G[0].length,error:`Value "${G[0]}" can't be safely passed as a path parameter`});if(J.sort((W,H)=>W.start-H.start),J.length>0){let W=0,H=J.reduce((U,q)=>{let N=" ".repeat(q.start-W),C="^".repeat(q.length);return W=q.start+q.length,U+N+C},"");throw new P(`Path parameters result in path with invalid segments:
133
136
  ${J.map((U)=>U.error).join(`
134
137
  `)}
135
138
  ${X}
136
- ${W}`)}return X},a=Zq(fJ);class q$ extends s{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",a0,{query:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(a`/v1/files/${$}`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(a`/v1/files/${$}/content`,{...Y,headers:I([{"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(a`/v1/files/${$}`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/files",V5({body:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},SJ(Q.file),Z?.headers])},this._client))}}class B$ extends s{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(a`/v1/models/${$}?beta=true`,{...Y,headers:I([{...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",a0,{query:Q,...Z,headers:I([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var b8={"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 bJ($){return $?.output_format??$?.output_config?.format}function $4($,Z,Y){let Q=bJ(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 Z4($,Z,Y)}function Z4($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=zq(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 zq($,Z){let Y=bJ($);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 Jq=($)=>{let Z=0,Y=[];while(Z<$.length){let Q=$[Z];if(Q==="\\"){Z++;continue}if(Q==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(Q==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(Q==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(Q==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(Q===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(Q===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(Q==='"'){let K="",V=!1;Q=$[++Z];while(Q!=='"'){if(Z===$.length){V=!0;break}if(Q==="\\"){if(Z++,Z===$.length){V=!0;break}K+=Q+$[Z],Q=$[++Z]}else K+=Q,Q=$[++Z]}if(Q=$[++Z],!V)Y.push({type:"string",value:K});continue}if(Q&&/\s/.test(Q)){Z++;continue}let 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},G5=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),G5($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),G5($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),G5($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),G5($);break;case"delimiter":return $=$.slice(0,$.length-1),G5($);break}return $},Xq=($)=>{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 $},Kq=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},y8=($)=>JSON.parse(Kq(Xq(G5(Jq($)))));var m0,i1,H5,N$,v8,O$,C$,x8,M$,L1,E$,_8,h8,T2,g8,m8,F$,Y4,yJ,p8,Q4,z4,J4,vJ,xJ="__json_buf";function _J($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class L${constructor($,Z){m0.add(this),this.messages=[],this.receivedMessages=[],i1.set(this,void 0),H5.set(this,null),this.controller=new AbortController,N$.set(this,void 0),v8.set(this,()=>{}),O$.set(this,()=>{}),C$.set(this,void 0),x8.set(this,()=>{}),M$.set(this,()=>{}),L1.set(this,{}),E$.set(this,!1),_8.set(this,!1),h8.set(this,!1),T2.set(this,!1),g8.set(this,void 0),m8.set(this,void 0),F$.set(this,void 0),p8.set(this,(Y)=>{if(L(this,_8,!0,"f"),E1(Y))Y=new E0;if(Y instanceof E0)return L(this,h8,!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)))}),L(this,N$,new Promise((Y,Q)=>{L(this,v8,Y,"f"),L(this,O$,Q,"f")}),"f"),L(this,C$,new Promise((Y,Q)=>{L(this,x8,Y,"f"),L(this,M$,Q,"f")}),"f"),O(this,N$,"f").catch(()=>{}),O(this,C$,"f").catch(()=>{}),L(this,H5,$,"f"),L(this,F$,Z?.logger??console,"f")}get response(){return O(this,g8,"f")}get request_id(){return O(this,m8,"f")}async withResponse(){L(this,T2,!0,"f");let $=await O(this,N$,"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 L$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new L$(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return L(z,H5,{...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,p8,"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,m0,"m",Q4).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,m0,"m",z4).call(this,K);if(X.controller.signal?.aborted)throw new E0;O(this,m0,"m",J4).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;L(this,g8,$,"f"),L(this,m8,$?.headers.get("request-id"),"f"),O(this,v8,"f").call(this,$),this._emit("connect")}get ended(){return O(this,E$,"f")}get errored(){return O(this,_8,"f")}get aborted(){return O(this,h8,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,L1,"f")[$]||(O(this,L1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,L1,"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,L1,"f")[$]||(O(this,L1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(L(this,T2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){L(this,T2,!0,"f"),await O(this,C$,"f")}get currentMessage(){return O(this,i1,"f")}async finalMessage(){return await this.done(),O(this,m0,"m",Y4).call(this)}async finalText(){return await this.done(),O(this,m0,"m",yJ).call(this)}_emit($,...Z){if(O(this,E$,"f"))return;if($==="end")L(this,E$,!0,"f"),O(this,x8,"f").call(this);let Y=O(this,L1,"f")[$];if(Y)O(this,L1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,T2,"f")&&!Y?.length)Promise.reject(Q);O(this,O$,"f").call(this,Q),O(this,M$,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,T2,"f")&&!Y?.length)Promise.reject(Q);O(this,O$,"f").call(this,Q),O(this,M$,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,m0,"m",Y4).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,m0,"m",Q4).call(this),this._connected(null);let z=v0.fromReadableStream($,this.controller);for await(let J of z)O(this,m0,"m",z4).call(this,J);if(z.controller.signal?.aborted)throw new E0;O(this,m0,"m",J4).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(i1=new WeakMap,H5=new WeakMap,N$=new WeakMap,v8=new WeakMap,O$=new WeakMap,C$=new WeakMap,x8=new WeakMap,M$=new WeakMap,L1=new WeakMap,E$=new WeakMap,_8=new WeakMap,h8=new WeakMap,T2=new WeakMap,g8=new WeakMap,m8=new WeakMap,F$=new WeakMap,p8=new WeakMap,m0=new WeakSet,Y4=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},yJ=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(" ")},Q4=function(){if(this.ended)return;L(this,i1,void 0,"f")},z4=function(Z){if(this.ended)return;let Y=O(this,m0,"m",vJ).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(_J(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:hJ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage($4(Y,O(this,H5,"f"),{logger:O(this,F$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{L(this,i1,Y,"f");break}case"content_block_start":case"message_delta":break}},J4=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 L(this,i1,void 0,"f"),$4(Z,O(this,H5,"f"),{logger:O(this,F$,"f")})},vJ=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.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&&_J(Q)){let z=Q[xJ]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,xJ,{value:z,enumerable:!1,writable:!0}),z)try{J.input=y8(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,p8,"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:hJ(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 v0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function hJ($){}class W5 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 gJ=1e5,mJ=`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:
139
+ ${H}`)}return X},s=Mq(cJ);class N$ extends t{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",e0,{query:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(s`/v1/files/${$}`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(s`/v1/files/${$}/content`,{...Y,headers:I([{"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(s`/v1/files/${$}`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/files",W5({body:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},uJ(Q.file),Z?.headers])},this._client))}}class O$ extends t{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(s`/v1/models/${$}?beta=true`,{...Y,headers:I([{...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",e0,{query:Q,...Z,headers:I([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var _8={"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 lJ($){return $?.output_format??$?.output_config?.format}function J4($,Z,Y){let Q=lJ(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 X4($,Z,Y)}function X4($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=Lq(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 Lq($,Z){let Y=lJ($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new P(`Failed to parse structured output: ${Q}`)}}var Rq=($)=>{let Z=0,Y=[];while(Z<$.length){let Q=$[Z];if(Q==="\\"){Z++;continue}if(Q==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(Q==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(Q==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(Q==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(Q===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(Q===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(Q==='"'){let K="",V=!1;Q=$[++Z];while(Q!=='"'){if(Z===$.length){V=!0;break}if(Q==="\\"){if(Z++,Z===$.length){V=!0;break}K+=Q+$[Z],Q=$[++Z]}else K+=Q,Q=$[++Z]}if(Q=$[++Z],!V)Y.push({type:"string",value:K});continue}if(Q&&/\s/.test(Q)){Z++;continue}let 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},H5=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),H5($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),H5($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),H5($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),H5($);break;case"delimiter":return $=$.slice(0,$.length-1),H5($);break}return $},jq=($)=>{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 $},Pq=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},h8=($)=>JSON.parse(Pq(jq(H5(Rq($)))));var u0,r1,U5,C$,g8,M$,E$,m8,F$,j1,L$,p8,u8,S2,d8,c8,R$,K4,oJ,l8,V4,G4,W4,iJ,nJ="__json_buf";function rJ($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class j${constructor($,Z){u0.add(this),this.messages=[],this.receivedMessages=[],r1.set(this,void 0),U5.set(this,null),this.controller=new AbortController,C$.set(this,void 0),g8.set(this,()=>{}),M$.set(this,()=>{}),E$.set(this,void 0),m8.set(this,()=>{}),F$.set(this,()=>{}),j1.set(this,{}),L$.set(this,!1),p8.set(this,!1),u8.set(this,!1),S2.set(this,!1),d8.set(this,void 0),c8.set(this,void 0),R$.set(this,void 0),l8.set(this,(Y)=>{if(L(this,p8,!0,"f"),L1(Y))Y=new F0;if(Y instanceof F0)return L(this,u8,!0,"f"),this._emit("abort",Y);if(Y instanceof P)return this._emit("error",Y);if(Y instanceof Error){let Q=new P(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new P(String(Y)))}),L(this,C$,new Promise((Y,Q)=>{L(this,g8,Y,"f"),L(this,M$,Q,"f")}),"f"),L(this,E$,new Promise((Y,Q)=>{L(this,m8,Y,"f"),L(this,F$,Q,"f")}),"f"),O(this,C$,"f").catch(()=>{}),O(this,E$,"f").catch(()=>{}),L(this,U5,$,"f"),L(this,R$,Z?.logger??console,"f")}get response(){return O(this,d8,"f")}get request_id(){return O(this,c8,"f")}async withResponse(){L(this,S2,!0,"f");let $=await O(this,C$,"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 j$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new j$(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return L(z,U5,{...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,l8,"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,u0,"m",V4).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,u0,"m",G4).call(this,K);if(X.controller.signal?.aborted)throw new F0;O(this,u0,"m",W4).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;L(this,d8,$,"f"),L(this,c8,$?.headers.get("request-id"),"f"),O(this,g8,"f").call(this,$),this._emit("connect")}get ended(){return O(this,L$,"f")}get errored(){return O(this,p8,"f")}get aborted(){return O(this,u8,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,j1,"f")[$]||(O(this,j1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,j1,"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,j1,"f")[$]||(O(this,j1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(L(this,S2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){L(this,S2,!0,"f"),await O(this,E$,"f")}get currentMessage(){return O(this,r1,"f")}async finalMessage(){return await this.done(),O(this,u0,"m",K4).call(this)}async finalText(){return await this.done(),O(this,u0,"m",oJ).call(this)}_emit($,...Z){if(O(this,L$,"f"))return;if($==="end")L(this,L$,!0,"f"),O(this,m8,"f").call(this);let Y=O(this,j1,"f")[$];if(Y)O(this,j1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,S2,"f")&&!Y?.length)Promise.reject(Q);O(this,M$,"f").call(this,Q),O(this,F$,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,S2,"f")&&!Y?.length)Promise.reject(Q);O(this,M$,"f").call(this,Q),O(this,F$,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,u0,"m",K4).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,u0,"m",V4).call(this),this._connected(null);let z=_0.fromReadableStream($,this.controller);for await(let J of z)O(this,u0,"m",G4).call(this,J);if(z.controller.signal?.aborted)throw new F0;O(this,u0,"m",W4).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(r1=new WeakMap,U5=new WeakMap,C$=new WeakMap,g8=new WeakMap,M$=new WeakMap,E$=new WeakMap,m8=new WeakMap,F$=new WeakMap,j1=new WeakMap,L$=new WeakMap,p8=new WeakMap,u8=new WeakMap,S2=new WeakMap,d8=new WeakMap,c8=new WeakMap,R$=new WeakMap,l8=new WeakMap,u0=new WeakSet,K4=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},oJ=function(){if(this.receivedMessages.length===0)throw new P("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 P("stream ended without producing a content block with type=text");return Z.join(" ")},V4=function(){if(this.ended)return;L(this,r1,void 0,"f")},G4=function(Z){if(this.ended)return;let Y=O(this,u0,"m",iJ).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(rJ(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:aJ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(J4(Y,O(this,U5,"f"),{logger:O(this,R$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{L(this,r1,Y,"f");break}case"content_block_start":case"message_delta":break}},W4=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let Z=O(this,r1,"f");if(!Z)throw new P("request ended without sending any chunks");return L(this,r1,void 0,"f"),J4(Z,O(this,U5,"f"),{logger:O(this,R$,"f")})},iJ=function(Z){let Y=O(this,r1,"f");if(Z.type==="message_start"){if(Y)throw new P(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new P(`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&&rJ(Q)){let z=Q[nJ]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,nJ,{value:z,enumerable:!1,writable:!0}),z)try{J.input=h8(z)}catch(X){let K=new P(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${X}. JSON: ${z}`);O(this,l8,"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:aJ(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 _0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function aJ($){}class q5 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 sJ=1e5,tJ=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
137
140
  1. Task Overview
138
141
  The user's core request and success criteria
139
142
  Any clarifications or constraints they specified
@@ -155,47 +158,47 @@ User preferences or style requirements
155
158
  Domain-specific details that aren't obvious
156
159
  Any promises made to the user
157
160
  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.
158
- Wrap your summary in <summary></summary> tags.`;var R$,U5,I2,K0,j$,x0,R1,n1,P$,pJ,X4;function uJ(){let $,Z;return{promise:new Promise((Q,z)=>{$=Q,Z=z}),resolve:$,reject:Z}}class A${constructor($,Z,Y){R$.add(this),this.client=$,U5.set(this,!1),I2.set(this,!1),K0.set(this,void 0),j$.set(this,void 0),x0.set(this,void 0),R1.set(this,void 0),n1.set(this,void 0),P$.set(this,0),L(this,K0,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let z=["BetaToolRunner",...eZ(Z.tools,Z.messages)].join(", ");L(this,j$,{...Y,headers:I([{"x-stainless-helper":z},Y?.headers])},"f"),L(this,n1,uJ(),"f")}async*[(U5=new WeakMap,I2=new WeakMap,K0=new WeakMap,j$=new WeakMap,x0=new WeakMap,R1=new WeakMap,n1=new WeakMap,P$=new WeakMap,R$=new WeakSet,pJ=async function(){let Z=O(this,K0,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(O(this,x0,"f")!==void 0)try{let V=await O(this,x0,"f");Y=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Q=Z.contextTokenThreshold??gJ;if(Y<Q)return!1;let z=Z.model??O(this,K0,"f").params.model,J=Z.summaryPrompt??mJ,X=O(this,K0,"f").params.messages;if(X[X.length-1].role==="assistant"){let V=X[X.length-1];if(Array.isArray(V.content)){let G=V.content.filter((H)=>H.type!=="tool_use");if(G.length===0)X.pop();else V.content=G}}let K=await this.client.beta.messages.create({model:z,messages:[...X,{role:"user",content:[{type:"text",text:J}]}],max_tokens:O(this,K0,"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,K0,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(O(this,U5,"f"))throw new j("Cannot iterate over a consumed stream");L(this,U5,!0,"f"),L(this,I2,!0,"f"),L(this,R1,void 0,"f");try{while(!0){let Z;try{if(O(this,K0,"f").params.max_iterations&&O(this,P$,"f")>=O(this,K0,"f").params.max_iterations)break;L(this,I2,!1,"f"),L(this,R1,void 0,"f"),L(this,P$,($=O(this,P$,"f"),$++,$),"f"),L(this,x0,void 0,"f");let{max_iterations:Y,compactionControl:Q,...z}=O(this,K0,"f").params;if(z.stream)Z=this.client.beta.messages.stream({...z},O(this,j$,"f")),L(this,x0,Z.finalMessage(),"f"),O(this,x0,"f").catch(()=>{}),yield Z;else L(this,x0,this.client.beta.messages.create({...z,stream:!1},O(this,j$,"f")),"f"),yield O(this,x0,"f");if(!await O(this,R$,"m",pJ).call(this)){if(!O(this,I2,"f")){let{role:K,content:V}=await O(this,x0,"f");O(this,K0,"f").params.messages.push({role:K,content:V})}let X=await O(this,R$,"m",X4).call(this,O(this,K0,"f").params.messages.at(-1));if(X)O(this,K0,"f").params.messages.push(X);else if(!O(this,I2,"f"))break}}finally{if(Z)Z.abort()}}if(!O(this,x0,"f"))throw new j("ToolRunner concluded without a message from the server");O(this,n1,"f").resolve(await O(this,x0,"f"))}catch(Z){throw L(this,U5,!1,"f"),O(this,n1,"f").promise.catch(()=>{}),O(this,n1,"f").reject(Z),L(this,n1,uJ(),"f"),Z}}setMessagesParams($){if(typeof $==="function")O(this,K0,"f").params=$(O(this,K0,"f").params);else O(this,K0,"f").params=$;L(this,I2,!0,"f"),L(this,R1,void 0,"f")}async generateToolResponse(){let $=await O(this,x0,"f")??this.params.messages.at(-1);if(!$)return null;return O(this,R$,"m",X4).call(this,$)}done(){return O(this,n1,"f").promise}async runUntilDone(){if(!O(this,U5,"f"))for await(let $ of this);return this.done()}get params(){return O(this,K0,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}X4=async function(Z){if(O(this,R1,"f")!==void 0)return O(this,R1,"f");return L(this,R1,Vq(O(this,K0,"f").params,Z),"f"),O(this,R1,"f")};async function Vq($,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 W5?X.content:`Error: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}))}}class q5{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new o1;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 q5(J$($.body),Z)}}class D$ extends s{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(a`/v1/messages/batches/${$}?beta=true`,{...Y,headers:I([{"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",a0,{query:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(a`/v1/messages/batches/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:Q}=Z??{};return this._client.post(a`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:I([{"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:I([{"anthropic-beta":[...z??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,X)=>q5.fromResponse(X.response,X.controller))}}var dJ={"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"},Hq=["claude-opus-4-6"];class r1 extends s{constructor(){super(...arguments);this.batches=new D$(this._client)}create($,Z){let Y=cJ($),{betas:Q,...z}=Y;if(z.model in dJ)console.warn(`The model '${z.model}' is deprecated and will reach end-of-life on ${dJ[z.model]}
159
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(z.model in Hq&&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=b8[z.model]??void 0;J=this._client.calculateNonstreamingTimeout(z.max_tokens,K)}let X=f8(z.tools,z.messages);return this._client.post("/v1/messages?beta=true",{body:z,timeout:J??600000,...Z,headers:I([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:I([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>Z4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return L$.createMessage(this,$,Z)}countTokens($,Z){let Y=cJ($),{betas:Q,...z}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:z,...Z,headers:I([{"anthropic-beta":[...Q??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new A$(this._client,$,Z)}}function cJ($){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}}}r1.Batches=D$;r1.BetaToolRunner=A$;r1.ToolError=W5;class T$ extends s{create($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.post(a`/v1/skills/${$}/versions?beta=true`,V5({body:z,...Y,headers:I([{"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(a`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.getAPIList(a`/v1/skills/${$}/versions?beta=true`,H$,{query:z,...Y,headers:I([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:Q,betas:z}=Z;return this._client.delete(a`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class B5 extends s{constructor(){super(...arguments);this.versions=new T$(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",V5({body:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(a`/v1/skills/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/skills?beta=true",H$,{query:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(a`/v1/skills/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}B5.Versions=T$;class J1 extends s{constructor(){super(...arguments);this.models=new B$(this._client),this.messages=new r1(this._client),this.files=new q$(this._client),this.skills=new B5(this._client)}}J1.Models=B$;J1.Messages=r1;J1.Files=q$;J1.Skills=B5;class N5 extends s{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Z,headers:I([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function lJ($){return $?.output_config?.format}function K4($,Z,Y){let Q=lJ(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 V4($,Z,Y)}function V4($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=Bq(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 Bq($,Z){let Y=lJ($);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 p0,a1,O5,I$,u8,w$,S$,d8,k$,j1,f$,c8,l8,w2,o8,i8,b$,G4,oJ,H4,W4,U4,q4,iJ,nJ="__json_buf";function rJ($){return $.type==="tool_use"||$.type==="server_tool_use"}class y${constructor($,Z){p0.add(this),this.messages=[],this.receivedMessages=[],a1.set(this,void 0),O5.set(this,null),this.controller=new AbortController,I$.set(this,void 0),u8.set(this,()=>{}),w$.set(this,()=>{}),S$.set(this,void 0),d8.set(this,()=>{}),k$.set(this,()=>{}),j1.set(this,{}),f$.set(this,!1),c8.set(this,!1),l8.set(this,!1),w2.set(this,!1),o8.set(this,void 0),i8.set(this,void 0),b$.set(this,void 0),H4.set(this,(Y)=>{if(L(this,c8,!0,"f"),E1(Y))Y=new E0;if(Y instanceof E0)return L(this,l8,!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)))}),L(this,I$,new Promise((Y,Q)=>{L(this,u8,Y,"f"),L(this,w$,Q,"f")}),"f"),L(this,S$,new Promise((Y,Q)=>{L(this,d8,Y,"f"),L(this,k$,Q,"f")}),"f"),O(this,I$,"f").catch(()=>{}),O(this,S$,"f").catch(()=>{}),L(this,O5,$,"f"),L(this,b$,Z?.logger??console,"f")}get response(){return O(this,o8,"f")}get request_id(){return O(this,i8,"f")}async withResponse(){L(this,w2,!0,"f");let $=await O(this,I$,"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 y$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new y$(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return L(z,O5,{...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,H4,"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,p0,"m",W4).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,p0,"m",U4).call(this,K);if(X.controller.signal?.aborted)throw new E0;O(this,p0,"m",q4).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;L(this,o8,$,"f"),L(this,i8,$?.headers.get("request-id"),"f"),O(this,u8,"f").call(this,$),this._emit("connect")}get ended(){return O(this,f$,"f")}get errored(){return O(this,c8,"f")}get aborted(){return O(this,l8,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,j1,"f")[$]||(O(this,j1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,j1,"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,j1,"f")[$]||(O(this,j1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(L(this,w2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){L(this,w2,!0,"f"),await O(this,S$,"f")}get currentMessage(){return O(this,a1,"f")}async finalMessage(){return await this.done(),O(this,p0,"m",G4).call(this)}async finalText(){return await this.done(),O(this,p0,"m",oJ).call(this)}_emit($,...Z){if(O(this,f$,"f"))return;if($==="end")L(this,f$,!0,"f"),O(this,d8,"f").call(this);let Y=O(this,j1,"f")[$];if(Y)O(this,j1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,w2,"f")&&!Y?.length)Promise.reject(Q);O(this,w$,"f").call(this,Q),O(this,k$,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,w2,"f")&&!Y?.length)Promise.reject(Q);O(this,w$,"f").call(this,Q),O(this,k$,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,p0,"m",G4).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,p0,"m",W4).call(this),this._connected(null);let z=v0.fromReadableStream($,this.controller);for await(let J of z)O(this,p0,"m",U4).call(this,J);if(z.controller.signal?.aborted)throw new E0;O(this,p0,"m",q4).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(a1=new WeakMap,O5=new WeakMap,I$=new WeakMap,u8=new WeakMap,w$=new WeakMap,S$=new WeakMap,d8=new WeakMap,k$=new WeakMap,j1=new WeakMap,f$=new WeakMap,c8=new WeakMap,l8=new WeakMap,w2=new WeakMap,o8=new WeakMap,i8=new WeakMap,b$=new WeakMap,H4=new WeakMap,p0=new WeakSet,G4=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},oJ=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(" ")},W4=function(){if(this.ended)return;L(this,a1,void 0,"f")},U4=function(Z){if(this.ended)return;let Y=O(this,p0,"m",iJ).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(rJ(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:aJ(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(K4(Y,O(this,O5,"f"),{logger:O(this,b$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{L(this,a1,Y,"f");break}case"content_block_start":case"message_delta":break}},q4=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 L(this,a1,void 0,"f"),K4(Z,O(this,O5,"f"),{logger:O(this,b$,"f")})},iJ=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.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&&rJ(Q)){let z=Q[nJ]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,nJ,{value:z,enumerable:!1,writable:!0}),z)J.input=y8(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:aJ(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 v0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function aJ($){}class v$ extends s{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(a`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",a0,{query:$,...Z})}delete($,Z){return this._client.delete(a`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(a`/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:I([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,z)=>q5.fromResponse(z.response,z.controller))}}class S2 extends s{constructor(){super(...arguments);this.batches=new v$(this._client)}create($,Z){if($.model in sJ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${sJ[$.model]}
160
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in Oq&&$.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=b8[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,z)}let Q=f8($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:I([Q,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>V4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return y$.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var sJ={"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"},Oq=["claude-opus-4-6"];S2.Batches=v$;class C5 extends s{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(a`/v1/models/${$}`,{...Y,headers:I([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models",a0,{query:Q,...Z,headers:I([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var x$=($)=>{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 B4,N4,n8,tJ,eJ="\\n\\nHuman:",$7="\\n\\nAssistant:";class e{constructor({baseURL:$=x$("ANTHROPIC_BASE_URL"),apiKey:Z=x$("ANTHROPIC_API_KEY")??null,authToken:Y=x$("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){B4.add(this),n8.set(this,void 0);let z={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!z.dangerouslyAllowBrowser&&NJ())throw new j(`It looks like you're running in a browser-like environment.
161
+ Wrap your summary in <summary></summary> tags.`;var P$,B5,w2,V0,A$,h0,P1,a1,D$,eJ,H4;function $7(){let $,Z;return{promise:new Promise((Q,z)=>{$=Q,Z=z}),resolve:$,reject:Z}}class T${constructor($,Z,Y){P$.add(this),this.client=$,B5.set(this,!1),w2.set(this,!1),V0.set(this,void 0),A$.set(this,void 0),h0.set(this,void 0),P1.set(this,void 0),a1.set(this,void 0),D$.set(this,0),L(this,V0,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let z=["BetaToolRunner",...z4(Z.tools,Z.messages)].join(", ");L(this,A$,{...Y,headers:I([{"x-stainless-helper":z},Y?.headers])},"f"),L(this,a1,$7(),"f")}async*[(B5=new WeakMap,w2=new WeakMap,V0=new WeakMap,A$=new WeakMap,h0=new WeakMap,P1=new WeakMap,a1=new WeakMap,D$=new WeakMap,P$=new WeakSet,eJ=async function(){let Z=O(this,V0,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(O(this,h0,"f")!==void 0)try{let V=await O(this,h0,"f");Y=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Q=Z.contextTokenThreshold??sJ;if(Y<Q)return!1;let z=Z.model??O(this,V0,"f").params.model,J=Z.summaryPrompt??tJ,X=O(this,V0,"f").params.messages;if(X[X.length-1].role==="assistant"){let V=X[X.length-1];if(Array.isArray(V.content)){let G=V.content.filter((W)=>W.type!=="tool_use");if(G.length===0)X.pop();else V.content=G}}let K=await this.client.beta.messages.create({model:z,messages:[...X,{role:"user",content:[{type:"text",text:J}]}],max_tokens:O(this,V0,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(K.content[0]?.type!=="text")throw new P("Expected text response for compaction");return O(this,V0,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(O(this,B5,"f"))throw new P("Cannot iterate over a consumed stream");L(this,B5,!0,"f"),L(this,w2,!0,"f"),L(this,P1,void 0,"f");try{while(!0){let Z;try{if(O(this,V0,"f").params.max_iterations&&O(this,D$,"f")>=O(this,V0,"f").params.max_iterations)break;L(this,w2,!1,"f"),L(this,P1,void 0,"f"),L(this,D$,($=O(this,D$,"f"),$++,$),"f"),L(this,h0,void 0,"f");let{max_iterations:Y,compactionControl:Q,...z}=O(this,V0,"f").params;if(z.stream)Z=this.client.beta.messages.stream({...z},O(this,A$,"f")),L(this,h0,Z.finalMessage(),"f"),O(this,h0,"f").catch(()=>{}),yield Z;else L(this,h0,this.client.beta.messages.create({...z,stream:!1},O(this,A$,"f")),"f"),yield O(this,h0,"f");if(!await O(this,P$,"m",eJ).call(this)){if(!O(this,w2,"f")){let{role:K,content:V}=await O(this,h0,"f");O(this,V0,"f").params.messages.push({role:K,content:V})}let X=await O(this,P$,"m",H4).call(this,O(this,V0,"f").params.messages.at(-1));if(X)O(this,V0,"f").params.messages.push(X);else if(!O(this,w2,"f"))break}}finally{if(Z)Z.abort()}}if(!O(this,h0,"f"))throw new P("ToolRunner concluded without a message from the server");O(this,a1,"f").resolve(await O(this,h0,"f"))}catch(Z){throw L(this,B5,!1,"f"),O(this,a1,"f").promise.catch(()=>{}),O(this,a1,"f").reject(Z),L(this,a1,$7(),"f"),Z}}setMessagesParams($){if(typeof $==="function")O(this,V0,"f").params=$(O(this,V0,"f").params);else O(this,V0,"f").params=$;L(this,w2,!0,"f"),L(this,P1,void 0,"f")}async generateToolResponse(){let $=await O(this,h0,"f")??this.params.messages.at(-1);if(!$)return null;return O(this,P$,"m",H4).call(this,$)}done(){return O(this,a1,"f").promise}async runUntilDone(){if(!O(this,B5,"f"))for await(let $ of this);return this.done()}get params(){return O(this,V0,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}H4=async function(Z){if(O(this,P1,"f")!==void 0)return O(this,P1,"f");return L(this,P1,Aq(O(this,V0,"f").params,Z),"f"),O(this,P1,"f")};async function Aq($,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 q5?X.content:`Error: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}))}}class N5{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new n1;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 P("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 P("Attempted to iterate over a response with no body")}return new N5(K$($.body),Z)}}class I$ extends t{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(s`/v1/messages/batches/${$}?beta=true`,{...Y,headers:I([{"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",e0,{query:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(s`/v1/messages/batches/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:Q}=Z??{};return this._client.post(s`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:I([{"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 P(`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:I([{"anthropic-beta":[...z??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,X)=>N5.fromResponse(X.response,X.controller))}}var Z7={"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"},Tq=["claude-opus-4-6"];class s1 extends t{constructor(){super(...arguments);this.batches=new I$(this._client)}create($,Z){let Y=Y7($),{betas:Q,...z}=Y;if(z.model in Z7)console.warn(`The model '${z.model}' is deprecated and will reach end-of-life on ${Z7[z.model]}
162
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(z.model in Tq&&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=_8[z.model]??void 0;J=this._client.calculateNonstreamingTimeout(z.max_tokens,K)}let X=x8(z.tools,z.messages);return this._client.post("/v1/messages?beta=true",{body:z,timeout:J??600000,...Z,headers:I([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:I([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>X4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return j$.createMessage(this,$,Z)}countTokens($,Z){let Y=Y7($),{betas:Q,...z}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:z,...Z,headers:I([{"anthropic-beta":[...Q??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new T$(this._client,$,Z)}}function Y7($){if(!$.output_format)return $;if($.output_config?.format)throw new P("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}}}s1.Batches=I$;s1.BetaToolRunner=T$;s1.ToolError=q5;class S$ extends t{create($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.post(s`/v1/skills/${$}/versions?beta=true`,W5({body:z,...Y,headers:I([{"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(s`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:Q,...z}=Z??{};return this._client.getAPIList(s`/v1/skills/${$}/versions?beta=true`,U$,{query:z,...Y,headers:I([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:Q,betas:z}=Z;return this._client.delete(s`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...z??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class O5 extends t{constructor(){super(...arguments);this.versions=new S$(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",W5({body:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(s`/v1/skills/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/skills?beta=true",U$,{query:Q,...Z,headers:I([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(s`/v1/skills/${$}?beta=true`,{...Y,headers:I([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}O5.Versions=S$;class K1 extends t{constructor(){super(...arguments);this.models=new O$(this._client),this.messages=new s1(this._client),this.files=new N$(this._client),this.skills=new O5(this._client)}}K1.Models=O$;K1.Messages=s1;K1.Files=N$;K1.Skills=O5;class C5 extends t{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Z,headers:I([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function Q7($){return $?.output_config?.format}function U4($,Z,Y){let Q=Q7(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 q4($,Z,Y)}function q4($,Z,Y){let Q=null,z=$.content.map((J)=>{if(J.type==="text"){let X=kq(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 kq($,Z){let Y=Q7($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new P(`Failed to parse structured output: ${Q}`)}}var d0,t1,M5,w$,o8,k$,f$,i8,b$,A1,y$,n8,r8,k2,a8,s8,v$,B4,z7,N4,O4,C4,M4,J7,X7="__json_buf";function K7($){return $.type==="tool_use"||$.type==="server_tool_use"}class x${constructor($,Z){d0.add(this),this.messages=[],this.receivedMessages=[],t1.set(this,void 0),M5.set(this,null),this.controller=new AbortController,w$.set(this,void 0),o8.set(this,()=>{}),k$.set(this,()=>{}),f$.set(this,void 0),i8.set(this,()=>{}),b$.set(this,()=>{}),A1.set(this,{}),y$.set(this,!1),n8.set(this,!1),r8.set(this,!1),k2.set(this,!1),a8.set(this,void 0),s8.set(this,void 0),v$.set(this,void 0),N4.set(this,(Y)=>{if(L(this,n8,!0,"f"),L1(Y))Y=new F0;if(Y instanceof F0)return L(this,r8,!0,"f"),this._emit("abort",Y);if(Y instanceof P)return this._emit("error",Y);if(Y instanceof Error){let Q=new P(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new P(String(Y)))}),L(this,w$,new Promise((Y,Q)=>{L(this,o8,Y,"f"),L(this,k$,Q,"f")}),"f"),L(this,f$,new Promise((Y,Q)=>{L(this,i8,Y,"f"),L(this,b$,Q,"f")}),"f"),O(this,w$,"f").catch(()=>{}),O(this,f$,"f").catch(()=>{}),L(this,M5,$,"f"),L(this,v$,Z?.logger??console,"f")}get response(){return O(this,a8,"f")}get request_id(){return O(this,s8,"f")}async withResponse(){L(this,k2,!0,"f");let $=await O(this,w$,"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 x$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let z=new x$(Z,{logger:Q});for(let J of Z.messages)z._addMessageParam(J);return L(z,M5,{...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,N4,"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,d0,"m",O4).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,d0,"m",C4).call(this,K);if(X.controller.signal?.aborted)throw new F0;O(this,d0,"m",M4).call(this)}finally{if(Q&&z)Q.removeEventListener("abort",z)}}_connected($){if(this.ended)return;L(this,a8,$,"f"),L(this,s8,$?.headers.get("request-id"),"f"),O(this,o8,"f").call(this,$),this._emit("connect")}get ended(){return O(this,y$,"f")}get errored(){return O(this,n8,"f")}get aborted(){return O(this,r8,"f")}abort(){this.controller.abort()}on($,Z){return(O(this,A1,"f")[$]||(O(this,A1,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=O(this,A1,"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,A1,"f")[$]||(O(this,A1,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(L(this,k2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){L(this,k2,!0,"f"),await O(this,f$,"f")}get currentMessage(){return O(this,t1,"f")}async finalMessage(){return await this.done(),O(this,d0,"m",B4).call(this)}async finalText(){return await this.done(),O(this,d0,"m",z7).call(this)}_emit($,...Z){if(O(this,y$,"f"))return;if($==="end")L(this,y$,!0,"f"),O(this,i8,"f").call(this);let Y=O(this,A1,"f")[$];if(Y)O(this,A1,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!O(this,k2,"f")&&!Y?.length)Promise.reject(Q);O(this,k$,"f").call(this,Q),O(this,b$,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!O(this,k2,"f")&&!Y?.length)Promise.reject(Q);O(this,k$,"f").call(this,Q),O(this,b$,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,d0,"m",B4).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,d0,"m",O4).call(this),this._connected(null);let z=_0.fromReadableStream($,this.controller);for await(let J of z)O(this,d0,"m",C4).call(this,J);if(z.controller.signal?.aborted)throw new F0;O(this,d0,"m",M4).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(t1=new WeakMap,M5=new WeakMap,w$=new WeakMap,o8=new WeakMap,k$=new WeakMap,f$=new WeakMap,i8=new WeakMap,b$=new WeakMap,A1=new WeakMap,y$=new WeakMap,n8=new WeakMap,r8=new WeakMap,k2=new WeakMap,a8=new WeakMap,s8=new WeakMap,v$=new WeakMap,N4=new WeakMap,d0=new WeakSet,B4=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},z7=function(){if(this.receivedMessages.length===0)throw new P("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 P("stream ended without producing a content block with type=text");return Z.join(" ")},O4=function(){if(this.ended)return;L(this,t1,void 0,"f")},C4=function(Z){if(this.ended)return;let Y=O(this,d0,"m",J7).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(K7(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:V7(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(U4(Y,O(this,M5,"f"),{logger:O(this,v$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{L(this,t1,Y,"f");break}case"content_block_start":case"message_delta":break}},M4=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let Z=O(this,t1,"f");if(!Z)throw new P("request ended without sending any chunks");return L(this,t1,void 0,"f"),U4(Z,O(this,M5,"f"),{logger:O(this,v$,"f")})},J7=function(Z){let Y=O(this,t1,"f");if(Z.type==="message_start"){if(Y)throw new P(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new P(`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&&K7(Q)){let z=Q[X7]||"";z+=Z.delta.partial_json;let J={...Q};if(Object.defineProperty(J,X7,{value:z,enumerable:!1,writable:!0}),z)J.input=h8(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:V7(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 _0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function V7($){}class _$ extends t{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(s`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",e0,{query:$,...Z})}delete($,Z){return this._client.delete(s`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(s`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new P(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:I([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,z)=>N5.fromResponse(z.response,z.controller))}}class f2 extends t{constructor(){super(...arguments);this.batches=new _$(this._client)}create($,Z){if($.model in G7)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${G7[$.model]}
163
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in bq&&$.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=_8[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,z)}let Q=x8($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:I([Q,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>q4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return x$.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var G7={"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"},bq=["claude-opus-4-6"];f2.Batches=_$;class E5 extends t{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(s`/v1/models/${$}`,{...Y,headers:I([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models",e0,{query:Q,...Z,headers:I([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var h$=($)=>{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 E4,F4,t8,W7,H7="\\n\\nHuman:",U7="\\n\\nAssistant:";class $0{constructor({baseURL:$=h$("ANTHROPIC_BASE_URL"),apiKey:Z=h$("ANTHROPIC_API_KEY")??null,authToken:Y=h$("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){E4.add(this),t8.set(this,void 0);let z={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!z.dangerouslyAllowBrowser&&TJ())throw new P(`It looks like you're running in a browser-like environment.
161
164
 
162
165
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
163
166
  If you understand the risks and have appropriate mitigations in place,
164
167
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
165
168
 
166
169
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
167
- `);this.baseURL=z.baseURL,this.timeout=z.timeout??N4.DEFAULT_TIMEOUT,this.logger=z.logger??console;let J="warn";this.logLevel=J,this.logLevel=oZ(z.logLevel,"ClientOptions.logLevel",this)??oZ(x$("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=z.fetchOptions,this.maxRetries=z.maxRetries??2,this.fetch=z.fetch??CJ(),L(this,n8,EJ,"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 I([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return I([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return I([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return FJ($)}getUserAgent(){return`${this.constructor.name}/JS ${l1}`}defaultIdempotencyKey(){return`stainless-node-retry-${mZ()}`}makeStatusError($,Z,Y,Q){return X0.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!O(this,B4,"m",tJ).call(this)&&Y||this.baseURL,z=VJ($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),X=Object.fromEntries(z.searchParams);if(!dZ(J)||!dZ(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 A2(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 V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),G=Y===void 0?"":`, retryOf: ${Y}`,H=Date.now();if(H0(this).debug(`[${V}] sending request`,F1({retryOfRequestLogID:Y,method:Q.method,url:X,options:Q,headers:J.headers})),Q.signal?.aborted)throw new E0;let W=new AbortController,U=await this.fetchWithTimeout(X,J,K,W).catch(r5),q=Date.now();if(U instanceof globalThis.Error){let M=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new E0;let F=E1(U)||/timed? ?out/i.test(String(U)+("cause"in U?String(U.cause):""));if(Z)return H0(this).info(`[${V}] connection ${F?"timed out":"failed"} - ${M}`),H0(this).debug(`[${V}] connection ${F?"timed out":"failed"} (${M})`,F1({retryOfRequestLogID:Y,url:X,durationMs:q-H,message:U.message})),this.retryRequest(Q,Z,Y??V);if(H0(this).info(`[${V}] connection ${F?"timed out":"failed"} - error; no more retries left`),H0(this).debug(`[${V}] connection ${F?"timed out":"failed"} (error; no more retries left)`,F1({retryOfRequestLogID:Y,url:X,durationMs:q-H,message:U.message})),F)throw new a5;throw new P2({cause:U})}let N=[...U.headers.entries()].filter(([M])=>M==="request-id").map(([M,F])=>", "+M+": "+JSON.stringify(F)).join(""),C=`[${V}${G}${N}] ${J.method} ${X} ${U.ok?"succeeded":"failed"} with status ${U.status} in ${q-H}ms`;if(!U.ok){let M=await this.shouldRetry(U);if(Z&&M){let c=`retrying, ${Z} attempts remaining`;return await MJ(U.body),H0(this).info(`${C} - ${c}`),H0(this).debug(`[${V}] response error (${c})`,F1({retryOfRequestLogID:Y,url:U.url,status:U.status,headers:U.headers,durationMs:q-H})),this.retryRequest(Q,Z,Y??V,U.headers)}let F=M?"error; no more retries left":"error; not retryable";H0(this).info(`${C} - ${F}`);let T=await U.text().catch((c)=>r5(c).message),v=j8(T),D=v?void 0:T;throw H0(this).debug(`[${V}] response error (${F})`,F1({retryOfRequestLogID:Y,url:U.url,status:U.status,headers:U.headers,message:D,durationMs:Date.now()-H})),this.makeStatusError(U.status,v,D,U.headers)}return H0(this).info(C),H0(this).debug(`[${V}] response start`,F1({retryOfRequestLogID:Y,url:U.url,status:U.status,headers:U.headers,durationMs:q-H})),{response:U,options:Q,controller:W,requestLogID:V,retryOfRequestLogID:Y,startTime:H}}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 w8(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 V=setTimeout(K,Y),G=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,H={signal:Q.signal,...G?{duplex:"half"}:{},method:"GET",...X};if(J)H.method=J.toUpperCase();try{return await this.fetch.call(void 0,$,H)}finally{clearTimeout(V)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,Q){let 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 WJ(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)HJ("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:V,body:G}=this.buildBody({options:Y}),H=await this.buildHeaders({options:$,method:Q,bodyHeaders:V,retryCount:Z});return{req:{method:Q,headers:H,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"},...G&&{body:G},...this.fetchOptions??{},...Y.fetchOptions??{}},url:K,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:Q}){let z={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();z[this.idempotencyHeader]=$.idempotencyKey}let J=I([z,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...OJ(),...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=I([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:P8($)};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,n8,"f").call(this,{body:$,headers:Y})}}N4=e,n8=new WeakMap,B4=new WeakSet,tJ=function(){return this.baseURL!=="https://api.anthropic.com"};e.Anthropic=N4;e.HUMAN_PROMPT=eJ;e.AI_PROMPT=$7;e.DEFAULT_TIMEOUT=600000;e.AnthropicError=j;e.APIError=X0;e.APIConnectionError=P2;e.APIConnectionTimeoutError=a5;e.APIUserAbortError=E0;e.NotFoundError=$$;e.ConflictError=Z$;e.RateLimitError=Q$;e.BadRequestError=s5;e.AuthenticationError=t5;e.InternalServerError=z$;e.PermissionDeniedError=e5;e.UnprocessableEntityError=Y$;e.toFile=S8;class X1 extends e{constructor(){super(...arguments);this.completions=new N5(this),this.messages=new S2(this),this.models=new C5(this),this.beta=new J1(this)}}X1.Completions=N5;X1.Messages=S2;X1.Models=C5;X1.Beta=J1;import{existsSync as Mq,readFileSync as Eq,writeFileSync as Fq}from"fs";import{basename as O4}from"path";var Z7=50;class C4{entries=[];saveState($){let Z=Mq($),Y=Z?Eq($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>Z7)this.entries=this.entries.slice(-Z7)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${O4($.path)} was a new file. Remove it manually if needed.`;Fq($.path,$.content);let Z=$.content.split(`
168
- `).length;return`Undo: restored ${O4($.path)} (${Z} lines, from ${Y7($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${O4($.path)} (${Y7($.timestamp)})`}}function Y7($){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`}Z0();var k=[{name:"read_file",description:"Read file contents. For large files, use offset/limit to read specific line ranges.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},offset:{type:"number",description:"Start reading from this line number (1-based). Optional."},limit:{type:"number",description:"Max lines to read. Optional, defaults to 500."}},required:["path"]}},{name:"write_file",description:"Create a new file or completely overwrite an existing file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write"},content:{type:"string",description:"Full file content"}},required:["path","content"]}},{name:"edit_file",description:"Make a precise edit to a file. Finds old_text and replaces it with new_text. The old_text must match exactly (including whitespace). "+"Use this instead of write_file when modifying existing files \u2014 it preserves the rest of the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to edit"},old_text:{type:"string",description:"Exact text to find (must be unique in the file)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}},{name:"search_files",description:"Search file contents using a regex pattern (like grep). Returns matching lines with file paths and line numbers.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in. Defaults to cwd."},include:{type:"string",description:'Glob pattern to filter files, e.g. "*.ts" or "*.py"'}},required:["pattern"]}},{name:"find_files",description:"Find files by name pattern (glob). Returns matching file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.ts", "src/**/test*"'},path:{type:"string",description:"Base directory. Defaults to cwd."}},required:["pattern"]}},{name:"list_directory",description:"List files and directories with type indicators and sizes.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to list. Defaults to cwd."}},required:[]}},{name:"run_command",description:"Run a shell command. Use for: git operations, running tests, installing packages, building projects, or any CLI task. Commands run in the current working directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"number",description:"Timeout in seconds. Default 30, max 120."}},required:["command"]}},{name:"fetch_url",description:"Fetch the content of a URL. Use for: reading documentation, checking APIs, downloading config files, or verifying endpoints. Returns the response body as text. For HTML pages, returns a text-only extraction (no tags).",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method. Default GET.",enum:["GET","POST","PUT","DELETE","PATCH","HEAD"]},headers:{type:"object",description:"Optional request headers as key-value pairs."},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH)."}},required:["url"]}}];var _$=[{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:[]}}],r8=[{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:[]}}],a8=[{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"]}}],s8=_$.find(($)=>$.name==="get_news");import{resolve as L9,sep as vV}from"path";import{writeFileSync as yC}from"fs";h();import{existsSync as Lq,readFileSync as Rq}from"fs";import{join as jq}from"path";var k2=[{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}],t8="",F0=[],_0=new Set,X7=()=>jq(t8,"news-feeds.json");function e8(){if(!t8)return;let $={custom:F0,disabled:[..._0]};P(X7(),JSON.stringify($,null,2))}function Pq(){if(!t8)return;let $=X7();if(!Lq($)){F0=[],_0=new Set;return}try{let Z=JSON.parse(Rq($,"utf-8"));F0=Z.custom||[],_0=new Set(Z.disabled||[])}catch{F0=[],_0=new Set}}function K7($){t8=$,Pq()}function $6(){return[...k2.filter((Z)=>!_0.has(Z.url)),...F0]}function p$($,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([...k2,...F0].some((V)=>V.url===J))return"Error: essa URL ja esta cadastrada.";let K={name:Q,url:J,category:z};return F0=[...F0,K],e8(),K}function Z6($){let Z=$.toLowerCase().trim(),Y=F0.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return F0=[...F0.slice(0,Y),...F0.slice(Y+1)],e8(),!0}function Y6($){let Z=$.toLowerCase().trim(),Y=k2.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(_0.has(Y.url))return!1;return _0=new Set([..._0,Y.url]),e8(),!0}function Q6($){let Z=$.toLowerCase().trim(),Y=k2.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!_0.has(Y.url))return!1;return _0=new Set([..._0].filter((Q)=>Q!==Y.url)),e8(),!0}function z6(){let $=["Fontes de noticias:"];$.push(`
169
- --- Built-in ---`);for(let Z of k2){let Y=_0.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(F0.length>0){$.push(`
170
- --- Custom ---`);for(let Z of F0)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
171
- Total: ${$6().length} ativas (${k2.length} built-in, ${F0.length} custom, ${_0.size} desativadas)`),$.join(`
172
- `)}var Aq={SP:[{name:"G1 Sao Paulo",url:"https://g1.globo.com/rss/g1/sao-paulo/"},{name:"Folha SP",url:"https://feeds.folha.uol.com.br/folha/cotidiano/rss091.xml"}],RJ:[{name:"G1 Rio",url:"https://g1.globo.com/rss/g1/rio-de-janeiro/"}],MG:[{name:"G1 Minas",url:"https://g1.globo.com/rss/g1/minas-gerais/"}],BA:[{name:"G1 Bahia",url:"https://g1.globo.com/rss/g1/bahia/"}],PR:[{name:"G1 Parana",url:"https://g1.globo.com/rss/g1/parana/"}],RS:[{name:"G1 RS",url:"https://g1.globo.com/rss/g1/rs/"}],PE:[{name:"G1 Pernambuco",url:"https://g1.globo.com/rss/g1/pernambuco/"}],CE:[{name:"G1 Ceara",url:"https://g1.globo.com/rss/g1/ceara/"}]};function V7($){let Z=[],Y=[...new Set($.map((Q)=>Q.toUpperCase()))];for(let Q of Y){let z=Aq[Q];if(!z)continue;for(let J of z){if([...k2,...F0].map((V)=>V.url).includes(J.url))continue;if(typeof p$(J.name,J.url,`regional-${Q.toLowerCase()}`)!=="string")Z.push(`${J.name} (${Q})`)}}return Z}async function E4($,Z=3){let Y=`regional-${$.toLowerCase()}`;if(!$6().filter((z)=>z.category===Y||z.category==="brazil").length)return`Nenhum feed de noticias registrado para ${$}. Adicione bairros para ativar feeds regionais.`;return P1([Y,"brazil"],Z)}var Q7=2097152,M4=10,Dq=1e4;function Tq($,Z,Y){let Q=[],z=/<item[\s>]([\s\S]*?)<\/item>/gi,J;while((J=z.exec($))!==null){let X=J[1],K=z7(X,Z,Y);if(K)Q.push(K);if(Q.length>=M4)break}if(Q.length===0){let X=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((J=X.exec($))!==null){let K=J[1],V=z7(K,Z,Y);if(V)Q.push(V);if(Q.length>=M4)break}}return Q}function z7($,Z,Y){let Q=h$($,"title");if(!Q)return null;let z=h$($,"link")||fq($),J=Iq(z),X=h$($,"pubDate")||h$($,"published")||h$($,"updated"),K;if(X){let V=new Date(X);K=isNaN(V.getTime())?void 0:V}return{title:m$(Q),link:J,source:Z,category:Y,pubDate:K}}function Iq($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function wq($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function h$($,Z){let Y=wq(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 Sq($,Z){let Y=kq($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function kq($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return g$(z[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return g$(Q[1]);return"utf-8"}function g$($){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 fq($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var bq={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 m$($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>bq[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 F4($,Z=5){let Y=Math.max(1,Math.min(Z,M4));if($&&$.length===0)return{items:[],errors:[]};let Q=$6(),z=$?Q.filter((V)=>$.includes(V.category)):Q,J=await Promise.allSettled(z.map((V)=>vq(V,Y))),X=[],K=[];for(let V=0;V<J.length;V++){let G=J[V];if(G.status==="fulfilled")X.push(...G.value);else K.push(`${z[V].name}: ${yq(G.reason)}`)}return X.sort((V,G)=>{let H=V.pubDate?.getTime()||0;return(G.pubDate?.getTime()||0)-H}),{items:X,errors:K}}async function P1($,Z=5){if($&&$.length===0)return _q();let{items:Y,errors:Q}=await F4($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
173
- Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return xq(Y,Q)}function yq($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function vq($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),Dq);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)>Q7)return[];let X=z.body?.getReader();if(!X)return[];let K=[],V=0;while(!0){let{done:U,value:q}=await X.read();if(U)break;if(V+=q.byteLength,V>Q7)return X.cancel(),[];K.push(q)}let G=Buffer.concat(K),H=Sq(G,z.headers.get("content-type"));return Tq(H,$.name,$.category).slice(0,Z)}catch(z){throw clearTimeout(Q),z}}function xq($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Q=new Map;for(let K of $){let V=Q.get(K.category)||[];Q.set(K.category,[...V,K])}let z=[],J=["finance","business","tech","security","brazil","world"];for(let K of J){let V=Q.get(K);if(!V||V.length===0)continue;let G=Y[K],H=V.slice(0,8).map((W)=>{let U=W.pubDate?W.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${U?`[${U}]`:""} ${W.title} (${W.source})`});z.push(`--- ${G} ---
174
- ${H.join(`
170
+ `);this.baseURL=z.baseURL,this.timeout=z.timeout??F4.DEFAULT_TIMEOUT,this.logger=z.logger??console;let J="warn";this.logLevel=J,this.logLevel=sZ(z.logLevel,"ClientOptions.logLevel",this)??sZ(h$("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=z.fetchOptions,this.maxRetries=z.maxRetries??2,this.fetch=z.fetch??SJ(),L(this,t8,kJ,"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 I([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return I([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return I([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return fJ($)}getUserAgent(){return`${this.constructor.name}/JS ${i1}`}defaultIdempotencyKey(){return`stainless-node-retry-${lZ()}`}makeStatusError($,Z,Y,Q){return K0.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!O(this,E4,"m",W7).call(this)&&Y||this.baseURL,z=FJ($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),X=Object.fromEntries(z.searchParams);if(!nZ(J)||!nZ(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 P("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 T2(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 V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),G=Y===void 0?"":`, retryOf: ${Y}`,W=Date.now();if(H0(this).debug(`[${V}] sending request`,R1({retryOfRequestLogID:Y,method:Q.method,url:X,options:Q,headers:J.headers})),Q.signal?.aborted)throw new F0;let H=new AbortController,U=await this.fetchWithTimeout(X,J,K,H).catch(s5),q=Date.now();if(U instanceof globalThis.Error){let M=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new F0;let F=L1(U)||/timed? ?out/i.test(String(U)+("cause"in U?String(U.cause):""));if(Z)return H0(this).info(`[${V}] connection ${F?"timed out":"failed"} - ${M}`),H0(this).debug(`[${V}] connection ${F?"timed out":"failed"} (${M})`,R1({retryOfRequestLogID:Y,url:X,durationMs:q-W,message:U.message})),this.retryRequest(Q,Z,Y??V);if(H0(this).info(`[${V}] connection ${F?"timed out":"failed"} - error; no more retries left`),H0(this).debug(`[${V}] connection ${F?"timed out":"failed"} (error; no more retries left)`,R1({retryOfRequestLogID:Y,url:X,durationMs:q-W,message:U.message})),F)throw new t5;throw new D2({cause:U})}let N=[...U.headers.entries()].filter(([M])=>M==="request-id").map(([M,F])=>", "+M+": "+JSON.stringify(F)).join(""),C=`[${V}${G}${N}] ${J.method} ${X} ${U.ok?"succeeded":"failed"} with status ${U.status} in ${q-W}ms`;if(!U.ok){let M=await this.shouldRetry(U);if(Z&&M){let l=`retrying, ${Z} attempts remaining`;return await wJ(U.body),H0(this).info(`${C} - ${l}`),H0(this).debug(`[${V}] response error (${l})`,R1({retryOfRequestLogID:Y,url:U.url,status:U.status,headers:U.headers,durationMs:q-W})),this.retryRequest(Q,Z,Y??V,U.headers)}let F=M?"error; no more retries left":"error; not retryable";H0(this).info(`${C} - ${F}`);let T=await U.text().catch((l)=>s5(l).message),v=T8(T),D=v?void 0:T;throw H0(this).debug(`[${V}] response error (${F})`,R1({retryOfRequestLogID:Y,url:U.url,status:U.status,headers:U.headers,message:D,durationMs:Date.now()-W})),this.makeStatusError(U.status,v,D,U.headers)}return H0(this).info(C),H0(this).debug(`[${V}] response start`,R1({retryOfRequestLogID:Y,url:U.url,status:U.status,headers:U.headers,durationMs:q-W})),{response:U,options:Q,controller:H,requestLogID:V,retryOfRequestLogID:Y,startTime:W}}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 b8(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 V=setTimeout(K,Y),G=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,W={signal:Q.signal,...G?{duplex:"half"}:{},method:"GET",...X};if(J)W.method=J.toUpperCase();try{return await this.fetch.call(void 0,$,W)}finally{clearTimeout(V)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,Q){let 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 jJ(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 P("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)RJ("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:V,body:G}=this.buildBody({options:Y}),W=await this.buildHeaders({options:$,method:Q,bodyHeaders:V,retryCount:Z});return{req:{method:Q,headers:W,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"},...G&&{body:G},...this.fetchOptions??{},...Y.fetchOptions??{}},url:K,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:Q}){let z={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();z[this.idempotencyHeader]=$.idempotencyKey}let J=I([z,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...IJ(),...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=I([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:I8($)};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,t8,"f").call(this,{body:$,headers:Y})}}F4=$0,t8=new WeakMap,E4=new WeakSet,W7=function(){return this.baseURL!=="https://api.anthropic.com"};$0.Anthropic=F4;$0.HUMAN_PROMPT=H7;$0.AI_PROMPT=U7;$0.DEFAULT_TIMEOUT=600000;$0.AnthropicError=P;$0.APIError=K0;$0.APIConnectionError=D2;$0.APIConnectionTimeoutError=t5;$0.APIUserAbortError=F0;$0.NotFoundError=Y$;$0.ConflictError=Q$;$0.RateLimitError=J$;$0.BadRequestError=e5;$0.AuthenticationError=$$;$0.InternalServerError=X$;$0.PermissionDeniedError=Z$;$0.UnprocessableEntityError=z$;$0.toFile=y8;class V1 extends $0{constructor(){super(...arguments);this.completions=new C5(this),this.messages=new f2(this),this.models=new E5(this),this.beta=new K1(this)}}V1.Completions=C5;V1.Messages=f2;V1.Models=E5;V1.Beta=K1;import{existsSync as vq,readFileSync as xq,writeFileSync as _q}from"fs";import{basename as L4}from"path";var q7=50;class R4{entries=[];saveState($){let Z=vq($),Y=Z?xq($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>q7)this.entries=this.entries.slice(-q7)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${L4($.path)} was a new file. Remove it manually if needed.`;_q($.path,$.content);let Z=$.content.split(`
171
+ `).length;return`Undo: restored ${L4($.path)} (${Z} lines, from ${B7($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${L4($.path)} (${B7($.timestamp)})`}}function B7($){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`}Y0();var k=[{name:"read_file",description:"Read file contents. For large files, use offset/limit to read specific line ranges.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},offset:{type:"number",description:"Start reading from this line number (1-based). Optional."},limit:{type:"number",description:"Max lines to read. Optional, defaults to 500."}},required:["path"]}},{name:"write_file",description:"Create a new file or completely overwrite an existing file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write"},content:{type:"string",description:"Full file content"}},required:["path","content"]}},{name:"edit_file",description:"Make a precise edit to a file. Finds old_text and replaces it with new_text. The old_text must match exactly (including whitespace). "+"Use this instead of write_file when modifying existing files \u2014 it preserves the rest of the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to edit"},old_text:{type:"string",description:"Exact text to find (must be unique in the file)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}},{name:"search_files",description:"Search file contents using a regex pattern (like grep). Returns matching lines with file paths and line numbers.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in. Defaults to cwd."},include:{type:"string",description:'Glob pattern to filter files, e.g. "*.ts" or "*.py"'}},required:["pattern"]}},{name:"find_files",description:"Find files by name pattern (glob). Returns matching file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.ts", "src/**/test*"'},path:{type:"string",description:"Base directory. Defaults to cwd."}},required:["pattern"]}},{name:"list_directory",description:"List files and directories with type indicators and sizes.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to list. Defaults to cwd."}},required:[]}},{name:"run_command",description:"Run a shell command. Use for: git operations, running tests, installing packages, building projects, or any CLI task. Commands run in the current working directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"number",description:"Timeout in seconds. Default 30, max 120."}},required:["command"]}},{name:"fetch_url",description:"Fetch the content of a URL. Use for: reading documentation, checking APIs, downloading config files, or verifying endpoints. Returns the response body as text. For HTML pages, returns a text-only extraction (no tags).",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method. Default GET.",enum:["GET","POST","PUT","DELETE","PATCH","HEAD"]},headers:{type:"object",description:"Optional request headers as key-value pairs."},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH)."}},required:["url"]}}];var g$=[{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:[]}}],e8=[{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:[]}}],$6=[{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"]}}],Z6=g$.find(($)=>$.name==="get_news");import{resolve as A9,sep as iV}from"path";import{writeFileSync as sC}from"fs";g();import{existsSync as hq,readFileSync as gq}from"fs";import{join as mq}from"path";var b2=[{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}],Y6="",L0=[],g0=new Set,M7=()=>mq(Y6,"news-feeds.json");function Q6(){if(!Y6)return;let $={custom:L0,disabled:[...g0]};j(M7(),JSON.stringify($,null,2))}function pq(){if(!Y6)return;let $=M7();if(!hq($)){L0=[],g0=new Set;return}try{let Z=JSON.parse(gq($,"utf-8"));L0=Z.custom||[],g0=new Set(Z.disabled||[])}catch{L0=[],g0=new Set}}function E7($){Y6=$,pq()}function z6(){return[...b2.filter((Z)=>!g0.has(Z.url)),...L0]}function d$($,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([...b2,...L0].some((V)=>V.url===J))return"Error: essa URL ja esta cadastrada.";let K={name:Q,url:J,category:z};return L0=[...L0,K],Q6(),K}function J6($){let Z=$.toLowerCase().trim(),Y=L0.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return L0=[...L0.slice(0,Y),...L0.slice(Y+1)],Q6(),!0}function X6($){let Z=$.toLowerCase().trim(),Y=b2.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(g0.has(Y.url))return!1;return g0=new Set([...g0,Y.url]),Q6(),!0}function K6($){let Z=$.toLowerCase().trim(),Y=b2.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!g0.has(Y.url))return!1;return g0=new Set([...g0].filter((Q)=>Q!==Y.url)),Q6(),!0}function V6(){let $=["Fontes de noticias:"];$.push(`
172
+ --- Built-in ---`);for(let Z of b2){let Y=g0.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(L0.length>0){$.push(`
173
+ --- Custom ---`);for(let Z of L0)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
174
+ Total: ${z6().length} ativas (${b2.length} built-in, ${L0.length} custom, ${g0.size} desativadas)`),$.join(`
175
+ `)}var uq={SP:[{name:"G1 Sao Paulo",url:"https://g1.globo.com/rss/g1/sao-paulo/"},{name:"Folha SP",url:"https://feeds.folha.uol.com.br/folha/cotidiano/rss091.xml"}],RJ:[{name:"G1 Rio",url:"https://g1.globo.com/rss/g1/rio-de-janeiro/"}],MG:[{name:"G1 Minas",url:"https://g1.globo.com/rss/g1/minas-gerais/"}],BA:[{name:"G1 Bahia",url:"https://g1.globo.com/rss/g1/bahia/"}],PR:[{name:"G1 Parana",url:"https://g1.globo.com/rss/g1/parana/"}],RS:[{name:"G1 RS",url:"https://g1.globo.com/rss/g1/rs/"}],PE:[{name:"G1 Pernambuco",url:"https://g1.globo.com/rss/g1/pernambuco/"}],CE:[{name:"G1 Ceara",url:"https://g1.globo.com/rss/g1/ceara/"}]};function F7($){let Z=[],Y=[...new Set($.map((Q)=>Q.toUpperCase()))];for(let Q of Y){let z=uq[Q];if(!z)continue;for(let J of z){if([...b2,...L0].map((V)=>V.url).includes(J.url))continue;if(typeof d$(J.name,J.url,`regional-${Q.toLowerCase()}`)!=="string")Z.push(`${J.name} (${Q})`)}}return Z}async function P4($,Z=3){let Y=`regional-${$.toLowerCase()}`;if(!z6().filter((z)=>z.category===Y||z.category==="brazil").length)return`Nenhum feed de noticias registrado para ${$}. Adicione bairros para ativar feeds regionais.`;return D1([Y,"brazil"],Z)}var N7=2097152,j4=10,dq=1e4;function cq($,Z,Y){let Q=[],z=/<item[\s>]([\s\S]*?)<\/item>/gi,J;while((J=z.exec($))!==null){let X=J[1],K=O7(X,Z,Y);if(K)Q.push(K);if(Q.length>=j4)break}if(Q.length===0){let X=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((J=X.exec($))!==null){let K=J[1],V=O7(K,Z,Y);if(V)Q.push(V);if(Q.length>=j4)break}}return Q}function O7($,Z,Y){let Q=m$($,"title");if(!Q)return null;let z=m$($,"link")||rq($),J=lq(z),X=m$($,"pubDate")||m$($,"published")||m$($,"updated"),K;if(X){let V=new Date(X);K=isNaN(V.getTime())?void 0:V}return{title:u$(Q),link:J,source:Z,category:Y,pubDate:K}}function lq($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function oq($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m$($,Z){let Y=oq(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 iq($,Z){let Y=nq($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function nq($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return p$(z[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return p$(Q[1]);return"utf-8"}function p$($){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 rq($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var aq={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 u$($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>aq[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 A4($,Z=5){let Y=Math.max(1,Math.min(Z,j4));if($&&$.length===0)return{items:[],errors:[]};let Q=z6(),z=$?Q.filter((V)=>$.includes(V.category)):Q,J=await Promise.allSettled(z.map((V)=>tq(V,Y))),X=[],K=[];for(let V=0;V<J.length;V++){let G=J[V];if(G.status==="fulfilled")X.push(...G.value);else K.push(`${z[V].name}: ${sq(G.reason)}`)}return X.sort((V,G)=>{let W=V.pubDate?.getTime()||0;return(G.pubDate?.getTime()||0)-W}),{items:X,errors:K}}async function D1($,Z=5){if($&&$.length===0)return $B();let{items:Y,errors:Q}=await A4($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
176
+ Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return eq(Y,Q)}function sq($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function tq($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),dq);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)>N7)return[];let X=z.body?.getReader();if(!X)return[];let K=[],V=0;while(!0){let{done:U,value:q}=await X.read();if(U)break;if(V+=q.byteLength,V>N7)return X.cancel(),[];K.push(q)}let G=Buffer.concat(K),W=iq(G,z.headers.get("content-type"));return cq(W,$.name,$.category).slice(0,Z)}catch(z){throw clearTimeout(Q),z}}function eq($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Q=new Map;for(let K of $){let V=Q.get(K.category)||[];Q.set(K.category,[...V,K])}let z=[],J=["finance","business","tech","security","brazil","world"];for(let K of J){let V=Q.get(K);if(!V||V.length===0)continue;let G=Y[K],W=V.slice(0,8).map((H)=>{let U=H.pubDate?H.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${U?`[${U}]`:""} ${H.title} (${H.source})`});z.push(`--- ${G} ---
177
+ ${W.join(`
175
178
  `)}`)}let X=z.join(`
176
179
 
177
180
  `);if(Z.length>0)X+=`
178
181
 
179
- (Fontes indisponiveis: ${Z.join(", ")})`;return X}function _q(){let $=$6();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
180
- Uso: /news [categoria]`}var hq=15000,J7=5242880;async function G7($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),hq);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)>J7)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:U,value:q}=await J.read();if(U)break;if(K+=q.byteLength,K>J7)return J.cancel(),"Error: pagina muito grande";X.push(q)}let V=Buffer.concat(X),G=Q.headers.get("content-type"),H=gq(V,G);return pq(H)}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 gq($,Z){let Y=mq($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function mq($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return g$(J[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return g$(Q[1]);let z=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(z)return g$(z[1]);return"utf-8"}function pq($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?m$(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 V=$.match(K);if(V){Q=V[1];break}}}if(!Q){let X=[],K=/<p[^>]*>([\s\S]*?)<\/p>/gi,V;while((V=K.exec($))!==null){let G=m$(V[1]).trim();if(G.length>50)X.push(G)}Q=X.join(`
182
+ (Fontes indisponiveis: ${Z.join(", ")})`;return X}function $B(){let $=z6();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
183
+ Uso: /news [categoria]`}var ZB=15000,C7=5242880;async function L7($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),ZB);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)>C7)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:U,value:q}=await J.read();if(U)break;if(K+=q.byteLength,K>C7)return J.cancel(),"Error: pagina muito grande";X.push(q)}let V=Buffer.concat(X),G=Q.headers.get("content-type"),W=YB(V,G);return zB(W)}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 YB($,Z){let Y=QB($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function QB($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return p$(J[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return p$(Q[1]);let z=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(z)return p$(z[1]);return"utf-8"}function zB($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?u$(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 V=$.match(K);if(V){Q=V[1];break}}}if(!Q){let X=[],K=/<p[^>]*>([\s\S]*?)<\/p>/gi,V;while((V=K.exec($))!==null){let G=u$(V[1]).trim();if(G.length>50)X.push(G)}Q=X.join(`
181
184
 
182
- `)}else Q=uq(Q);let J=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:J}}function uq($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let z=m$(Q[1]).trim();if(z.length>20)Z.push(z)}if(Z.length===0){let z=m$($).trim();if(z.length>50)return z}return Z.join(`
185
+ `)}else Q=JB(Q);let J=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:J}}function JB($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let z=u$(Q[1]).trim();if(z.length>20)Z.push(z)}if(Z.length===0){let z=u$($).trim();if(z.length>50)return z}return Z.join(`
183
186
 
184
- `)}Z0();h();Q1();import{existsSync as H7,mkdirSync as dq,readFileSync as cq}from"fs";import{join as lq}from"path";import{randomUUID as oq}from"crypto";var W7="",Y0=[],M5=null,U7=null,q7=()=>lq(W7,"tasks.json");function J6(){P(q7(),JSON.stringify(Y0,null,2))}function iq(){let $=q7();if(!H7($)){Y0=[];return}try{Y0=JSON.parse(cq($,"utf-8"))}catch{Y0=[]}}function R4($,Z){if(W7=$,U7=Z,!H7($))dq($,{recursive:!0});if(iq(),M5)clearInterval(M5);M5=setInterval(nq,30000),sq().catch(()=>{})}function B7(){if(M5)clearInterval(M5),M5=null}function X6($,Z){let Y={id:tq(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(Y0=[...Y0,Y],J6(),Z&&R)L4(Y).catch(()=>{});return Y}function K6($){let Z=$.toLowerCase(),Y=Y0.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(Y0=Y0.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),J6(),Y.dueAt&&R)O7(Y.id).catch(()=>{});return Y0.find((Q)=>Q.id===Y.id)||null}function N7($){let Z=$.toLowerCase(),Y=Y0.findIndex((z)=>z.id===$||z.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=Y0[Y];if(Y0=[...Y0.slice(0,Y),...Y0.slice(Y+1)],J6(),Q.dueAt&&R)O7(Q.id).catch(()=>{});return!0}function s0($=!1){return $?[...Y0]:Y0.filter((Z)=>!Z.done)}function f2($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",z=Y.dueAt?` (${eq(Y.dueAt)})`:"";return` ${Q} ${Y.title}${z} [${Y.id}]`});return`Tarefas (${$.length}):
187
+ `)}Y0();g();J1();import{existsSync as R7,mkdirSync as XB,readFileSync as KB}from"fs";import{join as VB}from"path";import{randomUUID as GB}from"crypto";var j7="",Q0=[],F5=null,P7=null,A7=()=>VB(j7,"tasks.json");function G6(){j(A7(),JSON.stringify(Q0,null,2))}function WB(){let $=A7();if(!R7($)){Q0=[];return}try{Q0=JSON.parse(KB($,"utf-8"))}catch{Q0=[]}}function T4($,Z){if(j7=$,P7=Z,!R7($))XB($,{recursive:!0});if(WB(),F5)clearInterval(F5);F5=setInterval(HB,30000),BB().catch(()=>{})}function D7(){if(F5)clearInterval(F5),F5=null}function W6($,Z){let Y={id:NB(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(Q0=[...Q0,Y],G6(),Z&&R)D4(Y).catch(()=>{});return Y}function H6($){let Z=$.toLowerCase(),Y=Q0.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(Q0=Q0.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),G6(),Y.dueAt&&R)I7(Y.id).catch(()=>{});return Q0.find((Q)=>Q.id===Y.id)||null}function T7($){let Z=$.toLowerCase(),Y=Q0.findIndex((z)=>z.id===$||z.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=Q0[Y];if(Q0=[...Q0.slice(0,Y),...Q0.slice(Y+1)],G6(),Q.dueAt&&R)I7(Q.id).catch(()=>{});return!0}function $1($=!1){return $?[...Q0]:Q0.filter((Z)=>!Z.done)}function y2($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",z=Y.dueAt?` (${OB(Y.dueAt)})`:"";return` ${Q} ${Y.title}${z} [${Y.id}]`});return`Tarefas (${$.length}):
185
188
  ${Z.join(`
186
- `)}`}function E5($){let Z=new Date,Y=$.toLowerCase().trim(),Q=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Q){let X=parseInt(Q[1]),K=Q[2].startsWith("h")?"hours":"minutes",V=new Date(Z);if(K==="hours")V.setHours(V.getHours()+X);else V.setMinutes(V.getMinutes()+X);return V}let 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 nq(){let $=new Date,Z=!1;for(let Y of Y0){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)Y0=Y0.map((J)=>J.id===Y.id?{...J,notified:!0}:J),Z=!0,aq(Y),U7?.(Y)}if(Z)J6()}function rq($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function aq($){if(!R)return;try{await m1("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var j4="smolerclaw-reminder-";async function L4($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${j4}${$.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"">${mz(rq($.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 O1("Create",Y,["/SC","ONCE","/SD",Q,"/ST",z,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${X}"`,"/F"])}catch{}}async function O7($){let Z=`${j4}${$}`;try{await O1("Delete",Z,["/F"])}catch{}}async function sq(){if(!R)return;let $=Date.now();for(let Z of Y0){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await O1("Query",`${j4}${Z.id}`)).exitCode!==0)await L4(Z)}catch{await L4(Z)}}}function tq(){return oq().slice(0,8)}function eq($){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}`}h();import{existsSync as C7,mkdirSync as $B,readFileSync as ZB}from"fs";import{join as YB}from"path";import{randomUUID as QB}from"crypto";var M7="",D0=[],E7=()=>YB(M7,"memos.json");function F7(){P(E7(),JSON.stringify(D0,null,2))}function zB(){let $=E7();if(!C7($)){D0=[];return}try{D0=JSON.parse(ZB($,"utf-8"))}catch{D0=[]}}function L7($){if(M7=$,!C7($))$B($,{recursive:!0});zB()}function u$($,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:XB(),content:$.trim(),tags:z,createdAt:Y,updatedAt:Y};return D0=[...D0,J],F7(),J}function R7($){let Z=D0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return D0=[...D0.slice(0,Z),...D0.slice(Z+1)],F7(),!0}function V6($){let Z=$.toLowerCase().trim();if(!Z)return[...D0];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return D0.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 d$($=20){return[...D0].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function JB(){let $=new Map;for(let Z of D0)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 b2($){if($.length===0)return"Nenhum memo encontrado.";let Z=new Date,Y=P4(Z),Q=new Date(Z);Q.setDate(Q.getDate()-1);let z=P4(Q),J={},X=[];for(let V of $){let G=new Date(V.updatedAt),H=P4(G),W;if(H===Y)W=`Hoje (${A4(G)})`;else if(H===z)W=`Ontem (${A4(G)})`;else W=A4(G);if(!J[W])J[W]=[],X.push(W);let U=V.tags.length>0?` [${V.tags.map((N)=>`#${N}`).join(" ")}]`:"",q=V.content.length>80?V.content.slice(0,80).replace(/\n/g," ")+"...":V.content.replace(/\n/g," ");J[W].push(` ${q}${U} {${V.id}}`)}let K=X.map((V)=>` ${V}:
189
+ `)}`}function L5($){let Z=new Date,Y=$.toLowerCase().trim(),Q=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Q){let X=parseInt(Q[1]),K=Q[2].startsWith("h")?"hours":"minutes",V=new Date(Z);if(K==="hours")V.setHours(V.getHours()+X);else V.setMinutes(V.getMinutes()+X);return V}let 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 HB(){let $=new Date,Z=!1;for(let Y of Q0){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)Q0=Q0.map((J)=>J.id===Y.id?{...J,notified:!0}:J),Z=!0,qB(Y),P7?.(Y)}if(Z)G6()}function UB($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function qB($){if(!R)return;try{await u1("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var I4="smolerclaw-reminder-";async function D4($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${I4}${$.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"">${tz(UB($.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 M1("Create",Y,["/SC","ONCE","/SD",Q,"/ST",z,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${X}"`,"/F"])}catch{}}async function I7($){let Z=`${I4}${$}`;try{await M1("Delete",Z,["/F"])}catch{}}async function BB(){if(!R)return;let $=Date.now();for(let Z of Q0){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await M1("Query",`${I4}${Z.id}`)).exitCode!==0)await D4(Z)}catch{await D4(Z)}}}function NB(){return GB().slice(0,8)}function OB($){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}`}g();import{existsSync as S7,mkdirSync as CB,readFileSync as MB}from"fs";import{join as EB}from"path";import{randomUUID as FB}from"crypto";var w7="",T0=[],k7=()=>EB(w7,"memos.json");function f7(){j(k7(),JSON.stringify(T0,null,2))}function LB(){let $=k7();if(!S7($)){T0=[];return}try{T0=JSON.parse(MB($,"utf-8"))}catch{T0=[]}}function b7($){if(w7=$,!S7($))CB($,{recursive:!0});LB()}function c$($,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:jB(),content:$.trim(),tags:z,createdAt:Y,updatedAt:Y};return T0=[...T0,J],f7(),J}function y7($){let Z=T0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return T0=[...T0.slice(0,Z),...T0.slice(Z+1)],f7(),!0}function U6($){let Z=$.toLowerCase().trim();if(!Z)return[...T0];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return T0.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 l$($=20){return[...T0].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function RB(){let $=new Map;for(let Z of T0)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 v2($){if($.length===0)return"Nenhum memo encontrado.";let Z=new Date,Y=S4(Z),Q=new Date(Z);Q.setDate(Q.getDate()-1);let z=S4(Q),J={},X=[];for(let V of $){let G=new Date(V.updatedAt),W=S4(G),H;if(W===Y)H=`Hoje (${w4(G)})`;else if(W===z)H=`Ontem (${w4(G)})`;else H=w4(G);if(!J[H])J[H]=[],X.push(H);let U=V.tags.length>0?` [${V.tags.map((N)=>`#${N}`).join(" ")}]`:"",q=V.content.length>80?V.content.slice(0,80).replace(/\n/g," ")+"...":V.content.replace(/\n/g," ");J[H].push(` ${q}${U} {${V.id}}`)}let K=X.map((V)=>` ${V}:
187
190
  ${J[V].map((G)=>` ${G}`).join(`
188
191
  `)}`);return`Memos (${$.length}):
189
192
  ${K.join(`
190
193
 
191
- `)}`}function j7(){let $=JB();if($.length===0)return"Nenhuma tag.";return`Tags:
194
+ `)}`}function v7(){let $=RB();if($.length===0)return"Nenhuma tag.";return`Tags:
192
195
  ${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
193
- `)}`}function XB(){return QB().slice(0,8)}function P4($){let Z=$.getFullYear(),Y=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0");return`${Z}-${Y}-${Q}`}function A4($){return $.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}Z0();async function G6($){if(R)return KB($);return D4($)}async function KB($){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(`
194
- `);try{let X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",J],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),15000),[V]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]);await X.exited,clearTimeout(K);let G=V.trim();if(G.includes("mailto"))return D4($);return G||"Email aberto no Outlook."}catch{return D4($)}}async function D4($){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=R?["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 H6($){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(`
195
- `)}Z0();h();Q1();import{existsSync as U6,mkdirSync as T7,readFileSync as VB,writeFileSync as GB,unlinkSync as HB}from"fs";import{join as q6}from"path";import{randomUUID as WB}from"crypto";var T4="",i=[],UB=null,I7=()=>q6(T4,"scheduler.json"),qB="Smolerclaw_";function w7($,Z){if(T4=$,UB=Z??null,!U6($))T7($,{recursive:!0});if(CB(),R)OB().catch(()=>{})}async function B6($,Z,Y,Q,z,J){let X=MB(),K=`${qB}${X}`,V={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(R)await W6(V);return i=[...i,V],F5(),V}async function N6($){let Z=$.toLowerCase(),Y=i.findIndex((z)=>z.id===$||z.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=i[Y];if(R)await w4(Q.taskName,Q.id);return i=[...i.slice(0,Y),...i.slice(Y+1)],F5(),!0}async function O6($){let Z=R6($);if(!Z||Z.enabled)return null;if(R)await W6(Z);return i=i.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),F5(),i.find((Y)=>Y.id===Z.id)??null}async function C6($){let Z=R6($);if(!Z||!Z.enabled)return null;if(R)await w4(Z.taskName,void 0);return i=i.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),F5(),i.find((Y)=>Y.id===Z.id)??null}function c$($=!1){return $?[...i]:i.filter((Z)=>Z.enabled)}function S7($){return R6($)}async function M6($){let Z=R6($);if(!Z)return"Agendamento nao encontrado.";if(R){let Y=await O1("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return i=i.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),F5(),`Agendamento "${Z.name}" executado.`}function l$($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",z=EB(Y),J=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${z} [${J}] (${Q})`});return`Agendamentos (${$.length}):
196
+ `)}`}function jB(){return FB().slice(0,8)}function S4($){let Z=$.getFullYear(),Y=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0");return`${Z}-${Y}-${Q}`}function w4($){return $.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}Y0();async function q6($){if(R)return PB($);return k4($)}async function PB($){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(`
197
+ `);try{let X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",J],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),15000),[V]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]);await X.exited,clearTimeout(K);let G=V.trim();if(G.includes("mailto"))return k4($);return G||"Email aberto no Outlook."}catch{return k4($)}}async function k4($){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=R?["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 B6($){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(`
198
+ `)}Y0();g();J1();import{existsSync as O6,mkdirSync as g7,readFileSync as AB,writeFileSync as DB,unlinkSync as TB}from"fs";import{join as C6}from"path";import{randomUUID as IB}from"crypto";var f4="",n=[],SB=null,m7=()=>C6(f4,"scheduler.json"),wB="Smolerclaw_";function p7($,Z){if(f4=$,SB=Z??null,!O6($))g7($,{recursive:!0});if(yB(),R)bB().catch(()=>{})}async function M6($,Z,Y,Q,z,J){let X=vB(),K=`${wB}${X}`,V={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(R)await N6(V);return n=[...n,V],R5(),V}async function E6($){let Z=$.toLowerCase(),Y=n.findIndex((z)=>z.id===$||z.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=n[Y];if(R)await y4(Q.taskName,Q.id);return n=[...n.slice(0,Y),...n.slice(Y+1)],R5(),!0}async function F6($){let Z=D6($);if(!Z||Z.enabled)return null;if(R)await N6(Z);return n=n.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),R5(),n.find((Y)=>Y.id===Z.id)??null}async function L6($){let Z=D6($);if(!Z||!Z.enabled)return null;if(R)await y4(Z.taskName,void 0);return n=n.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),R5(),n.find((Y)=>Y.id===Z.id)??null}function o$($=!1){return $?[...n]:n.filter((Z)=>Z.enabled)}function u7($){return D6($)}async function R6($){let Z=D6($);if(!Z)return"Agendamento nao encontrado.";if(R){let Y=await M1("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return n=n.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),R5(),`Agendamento "${Z.name}" executado.`}function i$($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",z=xB(Y),J=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${z} [${J}] (${Q})`});return`Agendamentos (${$.length}):
196
199
  ${Z.join(`
197
- `)}`}function I4($){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: ${A7($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${A7($.lastRun)}`);return Z.join(`
198
- `)}function E6($){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 F6($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return D7(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let J=new Date(Y);return J.setDate(J.getDate()+1),D7(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 L6($){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 W6($){let Z=NB($),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 O1("Create",$.taskName,Y)}catch{}}async function w4($,Z){try{await O1("Delete",$,["/F"])}catch{}if(Z)BB(Z)}function k7(){let $=q6(T4,"scripts");if(!U6($))T7($,{recursive:!0});return $}function P7($,Z,Y){let Q=k7(),z=q6(Q,`toast_${$}.ps1`),J=`# Toast notification script for smolerclaw
200
+ `)}`}function b4($){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: ${_7($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${_7($.lastRun)}`);return Z.join(`
201
+ `)}function j6($){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 P6($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return h7(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let J=new Date(Y);return J.setDate(J.getDate()+1),h7(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 A6($){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 N6($){let Z=fB($),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 M1("Create",$.taskName,Y)}catch{}}async function y4($,Z){try{await M1("Delete",$,["/F"])}catch{}if(Z)kB(Z)}function d7(){let $=C6(f4,"scripts");if(!O6($))g7($,{recursive:!0});return $}function x7($,Z,Y){let Q=d7(),z=C6(Q,`toast_${$}.ps1`),J=`# Toast notification script for smolerclaw
199
202
  # Job ID: ${$}
200
203
  # Generated: ${new Date().toISOString()}
201
204
 
@@ -221,82 +224,82 @@ $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
221
224
  $xml.LoadXml($template)
222
225
  $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
223
226
  [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show($toast)
224
- `,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(J,"utf-8")]);return GB(z,K),z}function BB($){let Z=q6(k7(),`toast_${$}.ps1`);try{if(U6(Z))HB(Z)}catch{}}function NB($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${P7($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${P7($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function OB(){if(!R)return;for(let $ of i){if(!$.enabled)continue;try{if((await O1("Query",$.taskName)).exitCode!==0)await W6($)}catch{await W6($)}}}function f7(){}async function b7(){let $=0;for(let Z of i){if(R)await w4(Z.taskName,Z.id);$++}return i=[],F5(),`${$} agendamento(s) removido(s).`}function CB(){let $=I7();if(!U6($)){i=[];return}try{i=JSON.parse(VB($,"utf-8"))}catch{i=[]}}function F5(){P(I7(),JSON.stringify(i,null,2))}function MB(){return WB().slice(0,8)}function R6($){let Z=$.toLowerCase();return i.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function EB($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${FB($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function FB($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function A7($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function D7($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}h();import{existsSync as v7,mkdirSync as LB,readFileSync as RB}from"fs";import{join as jB}from"path";import{randomUUID as PB}from"crypto";var x7="",s1=[],_7=()=>jB(x7,"finance.json");function AB(){P(_7(),JSON.stringify(s1,null,2))}function DB(){let $=_7();if(!v7($)){s1=[];return}try{s1=JSON.parse(RB($,"utf-8"))}catch{s1=[]}}function h7($){if(x7=$,!v7($))LB($,{recursive:!0});DB()}function o$($,Z,Y,Q){let z={id:TB(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return s1=[...s1,z],AB(),z}function j6($,Z){let Y=new Date,Q=$||Y.getFullYear(),z=Z!==void 0?Z:Y.getMonth(),J=s1.filter((W)=>{let U=new Date(W.date);return U.getFullYear()===Q&&U.getMonth()===z});if(J.length===0)return`Nenhuma transacao em ${y7(z)}/${Q}.`;let X=J.filter((W)=>W.type==="entrada").reduce((W,U)=>W+U.amount,0),K=J.filter((W)=>W.type==="saida").reduce((W,U)=>W+U.amount,0),V=X-K,G=new Map;for(let W of J.filter((U)=>U.type==="saida"))G.set(W.category,(G.get(W.category)||0)+W.amount);let H=[`--- Resumo ${y7(z)}/${Q} ---`,`Entradas: R$ ${X.toFixed(2)}`,`Saidas: R$ ${K.toFixed(2)}`,`Saldo: R$ ${V.toFixed(2)} ${V>=0?"":"(NEGATIVO)"}`];if(G.size>0){H.push(""),H.push("Saidas por categoria:");let W=[...G.entries()].sort((U,q)=>q[1]-U[1]);for(let[U,q]of W){let N=K>0?Math.round(q/K*100):0;H.push(` ${U.padEnd(15)} R$ ${q.toFixed(2)} (${N}%)`)}}return H.join(`
225
- `)}function S4($=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:
227
+ `,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(J,"utf-8")]);return DB(z,K),z}function kB($){let Z=C6(d7(),`toast_${$}.ps1`);try{if(O6(Z))TB(Z)}catch{}}function fB($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${x7($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${x7($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function bB(){if(!R)return;for(let $ of n){if(!$.enabled)continue;try{if((await M1("Query",$.taskName)).exitCode!==0)await N6($)}catch{await N6($)}}}function c7(){}async function l7(){let $=0;for(let Z of n){if(R)await y4(Z.taskName,Z.id);$++}return n=[],R5(),`${$} agendamento(s) removido(s).`}function yB(){let $=m7();if(!O6($)){n=[];return}try{n=JSON.parse(AB($,"utf-8"))}catch{n=[]}}function R5(){j(m7(),JSON.stringify(n,null,2))}function vB(){return IB().slice(0,8)}function D6($){let Z=$.toLowerCase();return n.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function xB($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${_B($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function _B($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function _7($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function h7($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}g();import{existsSync as i7,mkdirSync as hB,readFileSync as gB}from"fs";import{join as mB}from"path";import{randomUUID as pB}from"crypto";var n7="",e1=[],r7=()=>mB(n7,"finance.json");function uB(){j(r7(),JSON.stringify(e1,null,2))}function dB(){let $=r7();if(!i7($)){e1=[];return}try{e1=JSON.parse(gB($,"utf-8"))}catch{e1=[]}}function a7($){if(n7=$,!i7($))hB($,{recursive:!0});dB()}function n$($,Z,Y,Q){let z={id:cB(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return e1=[...e1,z],uB(),z}function T6($,Z){let Y=new Date,Q=$||Y.getFullYear(),z=Z!==void 0?Z:Y.getMonth(),J=e1.filter((H)=>{let U=new Date(H.date);return U.getFullYear()===Q&&U.getMonth()===z});if(J.length===0)return`Nenhuma transacao em ${o7(z)}/${Q}.`;let X=J.filter((H)=>H.type==="entrada").reduce((H,U)=>H+U.amount,0),K=J.filter((H)=>H.type==="saida").reduce((H,U)=>H+U.amount,0),V=X-K,G=new Map;for(let H of J.filter((U)=>U.type==="saida"))G.set(H.category,(G.get(H.category)||0)+H.amount);let W=[`--- Resumo ${o7(z)}/${Q} ---`,`Entradas: R$ ${X.toFixed(2)}`,`Saidas: R$ ${K.toFixed(2)}`,`Saldo: R$ ${V.toFixed(2)} ${V>=0?"":"(NEGATIVO)"}`];if(G.size>0){W.push(""),W.push("Saidas por categoria:");let H=[...G.entries()].sort((U,q)=>q[1]-U[1]);for(let[U,q]of H){let N=K>0?Math.round(q/K*100):0;W.push(` ${U.padEnd(15)} R$ ${q.toFixed(2)} (${N}%)`)}}return W.join(`
228
+ `)}function v4($=10){let Z=[...e1].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:
226
229
  ${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(`
227
- `)}`}function TB(){return PB().slice(0,8)}function y7($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}z1();var k4={debug:0,info:1,warn:2,error:3};function IB(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in k4)return $;if(process.env.DEBUG)return"debug";return"warn"}function wB($){return k4[$]>=k4[IB()]}function SB($,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 P6($,Z,Y){if(!wB($))return;let Q=SB($,Z,Y);process.stderr.write(Q+`
228
- `)}var l={debug:($,Z)=>P6("debug",$,Z),info:($,Z)=>P6("info",$,Z),warn:($,Z)=>P6("warn",$,Z),error:($,Z)=>P6("error",$,Z)};var g7={maxSingleAmount:1e4,dailyAlertThreshold:1000,duplicateWindowMs:300000,blockOnFailure:!1},t1={...g7},A6=[],D6=[];function m7($){t1={...g7,...$},A6=[],D6=[]}function i$($,Z,Y,Q){let z=[],J=null;if(Z<=0)return{allowed:!1,warnings:[],blocked:"Valor deve ser positivo."};if(!Y.trim())return{allowed:!1,warnings:[],blocked:"Categoria obrigatoria."};if(!Q.trim())return{allowed:!1,warnings:[],blocked:"Descricao obrigatoria."};if(Z>t1.maxSingleAmount){let G=`Valor alto: R$ ${Z.toFixed(2)} excede limite de R$ ${t1.maxSingleAmount.toFixed(2)}`;if(t1.blockOnFailure)J=G;else z.push(G)}let X=Date.now(),K=A6.find((G)=>G.type===$&&G.amount===Math.abs(Z)&&G.category===Y.toLowerCase().trim()&&X-G.timestamp<t1.duplicateWindowMs);if(K){let G=Math.round((X-K.timestamp)/1000);z.push(`Possivel duplicata: mesma transacao registrada ha ${G}s atras`)}if($==="saida"){let G=p7(),W=D6.filter((U)=>U.type==="saida"&&U.date===G).reduce((U,q)=>U+q.amount,0)+Math.abs(Z);if(W>t1.dailyAlertThreshold)z.push(`Alerta: gasto diario projetado R$ ${W.toFixed(2)} excede limite de R$ ${t1.dailyAlertThreshold.toFixed(2)}`)}let V=J===null;return kB($,Z,Y,Q,V,z),{allowed:V,warnings:z,blocked:J}}function n$($,Z,Y){let Q=Math.abs(Z),z=Date.now(),J={type:$,amount:Q,category:Y.toLowerCase().trim(),timestamp:z},X=z-t1.duplicateWindowMs*2;A6=[...A6.filter((V)=>V.timestamp>X),J];let K=p7();D6=[...D6.filter((V)=>V.date===K),{type:$,amount:Q,date:K}]}function r$($){if($.blocked)return`BLOQUEADO: ${$.blocked}`;if($.warnings.length===0)return"";return $.warnings.map((Z)=>`AVISO: ${Z}`).join(`
229
- `)}function p7(){return new Date().toISOString().slice(0,10)}function kB($,Z,Y,Q,z,J){let X=!z?"error":J.length>0?"warning":"info";if(G0("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)l.debug("Finance guard warnings",{type:$,amount:Z,category:Y,warnings:J})}h();import{existsSync as u7,mkdirSync as fB,readFileSync as bB}from"fs";import{join as yB}from"path";import{randomUUID as vB}from"crypto";var d7="",e1=[],c7=()=>yB(d7,"decisions.json");function xB(){P(c7(),JSON.stringify(e1,null,2))}function _B(){let $=c7();if(!u7($)){e1=[];return}try{e1=JSON.parse(bB($,"utf-8"))}catch{e1=[]}}function l7($){if(d7=$,!u7($))fB($,{recursive:!0});_B()}function o7($,Z,Y,Q,z=[]){let J={id:hB(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:z.map((X)=>X.toLowerCase()),date:new Date().toISOString()};return e1=[...e1,J],xB(),J}function y2($){let Z=$.toLowerCase();return e1.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 T6($=15){return[...e1].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function L5($){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}):
230
+ `)}`}function cB(){return pB().slice(0,8)}function o7($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}X1();var x4={debug:0,info:1,warn:2,error:3};function lB(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in x4)return $;if(process.env.DEBUG)return"debug";return"warn"}function oB($){return x4[$]>=x4[lB()]}function iB($,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 I6($,Z,Y){if(!oB($))return;let Q=iB($,Z,Y);process.stderr.write(Q+`
231
+ `)}var o={debug:($,Z)=>I6("debug",$,Z),info:($,Z)=>I6("info",$,Z),warn:($,Z)=>I6("warn",$,Z),error:($,Z)=>I6("error",$,Z)};var s7={maxSingleAmount:1e4,dailyAlertThreshold:1000,duplicateWindowMs:300000,blockOnFailure:!1},$2={...s7},S6=[],w6=[];function t7($){$2={...s7,...$},S6=[],w6=[]}function r$($,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>$2.maxSingleAmount){let G=`Valor alto: R$ ${Z.toFixed(2)} excede limite de R$ ${$2.maxSingleAmount.toFixed(2)}`;if($2.blockOnFailure)J=G;else z.push(G)}let X=Date.now(),K=S6.find((G)=>G.type===$&&G.amount===Math.abs(Z)&&G.category===Y.toLowerCase().trim()&&X-G.timestamp<$2.duplicateWindowMs);if(K){let G=Math.round((X-K.timestamp)/1000);z.push(`Possivel duplicata: mesma transacao registrada ha ${G}s atras`)}if($==="saida"){let G=e7(),H=w6.filter((U)=>U.type==="saida"&&U.date===G).reduce((U,q)=>U+q.amount,0)+Math.abs(Z);if(H>$2.dailyAlertThreshold)z.push(`Alerta: gasto diario projetado R$ ${H.toFixed(2)} excede limite de R$ ${$2.dailyAlertThreshold.toFixed(2)}`)}let V=J===null;return nB($,Z,Y,Q,V,z),{allowed:V,warnings:z,blocked:J}}function a$($,Z,Y){let Q=Math.abs(Z),z=Date.now(),J={type:$,amount:Q,category:Y.toLowerCase().trim(),timestamp:z},X=z-$2.duplicateWindowMs*2;S6=[...S6.filter((V)=>V.timestamp>X),J];let K=e7();w6=[...w6.filter((V)=>V.date===K),{type:$,amount:Q,date:K}]}function s$($){if($.blocked)return`BLOQUEADO: ${$.blocked}`;if($.warnings.length===0)return"";return $.warnings.map((Z)=>`AVISO: ${Z}`).join(`
232
+ `)}function e7(){return new Date().toISOString().slice(0,10)}function nB($,Z,Y,Q,z,J){let X=!z?"error":J.length>0?"warning":"info";if(W0("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)o.debug("Finance guard warnings",{type:$,amount:Z,category:Y,warnings:J})}g();import{existsSync as $X,mkdirSync as rB,readFileSync as aB}from"fs";import{join as sB}from"path";import{randomUUID as tB}from"crypto";var ZX="",Z2=[],YX=()=>sB(ZX,"decisions.json");function eB(){j(YX(),JSON.stringify(Z2,null,2))}function $N(){let $=YX();if(!$X($)){Z2=[];return}try{Z2=JSON.parse(aB($,"utf-8"))}catch{Z2=[]}}function QX($){if(ZX=$,!$X($))rB($,{recursive:!0});$N()}function zX($,Z,Y,Q,z=[]){let J={id:ZN(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:z.map((X)=>X.toLowerCase()),date:new Date().toISOString()};return Z2=[...Z2,J],eB(),J}function x2($){let Z=$.toLowerCase();return Z2.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 k6($=15){return[...Z2].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function j5($){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}):
230
233
  ${Z.join(`
231
- `)}`}function hB(){return vB().slice(0,8)}s$();h();import{existsSync as e7,mkdirSync as lB,readFileSync as oB}from"fs";import{join as iB}from"path";import{randomUUID as nB}from"crypto";var $X="",_={people:[],interactions:[],delegations:[]},ZX=()=>iB($X,"people.json");function S6(){P(ZX(),JSON.stringify(_,null,2))}function rB(){let $=ZX();if(!e7($)){_={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(oB($,"utf-8"));_={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{_={people:[],interactions:[],delegations:[]}}}function YX($){if($X=$,!e7($))lB($,{recursive:!0});rB()}function k6($,Z,Y,Q,z,J){let X={id:c4(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),neighborhood:z?.trim(),location:J?.trim(),createdAt:new Date().toISOString()};return _={..._,people:[..._.people,X]},S6(),X}function A1($){let Z=$.toLowerCase();return _.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function f6($){if($)return _.people.filter((Z)=>Z.group===$);return[..._.people]}function QX($,Z,Y,Q){let z=A1($);if(!z)return null;let J={id:c4(),personId:z.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return _={..._,interactions:[..._.interactions,J]},S6(),J}function aB($,Z=10){let Y=A1($);if(!Y)return[];return[..._.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 R5(){let $=new Date,Z=[];for(let Y of _.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let z=_.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 b6($,Z,Y){let Q=A1($);if(!Q)return null;let z={id:c4(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return _={..._,delegations:[..._.delegations,z]},S6(),z}function zX($,Z,Y){if(!_.delegations.find((z)=>z.id===$))return null;return _={..._,delegations:_.delegations.map((z)=>z.id===$?{...z,status:Z,notes:Y||z.notes}:z)},S6(),_.delegations.find((z)=>z.id===$)||null}function v2($,Z=!0){let Y=[..._.delegations];if($){let z=A1($);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 JX={equipe:"Equipe",familia:"Familia",contato:"Contato"};function y6($){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 V=K.role?` (${K.role})`:"",G=K.contact?` \u2014 ${K.contact}`:"";return` ${K.name}${V}${G} [${K.id}]`});Y.push(`--- ${JX[z]} ---
234
+ `)}`}function ZN(){return tB().slice(0,8)}e$();g();import{existsSync as HX,mkdirSync as VN,readFileSync as GN}from"fs";import{join as WN}from"path";import{randomUUID as HN}from"crypto";var UX="",_={people:[],interactions:[],delegations:[]},qX=()=>WN(UX,"people.json");function y6(){j(qX(),JSON.stringify(_,null,2))}function UN(){let $=qX();if(!HX($)){_={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(GN($,"utf-8"));_={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{_={people:[],interactions:[],delegations:[]}}}function BX($){if(UX=$,!HX($))VN($,{recursive:!0});UN()}function v6($,Z,Y,Q,z,J){let X={id:r4(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),neighborhood:z?.trim(),location:J?.trim(),createdAt:new Date().toISOString()};return _={..._,people:[..._.people,X]},y6(),X}function T1($){let Z=$.toLowerCase();return _.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function x6($){if($)return _.people.filter((Z)=>Z.group===$);return[..._.people]}function NX($,Z,Y,Q){let z=T1($);if(!z)return null;let J={id:r4(),personId:z.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return _={..._,interactions:[..._.interactions,J]},y6(),J}function qN($,Z=10){let Y=T1($);if(!Y)return[];return[..._.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 P5(){let $=new Date,Z=[];for(let Y of _.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let z=_.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 _6($,Z,Y){let Q=T1($);if(!Q)return null;let z={id:r4(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return _={..._,delegations:[..._.delegations,z]},y6(),z}function OX($,Z,Y){if(!_.delegations.find((z)=>z.id===$))return null;return _={..._,delegations:_.delegations.map((z)=>z.id===$?{...z,status:Z,notes:Y||z.notes}:z)},y6(),_.delegations.find((z)=>z.id===$)||null}function _2($,Z=!0){let Y=[..._.delegations];if($){let z=T1($);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 CX={equipe:"Equipe",familia:"Familia",contato:"Contato"};function h6($){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 V=K.role?` (${K.role})`:"",G=K.contact?` \u2014 ${K.contact}`:"";return` ${K.name}${V}${G} [${K.id}]`});Y.push(`--- ${CX[z]} ---
232
235
  ${X.join(`
233
236
  `)}`)}return Y.join(`
234
237
 
235
- `)}function v6($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${JX[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.neighborhood)Z.push(`Bairro: ${$.neighborhood}`);if($.location)Z.push(`Local: ${$.location}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=aB($.id,5);if(Y.length>0){Z.push(`
236
- 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=v2($.id);if(Q.length>0){Z.push(`
237
- Tarefas delegadas:`);for(let z of Q){let J=z.status==="atrasado"?"!!":z.status==="em_andamento"?">>":" ",X=z.dueDate?` (${l4(z.dueDate)})`:"";Z.push(` ${J} ${z.task}${X} [${z.status}]`)}}return Z.join(`
238
- `)}function x6($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let z=_.people.find((K)=>K.id===Y.personId)?.name||"?",J=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",X=Y.dueDate?` (${l4(Y.dueDate)})`:"";return`${J}${z}: ${Y.task}${X} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
238
+ `)}function g6($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${CX[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.neighborhood)Z.push(`Bairro: ${$.neighborhood}`);if($.location)Z.push(`Local: ${$.location}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=qN($.id,5);if(Y.length>0){Z.push(`
239
+ 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=_2($.id);if(Q.length>0){Z.push(`
240
+ Tarefas delegadas:`);for(let z of Q){let J=z.status==="atrasado"?"!!":z.status==="em_andamento"?">>":" ",X=z.dueDate?` (${a4(z.dueDate)})`:"";Z.push(` ${J} ${z.task}${X} [${z.status}]`)}}return Z.join(`
241
+ `)}function m6($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let z=_.people.find((K)=>K.id===Y.personId)?.name||"?",J=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",X=Y.dueDate?` (${a4(Y.dueDate)})`:"";return`${J}${z}: ${Y.task}${X} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
239
242
  ${Z.join(`
240
- `)}`}function _6($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${l4(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
243
+ `)}`}function p6($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${a4(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
241
244
  ${Z.join(`
242
- `)}`}function XX(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
243
- `);let Z=_.people.filter((G)=>G.group==="equipe").length,Y=_.people.filter((G)=>G.group==="familia").length,Q=_.people.filter((G)=>G.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let z=R5();if(z.length>0){$.push(`
244
- !! ${z.length} follow-up(s) pendente(s):`);for(let{person:G,interaction:H}of z.slice(0,5))$.push(` ${G.name}: ${H.summary}`)}let J=v2(),X=J.filter((G)=>G.status==="atrasado"),K=J.filter((G)=>G.status==="pendente"||G.status==="em_andamento");if(X.length>0){$.push(`
245
- !! ${X.length} delegacao(oes) atrasada(s):`);for(let G of X.slice(0,5)){let H=_.people.find((W)=>W.id===G.personId);$.push(` ${H?.name}: ${G.task}`)}}if(K.length>0)$.push(`
246
- ${K.length} delegacao(oes) em andamento`);let V=[..._.interactions].sort((G,H)=>new Date(H.date).getTime()-new Date(G.date).getTime()).slice(0,3);if(V.length>0){$.push(`
247
- Ultimas interacoes:`);for(let G of V){let H=_.people.find((U)=>U.id===G.personId),W=new Date(G.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${W}] ${H?.name}: ${G.summary}`)}}return $.push(`
245
+ `)}`}function MX(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
246
+ `);let Z=_.people.filter((G)=>G.group==="equipe").length,Y=_.people.filter((G)=>G.group==="familia").length,Q=_.people.filter((G)=>G.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let z=P5();if(z.length>0){$.push(`
247
+ !! ${z.length} follow-up(s) pendente(s):`);for(let{person:G,interaction:W}of z.slice(0,5))$.push(` ${G.name}: ${W.summary}`)}let J=_2(),X=J.filter((G)=>G.status==="atrasado"),K=J.filter((G)=>G.status==="pendente"||G.status==="em_andamento");if(X.length>0){$.push(`
248
+ !! ${X.length} delegacao(oes) atrasada(s):`);for(let G of X.slice(0,5)){let W=_.people.find((H)=>H.id===G.personId);$.push(` ${W?.name}: ${G.task}`)}}if(K.length>0)$.push(`
249
+ ${K.length} delegacao(oes) em andamento`);let V=[..._.interactions].sort((G,W)=>new Date(W.date).getTime()-new Date(G.date).getTime()).slice(0,3);if(V.length>0){$.push(`
250
+ Ultimas interacoes:`);for(let G of V){let W=_.people.find((U)=>U.id===G.personId),H=new Date(G.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${H}] ${W?.name}: ${G.summary}`)}}return $.push(`
248
251
  ========================`),$.join(`
249
- `)}function c4(){return nB().slice(0,8)}function l4($){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"})}h();import{existsSync as KX,mkdirSync as sB,readFileSync as tB}from"fs";import{join as eB}from"path";import{randomUUID as $N}from"crypto";var VX="",Q0=[],GX=()=>eB(VX,"materials.json");function o4(){P(GX(),JSON.stringify(Q0,null,2))}function ZN(){let $=GX();if(!KX($)){Q0=[];return}try{Q0=JSON.parse(tB($,"utf-8"))}catch{Q0=[]}}function HX($){if(VX=$,!KX($))sB($,{recursive:!0});ZN()}function h6($,Z,Y="geral",Q=[]){let z=new Date().toISOString(),J=Z.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=$.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=[...new Set([...Q.map((G)=>G.toLowerCase()),...J,...X])],V={id:YN(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:K,createdAt:z,updatedAt:z};return Q0=[...Q0,V],o4(),V}function WX($,Z){let Y=Q0.find((G)=>G.id===$);if(!Y)return null;let Q=Z.content??Y.content,z=Z.title??Y.title,J=Q.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=z.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=Z.tags??Y.tags,V=[...new Set([...K.map((G)=>G.toLowerCase()),...J,...X])];return Q0=Q0.map((G)=>G.id===$?{...G,title:z.trim(),content:Q.trim(),category:(Z.category??G.category).toLowerCase().trim(),tags:V,updatedAt:new Date().toISOString()}:G),o4(),Q0.find((G)=>G.id===$)||null}function g6($){let Z=Q0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return Q0=[...Q0.slice(0,Z),...Q0.slice(Z+1)],o4(),!0}function UX($){return Q0.find((Z)=>Z.id===$)||null}function j5($){let Z=$.toLowerCase().trim();if(!Z)return[...Q0];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),z=Y||Q?Z.slice(1):Z;return Q0.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 P5($=30,Z){let Y=[...Q0];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 qX(){let $=new Map;for(let Z of Q0)$.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 BX(){if(Q0.length===0)return"";let $=qX(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=Q0.filter((z)=>z.category===Y).sort((z,J)=>new Date(J.updatedAt).getTime()-new Date(z.updatedAt).getTime());Z.push(`
252
+ `)}function r4(){return HN().slice(0,8)}function a4($){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"})}g();import{existsSync as EX,mkdirSync as BN,readFileSync as NN}from"fs";import{join as ON}from"path";import{randomUUID as CN}from"crypto";var FX="",z0=[],LX=()=>ON(FX,"materials.json");function s4(){j(LX(),JSON.stringify(z0,null,2))}function MN(){let $=LX();if(!EX($)){z0=[];return}try{z0=JSON.parse(NN($,"utf-8"))}catch{z0=[]}}function RX($){if(FX=$,!EX($))BN($,{recursive:!0});MN()}function u6($,Z,Y="geral",Q=[]){let z=new Date().toISOString(),J=Z.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=$.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=[...new Set([...Q.map((G)=>G.toLowerCase()),...J,...X])],V={id:EN(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:K,createdAt:z,updatedAt:z};return z0=[...z0,V],s4(),V}function jX($,Z){let Y=z0.find((G)=>G.id===$);if(!Y)return null;let Q=Z.content??Y.content,z=Z.title??Y.title,J=Q.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=z.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=Z.tags??Y.tags,V=[...new Set([...K.map((G)=>G.toLowerCase()),...J,...X])];return z0=z0.map((G)=>G.id===$?{...G,title:z.trim(),content:Q.trim(),category:(Z.category??G.category).toLowerCase().trim(),tags:V,updatedAt:new Date().toISOString()}:G),s4(),z0.find((G)=>G.id===$)||null}function d6($){let Z=z0.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return z0=[...z0.slice(0,Z),...z0.slice(Z+1)],s4(),!0}function PX($){return z0.find((Z)=>Z.id===$)||null}function A5($){let Z=$.toLowerCase().trim();if(!Z)return[...z0];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),z=Y||Q?Z.slice(1):Z;return z0.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 D5($=30,Z){let Y=[...z0];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 AX(){let $=new Map;for(let Z of z0)$.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 DX(){if(z0.length===0)return"";let $=AX(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=z0.filter((z)=>z.category===Y).sort((z,J)=>new Date(J.updatedAt).getTime()-new Date(z.updatedAt).getTime());Z.push(`
250
253
  [${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(`
251
- `)}function $2($){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}):
254
+ `)}function Y2($){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}):
252
255
  ${Z.join(`
253
- `)}`}function NX($){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}} ---
256
+ `)}`}function TX($){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}} ---
254
257
  Titulo: ${$.title}
255
258
  Categoria: ${$.category}
256
259
 
257
260
  ${$.content}
258
261
 
259
262
  ${Q}
260
- ${z}`}function OX(){let $=qX();if($.length===0)return"Nenhuma categoria.";return`Categorias:
263
+ ${z}`}function IX(){let $=AX();if($.length===0)return"Nenhuma categoria.";return`Categorias:
261
264
  ${$.map((Y)=>` @${Y.category} (${Y.count})`).join(`
262
- `)}`}function YN(){return $N().slice(0,8)}h();import{existsSync as u0,mkdirSync as QN,readFileSync as p6}from"fs";import{join as T0,basename as zN}from"path";import{randomUUID as JN}from"crypto";var A5="",c0=[],d0=[],K1=[],Z2=null,CX=()=>T0(A5,"projects.json"),MX=()=>T0(A5,"work-sessions.json"),EX=()=>T0(A5,"opportunities.json"),FX=()=>T0(A5,"active-project.txt");function XN(){P(CX(),JSON.stringify(c0,null,2))}function n4(){P(MX(),JSON.stringify(d0,null,2))}function LX(){P(EX(),JSON.stringify(K1,null,2))}function KN(){P(FX(),Z2||"")}function VN(){c0=i4(CX,[]),d0=i4(MX,[]),K1=i4(EX,[]);let $=FX();if(u0($))try{Z2=p6($,"utf-8").trim()||null}catch{Z2=null}}function i4($,Z){let Y=$();if(!u0(Y))return Z;try{return JSON.parse(p6(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 RX($){if(A5=$,!u0($))QN($,{recursive:!0});VN()}function r4($,Z,Y="",Q=[],z=[]){let J={id:a4(),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 c0=[...c0,J],XN(),J}function u6($){let Z=$.toLowerCase().trim();return c0.find((Y)=>Y.id===$)||c0.find((Y)=>Y.name.toLowerCase()===Z)||c0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function D5($=!1){return($?c0.filter((Y)=>Y.active):[...c0]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function T5($){let Z=u6($);if(!Z)return null;return Z2=Z.id,KN(),Z}function Y2(){if(!Z2)return null;return c0.find(($)=>$.id===Z2)||null}function d6($,Z=""){if(!c0.find((z)=>z.id===$))return null;GN($);let Q={id:a4(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return d0=[...d0,Q],n4(),Q}function c6($,Z){let Y=d0.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 d0=d0.map((X)=>X.id===$?{...X,endedAt:Q.toISOString(),durationMinutes:J,notes:Z?`${X.notes}
263
- ${Z}`.trim():X.notes}:X),n4(),d0.find((X)=>X.id===$)||null}function GN($){let Z=new Date;d0=d0.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}),n4()}function Q2($){return d0.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function HN($,Z,Y){let Q=Y||new Date;return d0.filter((z)=>{if(z.projectId!==$)return!1;let J=new Date(z.startedAt);return J>=Z&&J<=Q})}async function WN($,Z="1 day ago"){if(!u0(T0($,".git")))return null;try{let Y=await m6(["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(`
264
- `).filter(Boolean),z=[...new Set(Q.map((N)=>N.split("|||")[0]))],J=Q.map((N)=>N.split("|||")[1]||"").filter(Boolean),X=await m6(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),K=await m6(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),V=0,G=0,H=0;if(K.ok&&K.stdout.trim())for(let N of K.stdout.trim().split(`
265
- `)){let C=N.match(/(\d+)\s+files?\s+changed/),M=N.match(/(\d+)\s+insertions?/),F=N.match(/(\d+)\s+deletions?/);if(C)V+=parseInt(C[1]);if(M)G+=parseInt(M[1]);if(F)H+=parseInt(F[1])}let W=await m6(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),U=new Map;if(W.ok&&W.stdout.trim())for(let N of W.stdout.trim().split(`
266
- `).filter(Boolean))U.set(N,(U.get(N)||0)+1);let q=[...U.entries()].sort((N,C)=>C[1]-N[1]).slice(0,10).map(([N])=>N);return{commits:Q.length,authors:z,filesChanged:V,insertions:G,deletions:H,topFiles:q,messages:J}}catch{return null}}async function m6($,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 jX($,Z,Y,Q=[],z="media",J=null){let X=new Date().toISOString(),K={id:a4(),title:$.trim(),description:Z.trim(),source:Y.trim(),techRequired:Q.map((V)=>V.toLowerCase()),priority:z,status:"nova",deadline:J,createdAt:X,updatedAt:X};return K1=[...K1,K],LX(),K}function PX($,Z){if(!K1.find((Q)=>Q.id===$))return null;return K1=K1.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),LX(),K1.find((Q)=>Q.id===$)||null}function l6($,Z){let Y=[...K1];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 o6($,Z="today",Y="pt"){let Q=u6($);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 WN(Q.path,X),V=HN(Q.id,J),G=V.reduce((U,q)=>U+q.durationMinutes,0),H=0;try{let U=T0(A5,"tasks.json");if(u0(U))H=JSON.parse(p6(U,"utf-8")).filter((N)=>{if(!N.done)return!1;return new Date(N.createdAt)>=J}).length}catch{}let W=UN(Q,Z,K,V,G,H,Y);return{project:Q,period:Z,gitSummary:K,sessions:V,totalMinutes:G,completedTasks:H,markdown:W}}function UN($,Z,Y,Q,z,J,X){let K=X==="pt",V=[],G=new Date,H=G.toLocaleDateString(K?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(V.push(`# ${K?"Relatorio de Progresso":"Work Progress Report"}`),V.push(`**${K?"Projeto":"Project"}:** ${$.name}`),V.push(`**${K?"Periodo":"Period"}:** ${Z} (${H})`),V.push(`**${K?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)V.push(`**Tech:** ${$.techStack.join(", ")}`);V.push("");let W=Math.floor(z/60),U=z%60;if(V.push(`## ${K?"Tempo Trabalhado":"Time Tracked"}`),V.push(`- **${K?"Total":"Total"}:** ${W}h ${U}m`),V.push(`- **${K?"Sessoes":"Sessions"}:** ${Q.length}`),J>0)V.push(`- **${K?"Tarefas concluidas":"Tasks completed"}:** ${J}`);if(V.push(""),Y&&Y.commits>0){if(V.push(`## ${K?"Atividade Git":"Git Activity"}`),V.push(`- **Commits:** ${Y.commits}`),Y.authors.length>0)V.push(`- **${K?"Autores":"Authors"}:** ${Y.authors.join(", ")}`);if(V.push(`- **${K?"Arquivos alterados":"Files changed"}:** ${Y.filesChanged}`),V.push(`- **${K?"Linhas":"Lines"}:** +${Y.insertions} / -${Y.deletions}`),Y.messages.length>0){V.push(""),V.push(`### ${K?"Commits recentes":"Recent commits"}`);for(let q of Y.messages.slice(0,15))V.push(`- ${q}`)}if(Y.topFiles.length>0){V.push(""),V.push(`### ${K?"Arquivos mais alterados":"Most changed files"}`);for(let q of Y.topFiles.slice(0,8))V.push(`- \`${q}\``)}V.push("")}else V.push(`## ${K?"Atividade Git":"Git Activity"}`),V.push(K?"_Nenhum commit no periodo._":"_No commits in this period._"),V.push("");if(Q.length>0){V.push(`## ${K?"Sessoes de Trabalho":"Work Sessions"}`);for(let q of Q){let N=new Date(q.startedAt).toLocaleTimeString(K?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),C=q.durationMinutes>0?`${q.durationMinutes}m`:K?"em andamento":"ongoing",M=q.notes?` \u2014 ${q.notes}`:"";V.push(`- ${N} (${C})${M}`)}V.push("")}return V.push("---"),V.push(K?`_Gerado por smolerclaw em ${G.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${G.toLocaleString("en-US")}_`),V.join(`
267
- `)}function i6($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===Z2?" [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}):
265
+ `)}`}function EN(){return CN().slice(0,8)}g();import{existsSync as c0,mkdirSync as FN,readFileSync as l6}from"fs";import{join as I0,basename as LN}from"path";import{randomUUID as RN}from"crypto";var T5="",o0=[],l0=[],G1=[],Q2=null,SX=()=>I0(T5,"projects.json"),wX=()=>I0(T5,"work-sessions.json"),kX=()=>I0(T5,"opportunities.json"),fX=()=>I0(T5,"active-project.txt");function jN(){j(SX(),JSON.stringify(o0,null,2))}function e4(){j(wX(),JSON.stringify(l0,null,2))}function bX(){j(kX(),JSON.stringify(G1,null,2))}function PN(){j(fX(),Q2||"")}function AN(){o0=t4(SX,[]),l0=t4(wX,[]),G1=t4(kX,[]);let $=fX();if(c0($))try{Q2=l6($,"utf-8").trim()||null}catch{Q2=null}}function t4($,Z){let Y=$();if(!c0(Y))return Z;try{return JSON.parse(l6(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 yX($){if(T5=$,!c0($))FN($,{recursive:!0});AN()}function $Y($,Z,Y="",Q=[],z=[]){let J={id:ZY(),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 o0=[...o0,J],jN(),J}function o6($){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 I5($=!1){return($?o0.filter((Y)=>Y.active):[...o0]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function S5($){let Z=o6($);if(!Z)return null;return Q2=Z.id,PN(),Z}function z2(){if(!Q2)return null;return o0.find(($)=>$.id===Q2)||null}function i6($,Z=""){if(!o0.find((z)=>z.id===$))return null;DN($);let Q={id:ZY(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return l0=[...l0,Q],e4(),Q}function n6($,Z){let Y=l0.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 l0=l0.map((X)=>X.id===$?{...X,endedAt:Q.toISOString(),durationMinutes:J,notes:Z?`${X.notes}
266
+ ${Z}`.trim():X.notes}:X),e4(),l0.find((X)=>X.id===$)||null}function DN($){let Z=new Date;l0=l0.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}),e4()}function J2($){return l0.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function TN($,Z,Y){let Q=Y||new Date;return l0.filter((z)=>{if(z.projectId!==$)return!1;let J=new Date(z.startedAt);return J>=Z&&J<=Q})}async function IN($,Z="1 day ago"){if(!c0(I0($,".git")))return null;try{let Y=await c6(["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(`
267
+ `).filter(Boolean),z=[...new Set(Q.map((N)=>N.split("|||")[0]))],J=Q.map((N)=>N.split("|||")[1]||"").filter(Boolean),X=await c6(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),K=await c6(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),V=0,G=0,W=0;if(K.ok&&K.stdout.trim())for(let N of K.stdout.trim().split(`
268
+ `)){let C=N.match(/(\d+)\s+files?\s+changed/),M=N.match(/(\d+)\s+insertions?/),F=N.match(/(\d+)\s+deletions?/);if(C)V+=parseInt(C[1]);if(M)G+=parseInt(M[1]);if(F)W+=parseInt(F[1])}let H=await c6(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),U=new Map;if(H.ok&&H.stdout.trim())for(let N of H.stdout.trim().split(`
269
+ `).filter(Boolean))U.set(N,(U.get(N)||0)+1);let q=[...U.entries()].sort((N,C)=>C[1]-N[1]).slice(0,10).map(([N])=>N);return{commits:Q.length,authors:z,filesChanged:V,insertions:G,deletions:W,topFiles:q,messages:J}}catch{return null}}async function c6($,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 vX($,Z,Y,Q=[],z="media",J=null){let X=new Date().toISOString(),K={id:ZY(),title:$.trim(),description:Z.trim(),source:Y.trim(),techRequired:Q.map((V)=>V.toLowerCase()),priority:z,status:"nova",deadline:J,createdAt:X,updatedAt:X};return G1=[...G1,K],bX(),K}function xX($,Z){if(!G1.find((Q)=>Q.id===$))return null;return G1=G1.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),bX(),G1.find((Q)=>Q.id===$)||null}function r6($,Z){let Y=[...G1];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 a6($,Z="today",Y="pt"){let Q=o6($);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 IN(Q.path,X),V=TN(Q.id,J),G=V.reduce((U,q)=>U+q.durationMinutes,0),W=0;try{let U=I0(T5,"tasks.json");if(c0(U))W=JSON.parse(l6(U,"utf-8")).filter((N)=>{if(!N.done)return!1;return new Date(N.createdAt)>=J}).length}catch{}let H=SN(Q,Z,K,V,G,W,Y);return{project:Q,period:Z,gitSummary:K,sessions:V,totalMinutes:G,completedTasks:W,markdown:H}}function SN($,Z,Y,Q,z,J,X){let K=X==="pt",V=[],G=new Date,W=G.toLocaleDateString(K?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(V.push(`# ${K?"Relatorio de Progresso":"Work Progress Report"}`),V.push(`**${K?"Projeto":"Project"}:** ${$.name}`),V.push(`**${K?"Periodo":"Period"}:** ${Z} (${W})`),V.push(`**${K?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)V.push(`**Tech:** ${$.techStack.join(", ")}`);V.push("");let H=Math.floor(z/60),U=z%60;if(V.push(`## ${K?"Tempo Trabalhado":"Time Tracked"}`),V.push(`- **${K?"Total":"Total"}:** ${H}h ${U}m`),V.push(`- **${K?"Sessoes":"Sessions"}:** ${Q.length}`),J>0)V.push(`- **${K?"Tarefas concluidas":"Tasks completed"}:** ${J}`);if(V.push(""),Y&&Y.commits>0){if(V.push(`## ${K?"Atividade Git":"Git Activity"}`),V.push(`- **Commits:** ${Y.commits}`),Y.authors.length>0)V.push(`- **${K?"Autores":"Authors"}:** ${Y.authors.join(", ")}`);if(V.push(`- **${K?"Arquivos alterados":"Files changed"}:** ${Y.filesChanged}`),V.push(`- **${K?"Linhas":"Lines"}:** +${Y.insertions} / -${Y.deletions}`),Y.messages.length>0){V.push(""),V.push(`### ${K?"Commits recentes":"Recent commits"}`);for(let q of Y.messages.slice(0,15))V.push(`- ${q}`)}if(Y.topFiles.length>0){V.push(""),V.push(`### ${K?"Arquivos mais alterados":"Most changed files"}`);for(let q of Y.topFiles.slice(0,8))V.push(`- \`${q}\``)}V.push("")}else V.push(`## ${K?"Atividade Git":"Git Activity"}`),V.push(K?"_Nenhum commit no periodo._":"_No commits in this period._"),V.push("");if(Q.length>0){V.push(`## ${K?"Sessoes de Trabalho":"Work Sessions"}`);for(let q of Q){let N=new Date(q.startedAt).toLocaleTimeString(K?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),C=q.durationMinutes>0?`${q.durationMinutes}m`:K?"em andamento":"ongoing",M=q.notes?` \u2014 ${q.notes}`:"";V.push(`- ${N} (${C})${M}`)}V.push("")}return V.push("---"),V.push(K?`_Gerado por smolerclaw em ${G.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${G.toLocaleString("en-US")}_`),V.join(`
270
+ `)}function s6($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===Q2?" [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}):
268
271
  ${Z.join(`
269
- `)}`}function n6($){let Z=$.id===Z2?" [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=Q2($.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(`
270
- `)}function r6($){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}):
272
+ `)}`}function t6($){let Z=$.id===Q2?" [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=J2($.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(`
273
+ `)}function e6($){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}):
271
274
  ${Z.join(`
272
- `)}`}function a6(){let $=Y2();if(!$)return"";let Z=Q2($.id),Y=K1.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(`
273
- `)}function s6($){let Z=c0.find((z)=>z.path===$);if(Z)return Z;if(!u0(T0($,".git")))return null;let Y=[];if(u0(T0($,"package.json")))try{let z=JSON.parse(p6(T0($,"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(u0(T0($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(u0(T0($,"Cargo.toml")))Y.push("rust");if(u0(T0($,"go.mod")))Y.push("go");if(u0(T0($,"requirements.txt"))||u0(T0($,"pyproject.toml")))Y.push("python");let Q=zN($);return r4(Q,$,"",[],Y)}function a4(){return JN().slice(0,8)}h();Z0();import{existsSync as e4,mkdirSync as qN,readFileSync as TX}from"fs";import{join as IX,basename as BN}from"path";var wX=2,SX="pitwall-baselines.json",NN=0.1,ON=0.05,CN=5000000,MN=512000,AX=2048,EN=120000,$9="",W0=[];function kX($){if($9=$,!e4($))qN($,{recursive:!0});TN()}async function DX($,Z){let Q=[...Y5(),$],z=process.cpuUsage(),J=Bun.nanoseconds(),X=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),K=setTimeout(()=>X.kill(),EN),V=X.pid,G=FN(V),[,H]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),W=await X.exited;clearTimeout(K);let U=Bun.nanoseconds(),q=process.cpuUsage(z),N=await G,C=H.length>AX?`...${H.slice(-AX)}`:H;return{durationNs:U-J,peakMemoryBytes:N,cpuUserUs:q.user,cpuSystemUs:q.system,exitCode:W,stderr:C.trim()}}async function $Y($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),z=Z.scriptKey||DN($);if(Z.warmup&&Q>1)await DX($,Y);let J=[];for(let H=0;H<Q;H++)J.push(await DX($,Y));let X=J[J.length-1],K=J.map((H)=>H.durationNs),V={durationNs:s4(K),peakMemoryBytes:Math.max(...J.map((H)=>H.peakMemoryBytes)),cpuUserUs:s4(J.map((H)=>H.cpuUserUs)),cpuSystemUs:s4(J.map((H)=>H.cpuSystemUs))},G=Q>1?{min:Math.min(...K),max:Math.max(...K),median:V.durationNs,stddev:AN(K)}:null;return{scriptKey:z,command:$,metrics:V,spread:G,exitCode:X.exitCode,stderr:X.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function FN($){try{if(R){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(e4(Z)){let Q=TX(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function fX($,Z=[]){let Y=W0.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 W0=W0.map((V)=>V.scriptKey===$.scriptKey?K:V),Z9(),K}let z={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return W0=[...W0,z],Z9(),z}function LN($){return W0.find((Z)=>Z.scriptKey===$)||null}function bX(){return[...W0].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function ZY($){let Z=W0.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return W0=[...W0.slice(0,Z),...W0.slice(Z+1)],Z9(),!0}function yX($,Z=[]){ZY($.scriptKey);let Y=new Date().toISOString(),Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return W0=[...W0,Q],Z9(),Q}function YY($){let Z=LN($.scriptKey),Y=[];if(Z)Y.push(t6("duration",Z.metrics.durationNs,$.metrics.durationNs,CN),t6("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,MN),t6("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),t6("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((J)=>J.severity==="regression"),z=PN($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:z}}function t6($,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>NN)X="regression";else if(J>ON)X="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(J*1e4)/100,absoluteDelta:z,severity:X}}function D1($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function t4($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function e6($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function RN($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function jN($){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 PN($,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: ${D1($.metrics.durationNs)}`),z.push(` Memoria: ${t4($.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${e6($.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${e6($.metrics.cpuSystemUs)}`),$.spread){z.push(""),z.push("--- Dispersao ---"),z.push(` Min: ${D1($.spread.min)}`),z.push(` Max: ${D1($.spread.max)}`),z.push(` Mediana: ${D1($.spread.median)}`),z.push(` Stddev: ${D1($.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(`
274
- `);z.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${vX(Z.updatedAt)}) ---`),z.push(` Duracao: ${D1(Z.metrics.durationNs)}`),z.push(` Memoria: ${t4(Z.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${e6(Z.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${e6(Z.metrics.cpuSystemUs)}`),z.push(""),z.push("--- Comparacao ---");for(let J of Y){let X=J.deltaPercent>=0?"+":"",K=jN(J.metric);z.push(` ${RN(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(`
275
- `)}function vX($){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 xX($){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=vX(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${D1(Y.metrics.durationNs)} | Memoria: ${t4(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: ${D1(Y.spread.min)} ~ ${D1(Y.spread.max)} (CV ${J}%)`)}Z.push("")}return Z.join(`
276
- `)}function s4($){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 AN($){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 DN($){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 BN(Z[0])}function TN(){let $=IX($9,SX);if(!e4($)){W0=[];return}try{let Z=JSON.parse(TX($,"utf-8"));if(Z.version!==wX&&Z.version!==1){W0=[];return}W0=(Z.baselines||[]).map(IN)}catch{W0=[]}}function IN($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function Z9(){if(!$9)return;let $=IX($9,SX);P($,JSON.stringify({baselines:W0,version:wX},null,2))}Z0();import{readdirSync as wN,readFileSync as SN,lstatSync as kN}from"fs";import{join as fN,resolve as t$,relative as QY,dirname as bN,extname as yN}from"path";var vN=[".ts",".tsx",".mts",".cts"],xN=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],_N=new Set(l5),_X=5000,hN=5000,hX=new Map;function gN($){let Z=hX.get($);if(Z&&Date.now()-Z.ts<hN)return Z.graph;return null}function mN($,Z){hX.set($,{graph:Z,ts:Date.now()})}var pN=[/^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 uN($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of pN){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 dN($){let Z=[];function Y(Q){if(Z.length>=_X)return;let z;try{z=wN(Q)}catch{return}for(let J of z){if(Z.length>=_X)return;if(_N.has(J))continue;let X=fN(Q,J),K;try{K=kN(X)}catch{continue}if(K.isSymbolicLink())continue;if(K.isDirectory())Y(X);else if(K.isFile()&&vN.includes(yN(J)))Z.push(X)}}return Y($),Z}function cN($,Z,Y){let Q=bN(Z),z=t$(Q,$);if(Y.has(z))return z;for(let J of xN){let X=z+J;if(Y.has(X))return X}return null}function zY($){let Z=t$($),Y=gN(Z);if(Y)return Y;let Q=dN(Z),z=new Set(Q),J=new Map,X=new Map;for(let V of Q)J.set(V,new Set),X.set(V,new Set);for(let V of Q){let G;try{G=SN(V,"utf-8")}catch{continue}let H=uN(G),W=J.get(V);for(let U of H){let q=cN(U,V,z);if(q){W.add(q);let N=X.get(q)||new Set;N.add(V),X.set(q,N)}}}let K={imports:J,importedBy:X,files:Q,root:Z};return mN(Z,K),K}function JY($,Z){let Y=t$(Z),Q=$.importedBy.get(Y)||new Set,z=[...Q],J=new Set([Y]),X=[],K=new Map,V=0;for(let N of Q)X.push({file:N,depth:1}),J.add(N),K.set(N,1);let G=[],H=0;while(H<X.length){let{file:N,depth:C}=X[H++];if(C>V)V=C;if(!Q.has(N))G.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 W=gX(Y,$.importedBy,new Set,0),U=(N)=>QY($.root,N).replace(/\\/g,"/"),q=new Map;for(let[N,C]of K)q.set(U(N),C);return{target:U(Y),directDependents:z.map(U),transitiveDependents:G.map(U),depthMap:q,totalAffected:z.length+G.length,depth:V,tree:mX(W,$.root)}}function gX($,Z,Y,Q){Y.add($);let z=Z.get($)||new Set,J=[];for(let X of z)if(!Y.has(X))J.push(gX(X,Z,Y,Q+1));return{file:$,depth:Q,children:J}}function mX($,Z){return{file:QY(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>mX(Y,Z))}}function pX($,Z){let Y=t$(Z),Q=JY($,Z),z=(N)=>t$($.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 V=[],G=new Set,H=0;while(H<K.length){let N=K[H++];V.push(N),G.add(N);let C=$.imports.get(N)||new Set;for(let M of C)if(J.has(M)&&!G.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(!G.has(N)&&N!==Y)V.push(N);let W=[Y,...V],U=(N)=>QY($.root,N).replace(/\\/g,"/"),q=W.map((N)=>{let M=[...$.imports.get(N)||new Set].filter((v)=>J.has(v)).map(U),F=U(N),T=N===Y?0:Q.depthMap.get(F)||1;return{file:F,depth:T,dependsOn:M}});return{target:U(Y),order:q,totalFiles:q.length}}function uX($){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 ---"),dX($.tree,Z,"",!0),Z.join(`
277
- `)}function dX($,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++)dX($.children[K],Z,X,K===$.children.length-1)}function cX($){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(`
278
- `)}h();import{existsSync as XY,mkdirSync as lN,readFileSync as oX}from"fs";import{join as iX}from"path";import{randomUUID as oN}from"crypto";var KY=[{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"}],VY="",T1=[],I1=[],nX=()=>iX(VY,"engine-tradeoffs.json"),rX=()=>iX(VY,"engine-incidents.json");function iN(){P(nX(),JSON.stringify(T1,null,2))}function nN(){P(rX(),JSON.stringify(I1,null,2))}function rN(){let $=nX();if(!XY($)){T1=[];return}try{T1=JSON.parse(oX($,"utf-8"))}catch{T1=[]}}function aN(){let $=rX();if(!XY($)){I1=[];return}try{I1=JSON.parse(oX($,"utf-8"))}catch{I1=[]}}function aX($){if(VY=$,!XY($))lN($,{recursive:!0});rN(),aN()}function sX($,Z,Y=KY){let Q=Y.reduce((H,W)=>H+W.weight,0);if(Math.abs(Q-1)>0.01)Y=Y.map((W)=>({...W,weight:W.weight/Q}));let z={};for(let H of Z){let W=0;for(let U of Y){let q=H.scores[U.name]??3;W+=q*U.weight}z[H.name]=Math.round(W*100)/100}let X=Object.entries(z).sort(([,H],[,W])=>W-H)[0]?.[0]||Z[0]?.name||"N/A",K=Z.find((H)=>H.name===X),V=sN($,Z,Y,z,X,K),G={id:KK(),context:$,options:Z,criteria:Y,recommendation:X,weightedScores:z,adr:V,createdAt:new Date().toISOString()};return T1=[...T1,G],iN(),G}function sN($,Z,Y,Q,z,J){let K=new Date().toISOString().split("T")[0],V=[`# ADR: ${$.title}`,"",`**Date:** ${K}`,"**Status:** Proposed","","## Context","",$.background,""];if($.constraints.length>0){V.push("### Constraints"),V.push("");for(let W of $.constraints)V.push(`- ${W}`);V.push("")}if($.stakeholders.length>0){V.push("### Stakeholders"),V.push("");for(let W of $.stakeholders)V.push(`- ${W}`);V.push("")}V.push("## Options Considered"),V.push("");for(let W of Z){if(V.push(`### ${W.name}`),V.push(""),V.push(W.description),V.push(""),W.pros.length>0){V.push("**Pros:**");for(let U of W.pros)V.push(`- ${U}`);V.push("")}if(W.cons.length>0){V.push("**Cons:**");for(let U of W.cons)V.push(`- ${U}`);V.push("")}}V.push("## Evaluation Matrix"),V.push("");let G=["Criterion (Weight)",...Z.map((W)=>W.name)];V.push(`| ${G.join(" | ")} |`),V.push(`| ${G.map(()=>"---").join(" | ")} |`);for(let W of Y){let U=Math.round(W.weight*100),q=[`${W.name} (${U}%)`,...Z.map((N)=>{return`${N.scores[W.name]??3}/5`})];V.push(`| ${q.join(" | ")} |`)}let H=["**Weighted Total**",...Z.map((W)=>`**${Q[W.name]?.toFixed(2)??"0.00"}**`)];if(V.push(`| ${H.join(" | ")} |`),V.push(""),V.push("## Decision"),V.push(""),V.push(`**Recommended:** ${z}`),V.push(""),J){if(V.push(`Based on the weighted evaluation, **${z}** scores highest with a weighted total of ${Q[z]?.toFixed(2)}.`),V.push(""),J.pros.length>0){V.push("Key advantages:");for(let W of J.pros.slice(0,3))V.push(`- ${W}`);V.push("")}}if(V.push("## Consequences"),V.push(""),V.push("### Positive"),V.push(""),J&&J.pros.length>0)for(let W of J.pros)V.push(`- ${W}`);else V.push("- *To be determined based on implementation*");if(V.push(""),V.push("### Negative"),V.push(""),J&&J.cons.length>0)for(let W of J.cons)V.push(`- ${W}`);else V.push("- *To be determined based on implementation*");return V.push(""),V.push("---"),V.push(""),V.push("*Generated by Decision Engine*"),V.join(`
279
- `)}function lX($){let Z=$.toLowerCase(),Y=[/error/gi,/exception/gi,/fail/gi,/crash/gi,/timeout/gi,/null/gi,/undefined/gi,/nan/gi,/overflow/gi,/underflow/gi,/memory/gi,/leak/gi,/deadlock/gi,/race/gi,/condition/gi,/connection/gi,/refused/gi,/denied/gi,/unauthorized/gi,/invalid/gi,/missing/gi,/corrupt/gi,/malformed/gi],Q=new Set;for(let V of Y){let G=Z.match(V);if(G)for(let H of G)Q.add(H.toLowerCase())}let z=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,J=$.match(z)||[];for(let V of J)if(V.length>3&&!V.match(/^(the|and|for|with|from|this|that)$/i))Q.add(V.toLowerCase());let X=/[A-Z]{2,}_[A-Z0-9_]+|E[0-9]{3,}/g,K=$.match(X)||[];for(let V of K)Q.add(V.toLowerCase());return[...Q]}function tN($,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 tX($,Z){let Y=Z?`${$}
280
- ${Z}`:$,Q=lX(Y),z=[];for(let V of I1){let G=`${V.title} ${V.description} ${V.stacktrace||""} ${V.rootCause} ${V.solution}`,H=lX(G),W=tN(Q,H);if(W>0.1){let U=Q.filter((C)=>H.includes(C)),q=[];for(let C of V.relatedDecisions){let M=y2(C);if(M.length>0)q.push(M[0])}let N=[];if(V.solution)N.push(`Apply solution: ${V.solution}`);if(V.rootCause)N.push(`Investigate root cause: ${V.rootCause}`);for(let C of q)N.push(`Review decision: ${C.title}`);z.push({incident:V,similarity:W,matchedKeywords:U,relatedDecisions:q,suggestedActions:N})}}z.sort((V,G)=>G.similarity-V.similarity);let J=y2($.slice(0,50)),X=j5($.slice(0,50)),K=eN($,z,J,X);return{query:$,matches:z.slice(0,5),materialsFound:X.slice(0,5),summary:K}}function eN($,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(`
281
- `)}function eX($,Z,Y,Q,z,J=[],X=[]){let K={id:KK(),title:$.trim(),description:Z.trim(),stacktrace:z?.trim(),rootCause:Y.trim(),solution:Q.trim(),relatedDecisions:J,tags:X.map((V)=>V.toLowerCase()),createdAt:new Date().toISOString()};return I1=[...I1,K],nN(),K}function $K($){let Z=$.toLowerCase();return I1.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 ZK($=10){return[...I1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function YK($=10){return[...T1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function QK($){let Z=$.toLowerCase();return T1.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 zK($){return T1.find((Z)=>Z.id===$)||null}function JK($){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}):
275
+ `)}`}function $9(){let $=z2();if(!$)return"";let Z=J2($.id),Y=G1.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(`
276
+ `)}function Z9($){let Z=o0.find((z)=>z.path===$);if(Z)return Z;if(!c0(I0($,".git")))return null;let Y=[];if(c0(I0($,"package.json")))try{let z=JSON.parse(l6(I0($,"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(c0(I0($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(c0(I0($,"Cargo.toml")))Y.push("rust");if(c0(I0($,"go.mod")))Y.push("go");if(c0(I0($,"requirements.txt"))||c0(I0($,"pyproject.toml")))Y.push("python");let Q=LN($);return $Y(Q,$,"",[],Y)}function ZY(){return RN().slice(0,8)}g();Y0();import{existsSync as zY,mkdirSync as wN,readFileSync as gX}from"fs";import{join as mX,basename as kN}from"path";var pX=2,uX="pitwall-baselines.json",fN=0.1,bN=0.05,yN=5000000,vN=512000,_X=2048,xN=120000,z9="",U0=[];function dX($){if(z9=$,!zY($))wN($,{recursive:!0});cN()}async function hX($,Z){let Q=[...z5(),$],z=process.cpuUsage(),J=Bun.nanoseconds(),X=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),K=setTimeout(()=>X.kill(),xN),V=X.pid,G=_N(V),[,W]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),H=await X.exited;clearTimeout(K);let U=Bun.nanoseconds(),q=process.cpuUsage(z),N=await G,C=W.length>_X?`...${W.slice(-_X)}`:W;return{durationNs:U-J,peakMemoryBytes:N,cpuUserUs:q.user,cpuSystemUs:q.system,exitCode:H,stderr:C.trim()}}async function JY($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),z=Z.scriptKey||dN($);if(Z.warmup&&Q>1)await hX($,Y);let J=[];for(let W=0;W<Q;W++)J.push(await hX($,Y));let X=J[J.length-1],K=J.map((W)=>W.durationNs),V={durationNs:YY(K),peakMemoryBytes:Math.max(...J.map((W)=>W.peakMemoryBytes)),cpuUserUs:YY(J.map((W)=>W.cpuUserUs)),cpuSystemUs:YY(J.map((W)=>W.cpuSystemUs))},G=Q>1?{min:Math.min(...K),max:Math.max(...K),median:V.durationNs,stddev:uN(K)}:null;return{scriptKey:z,command:$,metrics:V,spread:G,exitCode:X.exitCode,stderr:X.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function _N($){try{if(R){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(zY(Z)){let Q=gX(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function cX($,Z=[]){let Y=U0.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 U0=U0.map((V)=>V.scriptKey===$.scriptKey?K:V),J9(),K}let z={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return U0=[...U0,z],J9(),z}function hN($){return U0.find((Z)=>Z.scriptKey===$)||null}function lX(){return[...U0].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function XY($){let Z=U0.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return U0=[...U0.slice(0,Z),...U0.slice(Z+1)],J9(),!0}function oX($,Z=[]){XY($.scriptKey);let Y=new Date().toISOString(),Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return U0=[...U0,Q],J9(),Q}function KY($){let Z=hN($.scriptKey),Y=[];if(Z)Y.push(Y9("duration",Z.metrics.durationNs,$.metrics.durationNs,yN),Y9("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,vN),Y9("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),Y9("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((J)=>J.severity==="regression"),z=pN($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:z}}function Y9($,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>fN)X="regression";else if(J>bN)X="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(J*1e4)/100,absoluteDelta:z,severity:X}}function I1($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function QY($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function Q9($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function gN($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function mN($){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 pN($,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: ${I1($.metrics.durationNs)}`),z.push(` Memoria: ${QY($.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${Q9($.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${Q9($.metrics.cpuSystemUs)}`),$.spread){z.push(""),z.push("--- Dispersao ---"),z.push(` Min: ${I1($.spread.min)}`),z.push(` Max: ${I1($.spread.max)}`),z.push(` Mediana: ${I1($.spread.median)}`),z.push(` Stddev: ${I1($.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(`
277
+ `);z.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${iX(Z.updatedAt)}) ---`),z.push(` Duracao: ${I1(Z.metrics.durationNs)}`),z.push(` Memoria: ${QY(Z.metrics.peakMemoryBytes)}`),z.push(` CPU (user): ${Q9(Z.metrics.cpuUserUs)}`),z.push(` CPU (sys): ${Q9(Z.metrics.cpuSystemUs)}`),z.push(""),z.push("--- Comparacao ---");for(let J of Y){let X=J.deltaPercent>=0?"+":"",K=mN(J.metric);z.push(` ${gN(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(`
278
+ `)}function iX($){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 nX($){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=iX(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${I1(Y.metrics.durationNs)} | Memoria: ${QY(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: ${I1(Y.spread.min)} ~ ${I1(Y.spread.max)} (CV ${J}%)`)}Z.push("")}return Z.join(`
279
+ `)}function YY($){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 uN($){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 dN($){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 kN(Z[0])}function cN(){let $=mX(z9,uX);if(!zY($)){U0=[];return}try{let Z=JSON.parse(gX($,"utf-8"));if(Z.version!==pX&&Z.version!==1){U0=[];return}U0=(Z.baselines||[]).map(lN)}catch{U0=[]}}function lN($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function J9(){if(!z9)return;let $=mX(z9,uX);j($,JSON.stringify({baselines:U0,version:pX},null,2))}Y0();import{readdirSync as oN,readFileSync as iN,lstatSync as nN}from"fs";import{join as rN,resolve as $3,relative as VY,dirname as aN,extname as sN}from"path";var tN=[".ts",".tsx",".mts",".cts"],eN=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],$O=new Set(i5),rX=5000,ZO=5000,aX=new Map;function YO($){let Z=aX.get($);if(Z&&Date.now()-Z.ts<ZO)return Z.graph;return null}function QO($,Z){aX.set($,{graph:Z,ts:Date.now()})}var zO=[/^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 JO($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of zO){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 XO($){let Z=[];function Y(Q){if(Z.length>=rX)return;let z;try{z=oN(Q)}catch{return}for(let J of z){if(Z.length>=rX)return;if($O.has(J))continue;let X=rN(Q,J),K;try{K=nN(X)}catch{continue}if(K.isSymbolicLink())continue;if(K.isDirectory())Y(X);else if(K.isFile()&&tN.includes(sN(J)))Z.push(X)}}return Y($),Z}function KO($,Z,Y){let Q=aN(Z),z=$3(Q,$);if(Y.has(z))return z;for(let J of eN){let X=z+J;if(Y.has(X))return X}return null}function GY($){let Z=$3($),Y=YO(Z);if(Y)return Y;let Q=XO(Z),z=new Set(Q),J=new Map,X=new Map;for(let V of Q)J.set(V,new Set),X.set(V,new Set);for(let V of Q){let G;try{G=iN(V,"utf-8")}catch{continue}let W=JO(G),H=J.get(V);for(let U of W){let q=KO(U,V,z);if(q){H.add(q);let N=X.get(q)||new Set;N.add(V),X.set(q,N)}}}let K={imports:J,importedBy:X,files:Q,root:Z};return QO(Z,K),K}function WY($,Z){let Y=$3(Z),Q=$.importedBy.get(Y)||new Set,z=[...Q],J=new Set([Y]),X=[],K=new Map,V=0;for(let N of Q)X.push({file:N,depth:1}),J.add(N),K.set(N,1);let G=[],W=0;while(W<X.length){let{file:N,depth:C}=X[W++];if(C>V)V=C;if(!Q.has(N))G.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 H=sX(Y,$.importedBy,new Set,0),U=(N)=>VY($.root,N).replace(/\\/g,"/"),q=new Map;for(let[N,C]of K)q.set(U(N),C);return{target:U(Y),directDependents:z.map(U),transitiveDependents:G.map(U),depthMap:q,totalAffected:z.length+G.length,depth:V,tree:tX(H,$.root)}}function sX($,Z,Y,Q){Y.add($);let z=Z.get($)||new Set,J=[];for(let X of z)if(!Y.has(X))J.push(sX(X,Z,Y,Q+1));return{file:$,depth:Q,children:J}}function tX($,Z){return{file:VY(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>tX(Y,Z))}}function eX($,Z){let Y=$3(Z),Q=WY($,Z),z=(N)=>$3($.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 V=[],G=new Set,W=0;while(W<K.length){let N=K[W++];V.push(N),G.add(N);let C=$.imports.get(N)||new Set;for(let M of C)if(J.has(M)&&!G.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(!G.has(N)&&N!==Y)V.push(N);let H=[Y,...V],U=(N)=>VY($.root,N).replace(/\\/g,"/"),q=H.map((N)=>{let M=[...$.imports.get(N)||new Set].filter((v)=>J.has(v)).map(U),F=U(N),T=N===Y?0:Q.depthMap.get(F)||1;return{file:F,depth:T,dependsOn:M}});return{target:U(Y),order:q,totalFiles:q.length}}function $K($){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 ---"),ZK($.tree,Z,"",!0),Z.join(`
280
+ `)}function ZK($,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++)ZK($.children[K],Z,X,K===$.children.length-1)}function YK($){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(`
281
+ `)}g();import{existsSync as HY,mkdirSync as VO,readFileSync as zK}from"fs";import{join as JK}from"path";import{randomUUID as GO}from"crypto";var UY=[{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"}],qY="",S1=[],w1=[],XK=()=>JK(qY,"engine-tradeoffs.json"),KK=()=>JK(qY,"engine-incidents.json");function WO(){j(XK(),JSON.stringify(S1,null,2))}function HO(){j(KK(),JSON.stringify(w1,null,2))}function UO(){let $=XK();if(!HY($)){S1=[];return}try{S1=JSON.parse(zK($,"utf-8"))}catch{S1=[]}}function qO(){let $=KK();if(!HY($)){w1=[];return}try{w1=JSON.parse(zK($,"utf-8"))}catch{w1=[]}}function VK($){if(qY=$,!HY($))VO($,{recursive:!0});UO(),qO()}function GK($,Z,Y=UY){let Q=Y.reduce((W,H)=>W+H.weight,0);if(Math.abs(Q-1)>0.01)Y=Y.map((H)=>({...H,weight:H.weight/Q}));let z={};for(let W of Z){let H=0;for(let U of Y){let q=W.scores[U.name]??3;H+=q*U.weight}z[W.name]=Math.round(H*100)/100}let X=Object.entries(z).sort(([,W],[,H])=>H-W)[0]?.[0]||Z[0]?.name||"N/A",K=Z.find((W)=>W.name===X),V=BO($,Z,Y,z,X,K),G={id:EK(),context:$,options:Z,criteria:Y,recommendation:X,weightedScores:z,adr:V,createdAt:new Date().toISOString()};return S1=[...S1,G],WO(),G}function BO($,Z,Y,Q,z,J){let K=new Date().toISOString().split("T")[0],V=[`# ADR: ${$.title}`,"",`**Date:** ${K}`,"**Status:** Proposed","","## Context","",$.background,""];if($.constraints.length>0){V.push("### Constraints"),V.push("");for(let H of $.constraints)V.push(`- ${H}`);V.push("")}if($.stakeholders.length>0){V.push("### Stakeholders"),V.push("");for(let H of $.stakeholders)V.push(`- ${H}`);V.push("")}V.push("## Options Considered"),V.push("");for(let H of Z){if(V.push(`### ${H.name}`),V.push(""),V.push(H.description),V.push(""),H.pros.length>0){V.push("**Pros:**");for(let U of H.pros)V.push(`- ${U}`);V.push("")}if(H.cons.length>0){V.push("**Cons:**");for(let U of H.cons)V.push(`- ${U}`);V.push("")}}V.push("## Evaluation Matrix"),V.push("");let G=["Criterion (Weight)",...Z.map((H)=>H.name)];V.push(`| ${G.join(" | ")} |`),V.push(`| ${G.map(()=>"---").join(" | ")} |`);for(let H of Y){let U=Math.round(H.weight*100),q=[`${H.name} (${U}%)`,...Z.map((N)=>{return`${N.scores[H.name]??3}/5`})];V.push(`| ${q.join(" | ")} |`)}let W=["**Weighted Total**",...Z.map((H)=>`**${Q[H.name]?.toFixed(2)??"0.00"}**`)];if(V.push(`| ${W.join(" | ")} |`),V.push(""),V.push("## Decision"),V.push(""),V.push(`**Recommended:** ${z}`),V.push(""),J){if(V.push(`Based on the weighted evaluation, **${z}** scores highest with a weighted total of ${Q[z]?.toFixed(2)}.`),V.push(""),J.pros.length>0){V.push("Key advantages:");for(let H of J.pros.slice(0,3))V.push(`- ${H}`);V.push("")}}if(V.push("## Consequences"),V.push(""),V.push("### Positive"),V.push(""),J&&J.pros.length>0)for(let H of J.pros)V.push(`- ${H}`);else V.push("- *To be determined based on implementation*");if(V.push(""),V.push("### Negative"),V.push(""),J&&J.cons.length>0)for(let H of J.cons)V.push(`- ${H}`);else V.push("- *To be determined based on implementation*");return V.push(""),V.push("---"),V.push(""),V.push("*Generated by Decision Engine*"),V.join(`
282
+ `)}function QK($){let Z=$.toLowerCase(),Y=[/error/gi,/exception/gi,/fail/gi,/crash/gi,/timeout/gi,/null/gi,/undefined/gi,/nan/gi,/overflow/gi,/underflow/gi,/memory/gi,/leak/gi,/deadlock/gi,/race/gi,/condition/gi,/connection/gi,/refused/gi,/denied/gi,/unauthorized/gi,/invalid/gi,/missing/gi,/corrupt/gi,/malformed/gi],Q=new Set;for(let V of Y){let G=Z.match(V);if(G)for(let W of G)Q.add(W.toLowerCase())}let z=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,J=$.match(z)||[];for(let V of J)if(V.length>3&&!V.match(/^(the|and|for|with|from|this|that)$/i))Q.add(V.toLowerCase());let X=/[A-Z]{2,}_[A-Z0-9_]+|E[0-9]{3,}/g,K=$.match(X)||[];for(let V of K)Q.add(V.toLowerCase());return[...Q]}function NO($,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 WK($,Z){let Y=Z?`${$}
283
+ ${Z}`:$,Q=QK(Y),z=[];for(let V of w1){let G=`${V.title} ${V.description} ${V.stacktrace||""} ${V.rootCause} ${V.solution}`,W=QK(G),H=NO(Q,W);if(H>0.1){let U=Q.filter((C)=>W.includes(C)),q=[];for(let C of V.relatedDecisions){let M=x2(C);if(M.length>0)q.push(M[0])}let N=[];if(V.solution)N.push(`Apply solution: ${V.solution}`);if(V.rootCause)N.push(`Investigate root cause: ${V.rootCause}`);for(let C of q)N.push(`Review decision: ${C.title}`);z.push({incident:V,similarity:H,matchedKeywords:U,relatedDecisions:q,suggestedActions:N})}}z.sort((V,G)=>G.similarity-V.similarity);let J=x2($.slice(0,50)),X=A5($.slice(0,50)),K=OO($,z,J,X);return{query:$,matches:z.slice(0,5),materialsFound:X.slice(0,5),summary:K}}function OO($,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(`
284
+ `)}function HK($,Z,Y,Q,z,J=[],X=[]){let K={id:EK(),title:$.trim(),description:Z.trim(),stacktrace:z?.trim(),rootCause:Y.trim(),solution:Q.trim(),relatedDecisions:J,tags:X.map((V)=>V.toLowerCase()),createdAt:new Date().toISOString()};return w1=[...w1,K],HO(),K}function UK($){let Z=$.toLowerCase();return w1.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 qK($=10){return[...w1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function BK($=10){return[...S1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function NK($){let Z=$.toLowerCase();return S1.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 OK($){return S1.find((Z)=>Z.id===$)||null}function CK($){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}):
282
285
  ${Z.join(`
283
- `)}`}function XK($){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}):
286
+ `)}`}function MK($){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}):
284
287
  ${Z.join(`
285
- `)}`}function KK(){return oN().slice(0,8)}h();import{existsSync as $3,mkdirSync as VK,readFileSync as GY,readdirSync as $O,writeFileSync as GK}from"fs";import{join as _2}from"path";import{homedir as ZO}from"os";import{createHash as YO}from"crypto";var QO=20,HK=3,zO=0.6,JO={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"]},XO={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."}},e$="",z2="",g0={events:[],sessionStart:Date.now()},x2=new Map,w1=[],h0=[],I5=!1,WK=null,UK=()=>_2(e$,"usage-patterns.json"),qK=()=>_2(e$,"insights.json");function BK($,Z){if(e$=_2($,"docs-engine"),z2=_2(ZO(),".config","smolerclaw","materials","manual"),WK=Z||null,!$3(e$))VK(e$,{recursive:!0});if(!$3(z2))VK(z2,{recursive:!0});EO(),LO(),RO(),g0={events:[],sessionStart:Date.now()},I5=!0}function HY($){if(!I5)return;let Z={...$,timestamp:Date.now()},Y=[...g0.events,Z].slice(-QO);g0={...g0,events:Y},KO(Z),setImmediate(()=>VO(Z))}function KO($){let Z=`${$.type}:${$.name}`,Y=x2.get(Z);if(Y){let Q=Y.count+1,z=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;x2.set(Z,{action:Z,count:Q,avgDurationMs:z,lastUsed:$.timestamp})}else x2.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function VO($){let Z=g0.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:z}]of Object.entries(XO))if(Q.test(Z)){if(!w1.find((X)=>X.type==="inefficient_pattern"&&X.relatedActions.includes($.name)&&Date.now()-new Date(X.createdAt).getTime()<3600000)){let X={id:h2(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:z,relatedActions:g0.events.slice(-5).map((K)=>K.name),confidence:0.8,createdAt:new Date().toISOString()};NK(X)}}}async function w5(){if(!I5)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=GO();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=HO();$.insightsGenerated+=Y.length;let Q=WO();$.insightsGenerated+=Q.length;for(let z of[...Z,...Y,...Q])if(NK(z),await qO(z))$.manualUpdates++;return MO(),FO(),g0={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
286
- `),$}function GO(){let $=[],Z=UO(g0.events);for(let Y of Z)if(Y.count>=HK){let Q={id:h2(),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 HO(){let $=[],Z=new Set;for(let Y of g0.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(JO)){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>=zO){let K={id:h2(),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 WO(){let $=[];if(Date.now()-g0.sessionStart>1800000&&!g0.events.some((Q)=>Q.name==="save_memo"))$.push({id:h2(),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=g0.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!g0.events.some((Q)=>Q.name.includes("workflow")))$.push({id:h2(),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 UO($){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>=HK)}function NK($){if(!w1.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))w1=[...w1,$],WK?.($)}function OK($=5){return[...w1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function qO($){try{let Z=OO($.type),Y=`${$.id}.md`,Q=_2(z2,Y),z=h0.find((V)=>V.id===$.id),J=z?z.version+1:1,X={id:$.id,title:$.title,category:Z,content:NO($),tags:CO($),source:"auto_generated",version:J,createdAt:z?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},K=FK(X);return GK(Q,K,"utf-8"),h0=h0.filter((V)=>V.id!==X.id),h0=[...h0,X],!0}catch{return!1}}async function CK($,Z,Y="best_practice",Q=[]){if(!I5)return{success:!1,path:""};try{let z=h2(),J=`${PO($)}-${z.slice(0,4)}.md`,X=_2(z2,J),K={id:z,title:$,category:Y,content:Z,tags:Q,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},V=FK(K);return GK(X,V,"utf-8"),h0=[...h0,K],{success:!0,path:X,entry:K}}catch{return{success:!1,path:""}}}function BO($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return h0.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 MK($){let Z=$?BO($):h0;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=EK[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(`
287
- `)});return["# Manual de Uso Otimizado","",`Baseado em ${h0.length} entradas do manual vivo.`,"",...Y].join(`
288
- `)}var EK={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function NO($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
289
- `)}function FK($){let Z=EK[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
288
+ `)}`}function EK(){return GO().slice(0,8)}g();import{existsSync as Y3,mkdirSync as FK,readFileSync as BY,readdirSync as CO,writeFileSync as LK}from"fs";import{join as g2}from"path";import{homedir as MO}from"os";import{createHash as EO}from"crypto";var FO=20,RK=3,LO=0.6,RO={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"]},jO={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."}},Z3="",X2="",p0={events:[],sessionStart:Date.now()},h2=new Map,k1=[],m0=[],w5=!1,jK=null,PK=()=>g2(Z3,"usage-patterns.json"),AK=()=>g2(Z3,"insights.json");function DK($,Z){if(Z3=g2($,"docs-engine"),X2=g2(MO(),".config","smolerclaw","materials","manual"),jK=Z||null,!Y3(Z3))FK(Z3,{recursive:!0});if(!Y3(X2))FK(X2,{recursive:!0});xO(),hO(),gO(),p0={events:[],sessionStart:Date.now()},w5=!0}function NY($){if(!w5)return;let Z={...$,timestamp:Date.now()},Y=[...p0.events,Z].slice(-FO);p0={...p0,events:Y},PO(Z),setImmediate(()=>AO(Z))}function PO($){let Z=`${$.type}:${$.name}`,Y=h2.get(Z);if(Y){let Q=Y.count+1,z=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;h2.set(Z,{action:Z,count:Q,avgDurationMs:z,lastUsed:$.timestamp})}else h2.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function AO($){let Z=p0.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:z}]of Object.entries(jO))if(Q.test(Z)){if(!k1.find((X)=>X.type==="inefficient_pattern"&&X.relatedActions.includes($.name)&&Date.now()-new Date(X.createdAt).getTime()<3600000)){let X={id:m2(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:z,relatedActions:p0.events.slice(-5).map((K)=>K.name),confidence:0.8,createdAt:new Date().toISOString()};TK(X)}}}async function k5(){if(!w5)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=DO();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=TO();$.insightsGenerated+=Y.length;let Q=IO();$.insightsGenerated+=Q.length;for(let z of[...Z,...Y,...Q])if(TK(z),await wO(z))$.manualUpdates++;return vO(),_O(),p0={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
289
+ `),$}function DO(){let $=[],Z=SO(p0.events);for(let Y of Z)if(Y.count>=RK){let Q={id:m2(),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 TO(){let $=[],Z=new Set;for(let Y of p0.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(RO)){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>=LO){let K={id:m2(),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 IO(){let $=[];if(Date.now()-p0.sessionStart>1800000&&!p0.events.some((Q)=>Q.name==="save_memo"))$.push({id:m2(),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=p0.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!p0.events.some((Q)=>Q.name.includes("workflow")))$.push({id:m2(),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 SO($){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>=RK)}function TK($){if(!k1.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))k1=[...k1,$],jK?.($)}function IK($=5){return[...k1].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function wO($){try{let Z=bO($.type),Y=`${$.id}.md`,Q=g2(X2,Y),z=m0.find((V)=>V.id===$.id),J=z?z.version+1:1,X={id:$.id,title:$.title,category:Z,content:fO($),tags:yO($),source:"auto_generated",version:J,createdAt:z?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},K=fK(X);return LK(Q,K,"utf-8"),m0=m0.filter((V)=>V.id!==X.id),m0=[...m0,X],!0}catch{return!1}}async function SK($,Z,Y="best_practice",Q=[]){if(!w5)return{success:!1,path:""};try{let z=m2(),J=`${pO($)}-${z.slice(0,4)}.md`,X=g2(X2,J),K={id:z,title:$,category:Y,content:Z,tags:Q,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},V=fK(K);return LK(X,V,"utf-8"),m0=[...m0,K],{success:!0,path:X,entry:K}}catch{return{success:!1,path:""}}}function kO($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return m0.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 wK($){let Z=$?kO($):m0;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=kK[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(`
290
+ `)});return["# Manual de Uso Otimizado","",`Baseado em ${m0.length} entradas do manual vivo.`,"",...Y].join(`
291
+ `)}var kK={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function fO($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
292
+ `)}function fK($){let Z=kK[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
290
293
  Tags: ${$.tags.map((Y)=>`#${Y}`).join(" ")}`:""].filter(Boolean).join(`
291
- `)}function OO($){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 CO($){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 LK($){return $.summary}function RK($){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(`
294
+ `)}function bO($){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 yO($){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 bK($){return $.summary}function yK($){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(`
292
295
  `)});return`Insights (${$.length}):
293
296
 
294
297
  ${Z.join(`
295
298
 
296
- `)}`}function MO(){if(!I5)return;let $=Object.fromEntries(x2);P(UK(),JSON.stringify($,null,2))}function EO(){let $=UK();if(!$3($)){x2=new Map;return}try{let Z=JSON.parse(GY($,"utf-8"));x2=new Map(Object.entries(Z))}catch{x2=new Map}}function FO(){if(!I5)return;P(qK(),JSON.stringify(w1,null,2))}function LO(){let $=qK();if(!$3($)){w1=[];return}try{let Z=JSON.parse(GY($,"utf-8"));w1=Array.isArray(Z)?Z:[]}catch{w1=[]}}function RO(){if(!$3(z2)){h0=[];return}try{let $=$O(z2,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=_2(z2,Y.name),z=GY(Q,"utf-8"),J=jO(Y.name,z);if(J)Z.push(J)}h0=Z}catch{h0=[]}}function jO($,Z){try{let Y=Z.split(`
297
- `),Q=Y[0]?.replace(/^#\s*/,"")||$.replace(".md",""),z="best_practice",J=1,X=[];for(let W of Y.slice(1,6)){if(W.startsWith("> Categoria:")){let U=W.replace("> Categoria:","").trim().toLowerCase();if(U==="workflow"||U==="tool"||U==="shortcut"||U==="best_practice")z=U}if(W.startsWith("> Versao:"))J=parseInt(W.replace("> Versao:","").trim())||1}let V=Y.slice(-3).join(`
298
- `).match(/Tags:\s*(.+)/);if(V){let U=V[1].match(/#[\w-]+/g);if(U)X.push(...U.map((q)=>q.slice(1)))}let G=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:G?G[1]:h2(),title:Q,category:z,content:Y.slice(5).join(`
299
- `).trim(),tags:X,source:"auto_generated",version:J,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function h2(){return YO("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function PO($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}J2();var BY=($,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 V,G=!1,H;if($[K])H=$[K][0][0],Q.req.routeIndex=K;else H=K===$.length&&z||void 0;if(H)try{V=await H(Q,()=>X(K+1))}catch(W){if(W instanceof Error&&Z)Q.error=W,V=await Z(W,Q),G=!0;else throw W}else if(Q.finalized===!1&&Y)V=await Y(Q);if(V&&(Q.finalized===!1||G))Q.res=V;return Q}}};var PK=Symbol();var AK=async($,Z=Object.create(null))=>{let{all:Y=!1,dot:Q=!1}=Z,J=($ instanceof Y9?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return IO($,{all:Y,dot:Q});return{}};async function IO($,Z){let Y=await $.formData();if(Y)return wO(Y,Z);return{}}function wO($,Z){let Y=Object.create(null);if($.forEach((Q,z)=>{if(!(Z.all||z.endsWith("[]")))Y[z]=Q;else SO(Y,z,Q)}),Z.dot)Object.entries(Y).forEach(([Q,z])=>{if(Q.includes("."))kO(Y,Q,z),delete Y[Q]});return Y}var SO=($,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]},kO=($,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 OY=($)=>{let Z=$.split("/");if(Z[0]==="")Z.shift();return Z},DK=($)=>{let{groups:Z,path:Y}=fO($),Q=OY(Y);return bO(Q,Z)},fO=($)=>{let Z=[];return $=$.replace(/\{[^}]+\}/g,(Y,Q)=>{let z=`@${Q}`;return Z.push([z,Y]),z}),{groups:Z,path:$}},bO=($,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 $},Q9={},TK=($,Z)=>{if($==="*")return"*";let Y=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let Q=`${$}#${Z}`;if(!Q9[Q])if(Y[2])Q9[Q]=Z&&Z[0]!==":"&&Z[0]!=="*"?[Q,Y[1],new RegExp(`^${Y[2]}(?=/${Z})`)]:[$,Y[1],new RegExp(`^${Y[2]}$`)];else Q9[Q]=[$,Y[1],!0];return Q9[Q]}return null},z9=($,Z)=>{try{return Z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return Z(Y)}catch{return Y}})}},CY=($)=>z9($,decodeURI),MY=($)=>{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),V=Z.slice(Y,K);return CY(V.includes("%25")?V.replace(/%25/g,"%2525"):V)}else if(z===63||z===35)break}return Z.slice(Y,Q)};var IK=($)=>{let Z=MY($);return Z.length>1&&Z.at(-1)==="/"?Z.slice(0,-1):Z},u2=($,Z,...Y)=>{if(Y.length)Z=u2(Z,...Y);return`${$?.[0]==="/"?"":"/"}${$}${Z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${Z?.[0]==="/"?Z.slice(1):Z}`}`},J9=($)=>{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)},NY=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?z9($,EY):$},wK=($,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 V=X+Z.length+2,G=$.indexOf("&",V);return NY($.slice(V,G===-1?void 0:G))}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 V=$.slice(J+1,K===-1?X===-1?void 0:X:K);if(Q)V=NY(V);if(J=X,V==="")continue;let G;if(K===-1)G="";else if(G=$.slice(K+1,X===-1?void 0:X),Q)G=NY(G);if(Y){if(!(z[V]&&Array.isArray(z[V])))z[V]=[];z[V].push(G)}else z[V]??=G}return Z?z[Z]:z},SK=wK,kK=($,Z)=>{return wK($,Z,!0)},EY=decodeURIComponent;var fK=($)=>z9($,EY),Y9=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)?fK(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)?fK(Q):Q}return $}#z($){return this.#Z[1]?this.#Z[1][$]:$}query($){return SK(this.url,$)}queries($){return kK(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 AK(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[PK](){return this.#Z}get matchedRoutes(){return this.#Z[0].map(([[,$]])=>$)}get routePath(){return this.#Z[0].map(([[,$]])=>$)[this.routeIndex].path}};var bK={Stringify:1,BeforeStream:2,Stream:3},yK=($,Z)=>{let Y=new String($);return Y.isEscaped=!0,Y.callbacks=Z,Y};var FY=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((V)=>FY(V,Z,!1,Q,z))).then(()=>z[0]));if(Y)return yK(await X,J);else return X};var yO="text/plain; charset=UTF-8",LY=($,Z)=>{return{"Content-Type":$,...Z}},Y3=($,Z)=>new Response($,Z),vK=class{#$;#Z;env={};#Y;finalized=!1;error;#J;#z;#Q;#H;#V;#G;#K;#W;#U;constructor($,Z){if(this.#$=$,Z)this.#z=Z.executionCtx,this.env=Z.env,this.#G=Z.notFoundHandler,this.#U=Z.path,this.#W=Z.matchResult}get req(){return this.#Z??=new Y9(this.#$,this.#U,this.#W),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||=Y3(null,{headers:this.#K??=new Headers})}set res($){if(this.#Q&&$){$=Y3($.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.#V??=(Z)=>this.html(Z),this.#V(...$)};setLayout=($)=>this.#H=$;getLayout=()=>this.#H;setRenderer=($)=>{this.#V=$};header=($,Z,Y)=>{if(this.finalized)this.#Q=Y3(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 Y3($,{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,LY(yO,Y))};json=($,Z,Y)=>{return this.#X(JSON.stringify($),Z,LY("application/json",Y))};html=($,Z,Y)=>{let Q=(z)=>this.#X(z,Z,LY("text/html; charset=UTF-8",Y));return typeof $==="object"?FY($,bK.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.#G??=()=>Y3(),this.#G(this)}};var p="ALL",xK="all",_K=["get","post","put","delete","options","patch"],X9="Can not add a route since the matcher is already built.",K9=class extends Error{};var RY="__COMPOSED_HANDLER";var vO=($)=>{return $.text("404 Not Found",404)},hK=($,Z)=>{if("getResponse"in $){let Y=$.getResponse();return Z.newResponse(Y.body,Y)}return console.error($),Z.text("Internal Server Error",500)},gK=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[..._K,xK].forEach((J)=>{this[J]=(X,...K)=>{if(typeof X==="string")this.#$=X;else this.#J(J,this.#$,X);return K.forEach((V)=>{this.#J(J,this.#$,V)}),this}}),this.on=(J,X,...K)=>{for(let V of[X].flat()){this.#$=V;for(let G of[J].flat())K.map((H)=>{this.#J(G.toUpperCase(),this.#$,H)})}return this},this.use=(J,...X)=>{if(typeof J==="string")this.#$=J;else this.#$="*",X.unshift(J);return X.forEach((K)=>{this.#J(p,this.#$,K)}),this};let{strict:Q,...z}=Z;Object.assign(this,z),this.getPath=Q??!0?Z.getPath??MY:IK}#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=hK;route(Z,Y){let Q=this.basePath(Z);return Y.routes.map((z)=>{let J;if(Y.errorHandler===hK)J=z.handler;else J=async(X,K)=>(await BY([],Y.errorHandler)(X,()=>z.handler(X,K))).res,J[RY]=z.handler;Q.#J(z.method,z.path,J)}),this}basePath(Z){let Y=this.#Z();return Y._basePath=u2(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=(V)=>V;else z=Q.replaceRequest;let X=J?(V)=>{let G=J(V);return Array.isArray(G)?G:[G]}:(V)=>{let G=void 0;try{G=V.executionCtx}catch{}return[V.env,G]};z||=(()=>{let V=u2(this._basePath,Z),G=V==="/"?0:V.length;return(H)=>{let W=new URL(H.url);return W.pathname=W.pathname.slice(G)||"/",new Request(W,H)}})();let K=async(V,G)=>{let H=await Y(z(V.req.raw),...X(V));if(H)return H;await G()};return this.#J(p,u2(Z,"*"),K),this}#J(Z,Y,Q){Z=Z.toUpperCase(),Y=u2(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 vK(Z,{path:J,matchResult:X,env:Q,executionCtx:Y,notFoundHandler:this.#Y});if(X[0].length===1){let G;try{G=X[0][0][0][0](K,async()=>{K.res=await this.#Y(K)})}catch(H){return this.#z(H,K)}return G instanceof Promise?G.then((H)=>H||(K.finalized?K.res:this.#Y(K))).catch((H)=>this.#z(H,K)):G??this.#Y(K)}let V=BY(X[0],this.errorHandler,this.#Y);return(async()=>{try{let G=await V(K);if(!G.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return G.res}catch(G){return this.#z(G,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${u2("/",Z)}`,Y),Q,z)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#Q(Z.request,Z,void 0,Z.request.method))})}};var Q3=[];function V9($,Z){let Y=this.buildAllMatchers(),Q=(z,J)=>{let X=Y[z]||Y[p],K=X[2][J];if(K)return K;let V=J.match(X[0]);if(!V)return[[],Q3];let G=V.indexOf("",1);return[X[1][G],V]};return this.match=Q,Q($,Z)}var G9="[^/]+",z3=".*",J3="(?:|/.*)",d2=Symbol(),xO=new Set(".\\+*[^]$()");function _O($,Z){if($.length===1)return Z.length===1?$<Z?-1:1:-1;if(Z.length===1)return 1;if($===z3||$===J3)return 1;else if(Z===z3||Z===J3)return-1;if($===G9)return 1;else if(Z===G9)return-1;return $.length===Z.length?$<Z?-1:1:Z.length-$.length}var mK=class ${#$;#Z;#Y=Object.create(null);insert(Z,Y,Q,z,J){if(Z.length===0){if(this.#$!==void 0)throw d2;if(J)return;this.#$=Y;return}let[X,...K]=Z,V=X==="*"?K.length===0?["","",z3]:["","",G9]:X==="/*"?["","",J3]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),G;if(V){let H=V[1],W=V[2]||G9;if(H&&V[2]){if(W===".*")throw d2;if(W=W.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(W))throw d2}if(G=this.#Y[W],!G){if(Object.keys(this.#Y).some((U)=>U!==z3&&U!==J3))throw d2;if(J)return;if(G=this.#Y[W]=new $,H!=="")G.#Z=z.varIndex++}if(!J&&H!=="")Q.push([H,G.#Z])}else if(G=this.#Y[X],!G){if(Object.keys(this.#Y).some((H)=>H.length>1&&H!==z3&&H!==J3))throw d2;if(J)return;G=this.#Y[X]=new $}G.insert(K,Y,Q,z,J)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(_O).map((Q)=>{let z=this.#Y[Q];return(typeof z.#Z==="number"?`(${Q})@${z.#Z}`:xO.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 pK=class{#$={varIndex:0};#Z=new mK;insert($,Z,Y){let Q=[],z=[];for(let X=0;;){let K=!1;if($=$.replace(/\{[^}]+\}/g,(V)=>{let G=`@\\${X}`;return z[X]=[G,V],X++,K=!0,G}),!K)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let X=z.length-1;X>=0;X--){let[K]=z[X];for(let V=J.length-1;V>=0;V--)if(J[V].indexOf(K)!==-1){J[V]=J[V].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)],uK=Object.create(null);function dK($){return uK[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function gO(){uK=Object.create(null)}function mO($){let Z=new pK,Y=[];if($.length===0)return hO;let Q=$.map((G)=>[!/\*|\/:/.test(G[0]),...G]).sort(([G,H],[W,U])=>G?1:W?-1:H.length-U.length),z=Object.create(null);for(let G=0,H=-1,W=Q.length;G<W;G++){let[U,q,N]=Q[G];if(U)z[q]=[N.map(([M])=>[M,Object.create(null)]),Q3];else H++;let C;try{C=Z.insert(q,H,U)}catch(M){throw M===d2?new K9(q):M}if(U)continue;Y[H]=N.map(([M,F])=>{let T=Object.create(null);F-=1;for(;F>=0;F--){let[v,D]=C[F];T[v]=D}return[M,T]})}let[J,X,K]=Z.buildRegExp();for(let G=0,H=Y.length;G<H;G++)for(let W=0,U=Y[G].length;W<U;W++){let q=Y[G][W]?.[1];if(!q)continue;let N=Object.keys(q);for(let C=0,M=N.length;C<M;C++)q[N[C]]=K[q[N[C]]]}let V=[];for(let G in X)V[G]=Y[X[G]];return[J,V,z]}function S5($,Z){if(!$)return;for(let Y of Object.keys($).sort((Q,z)=>z.length-Q.length))if(dK(Y).test(Z))return[...$[Y]];return}var H9=class{name="RegExpRouter";#$;#Z;constructor(){this.#$={[p]:Object.create(null)},this.#Z={[p]:Object.create(null)}}add($,Z,Y){let Q=this.#$,z=this.#Z;if(!Q||!z)throw Error(X9);if(!Q[$])[Q,z].forEach((K)=>{K[$]=Object.create(null),Object.keys(K[p]).forEach((V)=>{K[$][V]=[...K[p][V]]})});if(Z==="/*")Z="*";let J=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let K=dK(Z);if($===p)Object.keys(Q).forEach((V)=>{Q[V][Z]||=S5(Q[V],Z)||S5(Q[p],Z)||[]});else Q[$][Z]||=S5(Q[$],Z)||S5(Q[p],Z)||[];Object.keys(Q).forEach((V)=>{if($===p||$===V)Object.keys(Q[V]).forEach((G)=>{K.test(G)&&Q[V][G].push([Y,J])})}),Object.keys(z).forEach((V)=>{if($===p||$===V)Object.keys(z[V]).forEach((G)=>K.test(G)&&z[V][G].push([Y,J]))});return}let X=J9(Z)||[Z];for(let K=0,V=X.length;K<V;K++){let G=X[K];Object.keys(z).forEach((H)=>{if($===p||$===H)z[H][G]||=[...S5(Q[H],G)||S5(Q[p],G)||[]],z[H][G].push([Y,J-V+K+1])})}}match=V9;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,gO(),$}#Y($){let Z=[],Y=$===p;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($!==p)Z.push(...Object.keys(Q[p]).map((J)=>[J,Q[p][J]]))}),!Y)return null;else return mO(Z)}};var pO=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.#$[p],J={};for(let X in z[2])J[X]=[z[2][X][0].slice(),Q3];this.#$[$]=[z[0],z[1].map((X)=>Array.isArray(X)?X.slice():0),J]}if(Z==="/*"||Z==="*"){let z=[Y,{}];if($===p)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($===p)for(let X in this.#$)this.#J(X,Z,Y,z,J);else this.#J($,Z,Y,z,J)}buildAllMatchers(){return this.#$}match=V9};var jY=class{name="SmartRouter";#$=[];#Z=[];constructor($){this.#$=$.routers}add($,Z,Y){if(!this.#Z)throw Error(X9);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 V=0,G=Q.length;V<G;V++)K.add(...Q[V]);X=K.match($,Z)}catch(V){if(V instanceof K9)continue;throw V}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 X3=Object.create(null),uO=($)=>{for(let Z in $)return!0;return!1},cK=class ${#$;#Z;#Y;#J=0;#z=X3;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=DK(Y),X=[];for(let K=0,V=J.length;K<V;K++){let G=J[K],H=J[K+1],W=TK(G,H),U=Array.isArray(W)?W[0]:G;if(U in z.#Z){if(z=z.#Z[U],W)X.push(W[1]);continue}if(z.#Z[U]=new $,W)z.#Y.push(W),X.push(W[1]);z=z.#Z[U]}return z.#$.push({[Z]:{handler:Q,possibleKeys:X.filter((K,V,G)=>G.indexOf(K)===V),score:this.#J}}),z}#Q(Z,Y,Q,z,J){for(let X=0,K=Y.#$.length;X<K;X++){let V=Y.#$[X],G=V[Q]||V[p],H={};if(G!==void 0){if(G.params=Object.create(null),Z.push(G),z!==X3||J&&J!==X3)for(let W=0,U=G.possibleKeys.length;W<U;W++){let q=G.possibleKeys[W],N=H[G.score];G.params[q]=J?.[q]&&!N?J[q]:z[q]??J?.[q],H[G.score]=!0}}}}search(Z,Y){let Q=[];this.#z=X3;let J=[this],X=OY(Y),K=[],V=X.length,G=null;for(let H=0;H<V;H++){let W=X[H],U=H===V-1,q=[];for(let C=0,M=J.length;C<M;C++){let F=J[C],T=F.#Z[W];if(T)if(T.#z=F.#z,U){if(T.#Z["*"])this.#Q(Q,T.#Z["*"],Z,F.#z);this.#Q(Q,T,Z,F.#z)}else q.push(T);for(let v=0,D=F.#Y.length;v<D;v++){let x=F.#Y[v],c=F.#z===X3?{}:{...F.#z};if(x==="*"){let M0=F.#Z["*"];if(M0)this.#Q(Q,M0,Z,F.#z),M0.#z=c,q.push(M0);continue}let[V0,g,C0]=x;if(!W&&!(C0 instanceof RegExp))continue;let r=F.#Z[V0];if(C0 instanceof RegExp){if(G===null){G=Array(V);let k0=Y[0]==="/"?1:0;for(let P0=0;P0<V;P0++)G[P0]=k0,k0+=X[P0].length+1}let M0=Y.substring(G[H]),r0=C0.exec(M0);if(r0){if(c[g]=r0[0],this.#Q(Q,r,Z,F.#z,c),uO(r.#Z)){r.#z=c;let k0=r0[0].match(/\//)?.length??0;(K[k0]||=[]).push(r)}continue}}if(C0===!0||C0.test(W))if(c[g]=W,U){if(this.#Q(Q,r,Z,c,F.#z),r.#Z["*"])this.#Q(Q,r.#Z["*"],Z,c,F.#z)}else r.#z=c,q.push(r)}}let N=K.shift();J=N?q.concat(N):q}if(Q.length>1)Q.sort((H,W)=>{return H.score-W.score});return[Q.map(({handler:H,params:W})=>[H,W])]}};var PY=class{name="TrieRouter";#$;constructor(){this.#$=new cK}add($,Z,Y){let Q=J9(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 K3=class extends gK{constructor($={}){super($);this.router=$.router??new jY({routers:[new H9,new PY]})}};var W9=($)=>{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 V(H,W){X.res.headers.set(H,W)}let G=await Q(X.req.header("origin")||"",X);if(G)V("Access-Control-Allow-Origin",G);if(Y.credentials)V("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)V("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(X.req.method==="OPTIONS"){if(Y.origin!=="*"||Y.credentials)V("Vary","Origin");if(Y.maxAge!=null)V("Access-Control-Max-Age",Y.maxAge.toString());let H=await z(X.req.header("origin")||"",X);if(H.length)V("Access-Control-Allow-Methods",H.join(","));let W=Y.allowHeaders;if(!W?.length){let U=X.req.header("Access-Control-Request-Headers");if(U)W=U.split(/\s*,\s*/)}if(W?.length)V("Access-Control-Allow-Headers",W.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 V3(){return`<!DOCTYPE html>
299
+ `)}`}function vO(){if(!w5)return;let $=Object.fromEntries(h2);j(PK(),JSON.stringify($,null,2))}function xO(){let $=PK();if(!Y3($)){h2=new Map;return}try{let Z=JSON.parse(BY($,"utf-8"));h2=new Map(Object.entries(Z))}catch{h2=new Map}}function _O(){if(!w5)return;j(AK(),JSON.stringify(k1,null,2))}function hO(){let $=AK();if(!Y3($)){k1=[];return}try{let Z=JSON.parse(BY($,"utf-8"));k1=Array.isArray(Z)?Z:[]}catch{k1=[]}}function gO(){if(!Y3(X2)){m0=[];return}try{let $=CO(X2,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=g2(X2,Y.name),z=BY(Q,"utf-8"),J=mO(Y.name,z);if(J)Z.push(J)}m0=Z}catch{m0=[]}}function mO($,Z){try{let Y=Z.split(`
300
+ `),Q=Y[0]?.replace(/^#\s*/,"")||$.replace(".md",""),z="best_practice",J=1,X=[];for(let H of Y.slice(1,6)){if(H.startsWith("> Categoria:")){let U=H.replace("> Categoria:","").trim().toLowerCase();if(U==="workflow"||U==="tool"||U==="shortcut"||U==="best_practice")z=U}if(H.startsWith("> Versao:"))J=parseInt(H.replace("> Versao:","").trim())||1}let V=Y.slice(-3).join(`
301
+ `).match(/Tags:\s*(.+)/);if(V){let U=V[1].match(/#[\w-]+/g);if(U)X.push(...U.map((q)=>q.slice(1)))}let G=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:G?G[1]:m2(),title:Q,category:z,content:Y.slice(5).join(`
302
+ `).trim(),tags:X,source:"auto_generated",version:J,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function m2(){return EO("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function pO($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}K2();var EY=($,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 V,G=!1,W;if($[K])W=$[K][0][0],Q.req.routeIndex=K;else W=K===$.length&&z||void 0;if(W)try{V=await W(Q,()=>X(K+1))}catch(H){if(H instanceof Error&&Z)Q.error=H,V=await Z(H,Q),G=!0;else throw H}else if(Q.finalized===!1&&Y)V=await Y(Q);if(V&&(Q.finalized===!1||G))Q.res=V;return Q}}};var xK=Symbol();var _K=async($,Z=Object.create(null))=>{let{all:Y=!1,dot:Q=!1}=Z,J=($ instanceof X9?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return lO($,{all:Y,dot:Q});return{}};async function lO($,Z){let Y=await $.formData();if(Y)return oO(Y,Z);return{}}function oO($,Z){let Y=Object.create(null);if($.forEach((Q,z)=>{if(!(Z.all||z.endsWith("[]")))Y[z]=Q;else iO(Y,z,Q)}),Z.dot)Object.entries(Y).forEach(([Q,z])=>{if(Q.includes("."))nO(Y,Q,z),delete Y[Q]});return Y}var iO=($,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]},nO=($,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 LY=($)=>{let Z=$.split("/");if(Z[0]==="")Z.shift();return Z},hK=($)=>{let{groups:Z,path:Y}=rO($),Q=LY(Y);return aO(Q,Z)},rO=($)=>{let Z=[];return $=$.replace(/\{[^}]+\}/g,(Y,Q)=>{let z=`@${Q}`;return Z.push([z,Y]),z}),{groups:Z,path:$}},aO=($,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 $},K9={},gK=($,Z)=>{if($==="*")return"*";let Y=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let Q=`${$}#${Z}`;if(!K9[Q])if(Y[2])K9[Q]=Z&&Z[0]!==":"&&Z[0]!=="*"?[Q,Y[1],new RegExp(`^${Y[2]}(?=/${Z})`)]:[$,Y[1],new RegExp(`^${Y[2]}$`)];else K9[Q]=[$,Y[1],!0];return K9[Q]}return null},V9=($,Z)=>{try{return Z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return Z(Y)}catch{return Y}})}},RY=($)=>V9($,decodeURI),jY=($)=>{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),V=Z.slice(Y,K);return RY(V.includes("%25")?V.replace(/%25/g,"%2525"):V)}else if(z===63||z===35)break}return Z.slice(Y,Q)};var mK=($)=>{let Z=jY($);return Z.length>1&&Z.at(-1)==="/"?Z.slice(0,-1):Z},c2=($,Z,...Y)=>{if(Y.length)Z=c2(Z,...Y);return`${$?.[0]==="/"?"":"/"}${$}${Z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${Z?.[0]==="/"?Z.slice(1):Z}`}`},G9=($)=>{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)},FY=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?V9($,PY):$},pK=($,Z,Y)=>{let Q;if(!Y&&Z&&!/[%+]/.test(Z)){let X=$.indexOf("?",8);if(X===-1)return;if(!$.startsWith(Z,X+1))X=$.indexOf(`&${Z}`,X+1);while(X!==-1){let K=$.charCodeAt(X+Z.length+1);if(K===61){let V=X+Z.length+2,G=$.indexOf("&",V);return FY($.slice(V,G===-1?void 0:G))}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 V=$.slice(J+1,K===-1?X===-1?void 0:X:K);if(Q)V=FY(V);if(J=X,V==="")continue;let G;if(K===-1)G="";else if(G=$.slice(K+1,X===-1?void 0:X),Q)G=FY(G);if(Y){if(!(z[V]&&Array.isArray(z[V])))z[V]=[];z[V].push(G)}else z[V]??=G}return Z?z[Z]:z},uK=pK,dK=($,Z)=>{return pK($,Z,!0)},PY=decodeURIComponent;var cK=($)=>V9($,PY),X9=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)?cK(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)?cK(Q):Q}return $}#z($){return this.#Z[1]?this.#Z[1][$]:$}query($){return uK(this.url,$)}queries($){return dK(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[xK](){return this.#Z}get matchedRoutes(){return this.#Z[0].map(([[,$]])=>$)}get routePath(){return this.#Z[0].map(([[,$]])=>$)[this.routeIndex].path}};var lK={Stringify:1,BeforeStream:2,Stream:3},oK=($,Z)=>{let Y=new String($);return Y.isEscaped=!0,Y.callbacks=Z,Y};var AY=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((V)=>AY(V,Z,!1,Q,z))).then(()=>z[0]));if(Y)return oK(await X,J);else return X};var sO="text/plain; charset=UTF-8",DY=($,Z)=>{return{"Content-Type":$,...Z}},z3=($,Z)=>new Response($,Z),iK=class{#$;#Z;env={};#Y;finalized=!1;error;#J;#z;#Q;#W;#V;#G;#K;#H;#U;constructor($,Z){if(this.#$=$,Z)this.#z=Z.executionCtx,this.env=Z.env,this.#G=Z.notFoundHandler,this.#U=Z.path,this.#H=Z.matchResult}get req(){return this.#Z??=new X9(this.#$,this.#U,this.#H),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||=z3(null,{headers:this.#K??=new Headers})}set res($){if(this.#Q&&$){$=z3($.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.#V??=(Z)=>this.html(Z),this.#V(...$)};setLayout=($)=>this.#W=$;getLayout=()=>this.#W;setRenderer=($)=>{this.#V=$};header=($,Z,Y)=>{if(this.finalized)this.#Q=z3(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 z3($,{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,DY(sO,Y))};json=($,Z,Y)=>{return this.#X(JSON.stringify($),Z,DY("application/json",Y))};html=($,Z,Y)=>{let Q=(z)=>this.#X(z,Z,DY("text/html; charset=UTF-8",Y));return typeof $==="object"?AY($,lK.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.#G??=()=>z3(),this.#G(this)}};var u="ALL",nK="all",rK=["get","post","put","delete","options","patch"],W9="Can not add a route since the matcher is already built.",H9=class extends Error{};var TY="__COMPOSED_HANDLER";var tO=($)=>{return $.text("404 Not Found",404)},aK=($,Z)=>{if("getResponse"in $){let Y=$.getResponse();return Z.newResponse(Y.body,Y)}return console.error($),Z.text("Internal Server Error",500)},sK=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(Z={}){[...rK,nK].forEach((J)=>{this[J]=(X,...K)=>{if(typeof X==="string")this.#$=X;else this.#J(J,this.#$,X);return K.forEach((V)=>{this.#J(J,this.#$,V)}),this}}),this.on=(J,X,...K)=>{for(let V of[X].flat()){this.#$=V;for(let G of[J].flat())K.map((W)=>{this.#J(G.toUpperCase(),this.#$,W)})}return this},this.use=(J,...X)=>{if(typeof J==="string")this.#$=J;else this.#$="*",X.unshift(J);return X.forEach((K)=>{this.#J(u,this.#$,K)}),this};let{strict:Q,...z}=Z;Object.assign(this,z),this.getPath=Q??!0?Z.getPath??jY:mK}#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=tO;errorHandler=aK;route(Z,Y){let Q=this.basePath(Z);return Y.routes.map((z)=>{let J;if(Y.errorHandler===aK)J=z.handler;else J=async(X,K)=>(await EY([],Y.errorHandler)(X,()=>z.handler(X,K))).res,J[TY]=z.handler;Q.#J(z.method,z.path,J)}),this}basePath(Z){let Y=this.#Z();return Y._basePath=c2(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=(V)=>V;else z=Q.replaceRequest;let X=J?(V)=>{let G=J(V);return Array.isArray(G)?G:[G]}:(V)=>{let G=void 0;try{G=V.executionCtx}catch{}return[V.env,G]};z||=(()=>{let V=c2(this._basePath,Z),G=V==="/"?0:V.length;return(W)=>{let H=new URL(W.url);return H.pathname=H.pathname.slice(G)||"/",new Request(H,W)}})();let K=async(V,G)=>{let W=await Y(z(V.req.raw),...X(V));if(W)return W;await G()};return this.#J(u,c2(Z,"*"),K),this}#J(Z,Y,Q){Z=Z.toUpperCase(),Y=c2(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 iK(Z,{path:J,matchResult:X,env:Q,executionCtx:Y,notFoundHandler:this.#Y});if(X[0].length===1){let G;try{G=X[0][0][0][0](K,async()=>{K.res=await this.#Y(K)})}catch(W){return this.#z(W,K)}return G instanceof Promise?G.then((W)=>W||(K.finalized?K.res:this.#Y(K))).catch((W)=>this.#z(W,K)):G??this.#Y(K)}let V=EY(X[0],this.errorHandler,this.#Y);return(async()=>{try{let G=await V(K);if(!G.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return G.res}catch(G){return this.#z(G,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${c2("/",Z)}`,Y),Q,z)};fire=()=>{addEventListener("fetch",(Z)=>{Z.respondWith(this.#Q(Z.request,Z,void 0,Z.request.method))})}};var J3=[];function U9($,Z){let Y=this.buildAllMatchers(),Q=(z,J)=>{let X=Y[z]||Y[u],K=X[2][J];if(K)return K;let V=J.match(X[0]);if(!V)return[[],J3];let G=V.indexOf("",1);return[X[1][G],V]};return this.match=Q,Q($,Z)}var q9="[^/]+",X3=".*",K3="(?:|/.*)",l2=Symbol(),eO=new Set(".\\+*[^]$()");function $C($,Z){if($.length===1)return Z.length===1?$<Z?-1:1:-1;if(Z.length===1)return 1;if($===X3||$===K3)return 1;else if(Z===X3||Z===K3)return-1;if($===q9)return 1;else if(Z===q9)return-1;return $.length===Z.length?$<Z?-1:1:Z.length-$.length}var tK=class ${#$;#Z;#Y=Object.create(null);insert(Z,Y,Q,z,J){if(Z.length===0){if(this.#$!==void 0)throw l2;if(J)return;this.#$=Y;return}let[X,...K]=Z,V=X==="*"?K.length===0?["","",X3]:["","",q9]:X==="/*"?["","",K3]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),G;if(V){let W=V[1],H=V[2]||q9;if(W&&V[2]){if(H===".*")throw l2;if(H=H.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(H))throw l2}if(G=this.#Y[H],!G){if(Object.keys(this.#Y).some((U)=>U!==X3&&U!==K3))throw l2;if(J)return;if(G=this.#Y[H]=new $,W!=="")G.#Z=z.varIndex++}if(!J&&W!=="")Q.push([W,G.#Z])}else if(G=this.#Y[X],!G){if(Object.keys(this.#Y).some((W)=>W.length>1&&W!==X3&&W!==K3))throw l2;if(J)return;G=this.#Y[X]=new $}G.insert(K,Y,Q,z,J)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort($C).map((Q)=>{let z=this.#Y[Q];return(typeof z.#Z==="number"?`(${Q})@${z.#Z}`:eO.has(Q)?`\\${Q}`:Q)+z.buildRegExpStr()});if(typeof this.#$==="number")Y.unshift(`#${this.#$}`);if(Y.length===0)return"";if(Y.length===1)return Y[0];return"(?:"+Y.join("|")+")"}};var eK=class{#$={varIndex:0};#Z=new tK;insert($,Z,Y){let Q=[],z=[];for(let X=0;;){let K=!1;if($=$.replace(/\{[^}]+\}/g,(V)=>{let G=`@\\${X}`;return z[X]=[G,V],X++,K=!0,G}),!K)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let X=z.length-1;X>=0;X--){let[K]=z[X];for(let V=J.length-1;V>=0;V--)if(J[V].indexOf(K)!==-1){J[V]=J[V].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 ZC=[/^$/,[],Object.create(null)],$V=Object.create(null);function ZV($){return $V[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(Z,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function YC(){$V=Object.create(null)}function QC($){let Z=new eK,Y=[];if($.length===0)return ZC;let Q=$.map((G)=>[!/\*|\/:/.test(G[0]),...G]).sort(([G,W],[H,U])=>G?1:H?-1:W.length-U.length),z=Object.create(null);for(let G=0,W=-1,H=Q.length;G<H;G++){let[U,q,N]=Q[G];if(U)z[q]=[N.map(([M])=>[M,Object.create(null)]),J3];else W++;let C;try{C=Z.insert(q,W,U)}catch(M){throw M===l2?new H9(q):M}if(U)continue;Y[W]=N.map(([M,F])=>{let T=Object.create(null);F-=1;for(;F>=0;F--){let[v,D]=C[F];T[v]=D}return[M,T]})}let[J,X,K]=Z.buildRegExp();for(let G=0,W=Y.length;G<W;G++)for(let H=0,U=Y[G].length;H<U;H++){let q=Y[G][H]?.[1];if(!q)continue;let N=Object.keys(q);for(let C=0,M=N.length;C<M;C++)q[N[C]]=K[q[N[C]]]}let V=[];for(let G in X)V[G]=Y[X[G]];return[J,V,z]}function f5($,Z){if(!$)return;for(let Y of Object.keys($).sort((Q,z)=>z.length-Q.length))if(ZV(Y).test(Z))return[...$[Y]];return}var B9=class{name="RegExpRouter";#$;#Z;constructor(){this.#$={[u]:Object.create(null)},this.#Z={[u]:Object.create(null)}}add($,Z,Y){let Q=this.#$,z=this.#Z;if(!Q||!z)throw Error(W9);if(!Q[$])[Q,z].forEach((K)=>{K[$]=Object.create(null),Object.keys(K[u]).forEach((V)=>{K[$][V]=[...K[u][V]]})});if(Z==="/*")Z="*";let J=(Z.match(/\/:/g)||[]).length;if(/\*$/.test(Z)){let K=ZV(Z);if($===u)Object.keys(Q).forEach((V)=>{Q[V][Z]||=f5(Q[V],Z)||f5(Q[u],Z)||[]});else Q[$][Z]||=f5(Q[$],Z)||f5(Q[u],Z)||[];Object.keys(Q).forEach((V)=>{if($===u||$===V)Object.keys(Q[V]).forEach((G)=>{K.test(G)&&Q[V][G].push([Y,J])})}),Object.keys(z).forEach((V)=>{if($===u||$===V)Object.keys(z[V]).forEach((G)=>K.test(G)&&z[V][G].push([Y,J]))});return}let X=G9(Z)||[Z];for(let K=0,V=X.length;K<V;K++){let G=X[K];Object.keys(z).forEach((W)=>{if($===u||$===W)z[W][G]||=[...f5(Q[W],G)||f5(Q[u],G)||[]],z[W][G].push([Y,J-V+K+1])})}}match=U9;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,YC(),$}#Y($){let Z=[],Y=$===u;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($!==u)Z.push(...Object.keys(Q[u]).map((J)=>[J,Q[u][J]]))}),!Y)return null;else return QC(Z)}};var zC=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.#$[u],J={};for(let X in z[2])J[X]=[z[2][X][0].slice(),J3];this.#$[$]=[z[0],z[1].map((X)=>Array.isArray(X)?X.slice():0),J]}if(Z==="/*"||Z==="*"){let z=[Y,{}];if($===u)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($===u)for(let X in this.#$)this.#J(X,Z,Y,z,J);else this.#J($,Z,Y,z,J)}buildAllMatchers(){return this.#$}match=U9};var IY=class{name="SmartRouter";#$=[];#Z=[];constructor($){this.#$=$.routers}add($,Z,Y){if(!this.#Z)throw Error(W9);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 V=0,G=Q.length;V<G;V++)K.add(...Q[V]);X=K.match($,Z)}catch(V){if(V instanceof H9)continue;throw V}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 V3=Object.create(null),JC=($)=>{for(let Z in $)return!0;return!1},YV=class ${#$;#Z;#Y;#J=0;#z=V3;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=hK(Y),X=[];for(let K=0,V=J.length;K<V;K++){let G=J[K],W=J[K+1],H=gK(G,W),U=Array.isArray(H)?H[0]:G;if(U in z.#Z){if(z=z.#Z[U],H)X.push(H[1]);continue}if(z.#Z[U]=new $,H)z.#Y.push(H),X.push(H[1]);z=z.#Z[U]}return z.#$.push({[Z]:{handler:Q,possibleKeys:X.filter((K,V,G)=>G.indexOf(K)===V),score:this.#J}}),z}#Q(Z,Y,Q,z,J){for(let X=0,K=Y.#$.length;X<K;X++){let V=Y.#$[X],G=V[Q]||V[u],W={};if(G!==void 0){if(G.params=Object.create(null),Z.push(G),z!==V3||J&&J!==V3)for(let H=0,U=G.possibleKeys.length;H<U;H++){let q=G.possibleKeys[H],N=W[G.score];G.params[q]=J?.[q]&&!N?J[q]:z[q]??J?.[q],W[G.score]=!0}}}}search(Z,Y){let Q=[];this.#z=V3;let J=[this],X=LY(Y),K=[],V=X.length,G=null;for(let W=0;W<V;W++){let H=X[W],U=W===V-1,q=[];for(let C=0,M=J.length;C<M;C++){let F=J[C],T=F.#Z[H];if(T)if(T.#z=F.#z,U){if(T.#Z["*"])this.#Q(Q,T.#Z["*"],Z,F.#z);this.#Q(Q,T,Z,F.#z)}else q.push(T);for(let v=0,D=F.#Y.length;v<D;v++){let x=F.#Y[v],l=F.#z===V3?{}:{...F.#z};if(x==="*"){let E0=F.#Z["*"];if(E0)this.#Q(Q,E0,Z,F.#z),E0.#z=l,q.push(E0);continue}let[G0,m,M0]=x;if(!H&&!(M0 instanceof RegExp))continue;let a=F.#Z[G0];if(M0 instanceof RegExp){if(G===null){G=Array(V);let b0=Y[0]==="/"?1:0;for(let A0=0;A0<V;A0++)G[A0]=b0,b0+=X[A0].length+1}let E0=Y.substring(G[W]),s0=M0.exec(E0);if(s0){if(l[m]=s0[0],this.#Q(Q,a,Z,F.#z,l),JC(a.#Z)){a.#z=l;let b0=s0[0].match(/\//)?.length??0;(K[b0]||=[]).push(a)}continue}}if(M0===!0||M0.test(H))if(l[m]=H,U){if(this.#Q(Q,a,Z,l,F.#z),a.#Z["*"])this.#Q(Q,a.#Z["*"],Z,l,F.#z)}else a.#z=l,q.push(a)}}let N=K.shift();J=N?q.concat(N):q}if(Q.length>1)Q.sort((W,H)=>{return W.score-H.score});return[Q.map(({handler:W,params:H})=>[W,H])]}};var SY=class{name="TrieRouter";#$;constructor(){this.#$=new YV}add($,Z,Y){let Q=G9(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 G3=class extends sK{constructor($={}){super($);this.router=$.router??new IY({routers:[new B9,new SY]})}};var N9=($)=>{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 V(W,H){X.res.headers.set(W,H)}let G=await Q(X.req.header("origin")||"",X);if(G)V("Access-Control-Allow-Origin",G);if(Y.credentials)V("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)V("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(X.req.method==="OPTIONS"){if(Y.origin!=="*"||Y.credentials)V("Vary","Origin");if(Y.maxAge!=null)V("Access-Control-Max-Age",Y.maxAge.toString());let W=await z(X.req.header("origin")||"",X);if(W.length)V("Access-Control-Allow-Methods",W.join(","));let H=Y.allowHeaders;if(!H?.length){let U=X.req.header("Access-Control-Request-Headers");if(U)H=U.split(/\s*,\s*/)}if(H?.length)V("Access-Control-Allow-Headers",H.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 W3(){return`<!DOCTYPE html>
300
303
  <html lang="pt-BR">
301
304
  <head>
302
305
  <meta charset="UTF-8">
@@ -1023,13 +1026,13 @@ ${Z.join(`
1023
1026
  })();
1024
1027
  </script>
1025
1028
  </body>
1026
- </html>`}h();import{existsSync as AY,mkdirSync as dO,readFileSync as cO}from"fs";import{join as lO}from"path";import{randomUUID as G3}from"crypto";var DY="",b=[],TY=()=>lO(DY,"neighborhoods.json");function X2(){P(TY(),JSON.stringify(b,null,2))}function lK(){let $=TY();if(!AY($)){b=[];return}try{b=JSON.parse(cO($,"utf-8"))}catch{b=[]}}function oK($){if(DY=$,!AY($))dO($,{recursive:!0});lK()}async function oO($){let Z=`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent($)}&format=json&limit=1&polygon_geojson=1`;try{let Q=await(await fetch(Z,{headers:{"User-Agent":"smolerclaw/1.7.0"}})).json();if(!Q.length)return null;let z=Q[0];return{lat:parseFloat(z.lat),lng:parseFloat(z.lon),displayName:z.display_name,boundingBox:z.boundingbox.map(Number)}}catch{return null}}async function iO($){let Z=`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent($)}&format=json&limit=1&polygon_geojson=1`;try{let Q=await(await fetch(Z,{headers:{"User-Agent":"smolerclaw/1.7.0"}})).json();if(!Q.length||!Q[0].geojson)return null;let z=Q[0].geojson;if(z.type==="Polygon"||z.type==="MultiPolygon")return z;return null}catch{return null}}var nO=[{category:"escola",osmTag:'"amenity"="school"'},{category:"hospital",osmTag:'"amenity"="hospital"'},{category:"posto de saude",osmTag:'"amenity"="clinic"'},{category:"farmacia",osmTag:'"amenity"="pharmacy"'},{category:"delegacia",osmTag:'"amenity"="police"'},{category:"bombeiros",osmTag:'"amenity"="fire_station"'},{category:"supermercado",osmTag:'"shop"="supermarket"'},{category:"estacao de trem",osmTag:'"railway"="station"'},{category:"ponto de onibus",osmTag:'"highway"="bus_stop"'},{category:"parque",osmTag:'"leisure"="park"'},{category:"igreja",osmTag:'"amenity"="place_of_worship"'},{category:"banco",osmTag:'"amenity"="bank"'}];async function rO($,Z,Y=2000){let Q=[],J=`[out:json][timeout:15];(${nO.map((K)=>`node[${K.osmTag}](around:${Y},${$},${Z});way[${K.osmTag}](around:${Y},${$},${Z});`).join("")});out center 100;`,X=`https://overpass-api.de/api/interpreter?data=${encodeURIComponent(J)}`;try{let V=await(await fetch(X,{headers:{"User-Agent":"smolerclaw/1.7.0"}})).json();if(!V.elements)return Q;for(let G of V.elements){let H=G.lat??G.center?.lat,W=G.lon??G.center?.lon;if(!H||!W)continue;let U=G.tags?.name||G.tags?.["name:pt"]||"";if(!U)continue;let q=aO(G.tags??{});Q.push({id:G3().slice(0,8),name:U,category:q,position:{lat:H,lng:W},tags:sO(G.tags??{}),metadata:{source:"openstreetmap",osmType:G.type,...tO(G.tags??{})},createdAt:new Date().toISOString()})}}catch{}return Q}function aO($){if($.amenity==="school")return"escola";if($.amenity==="hospital")return"hospital";if($.amenity==="clinic")return"posto de saude";if($.amenity==="pharmacy")return"farmacia";if($.amenity==="police")return"delegacia";if($.amenity==="fire_station")return"bombeiros";if($.amenity==="bank")return"banco";if($.amenity==="place_of_worship")return"igreja";if($.shop==="supermarket")return"supermercado";if($.railway==="station")return"estacao de trem";if($.highway==="bus_stop")return"ponto de onibus";if($.leisure==="park")return"parque";return $.amenity||$.shop||$.leisure||"outro"}function sO($){let Z=[];if($.amenity)Z.push($.amenity);if($.shop)Z.push($.shop);if($.leisure)Z.push($.leisure);if($.healthcare)Z.push($.healthcare);if($.railway)Z.push($.railway);return Z}function tO($){let Z=["addr:street","addr:housenumber","phone","website","opening_hours","operator"],Y={};for(let Q of Z)if($[Q])Y[Q]=$[Q];return Y}async function iK($,Z,Y,Q="Brazil",z=[],J=!0){let X=`${$}, ${Z}, ${Y}, ${Q}`,K=await oO(X),V=await iO(X),G=new Date().toISOString(),H={id:G3().slice(0,8),name:$,city:Z,state:Y,country:Q,center:K?{lat:K.lat,lng:K.lng}:{lat:0,lng:0},boundary:V,pois:[],layers:[],tags:z.map((W)=>W.toLowerCase()),metadata:K?{displayName:K.displayName,boundingBox:K.boundingBox}:{},createdAt:G,updatedAt:G};if(J&&K){let W=await rO(K.lat,K.lng,3000);if(H.pois=W,W.length>0){let U=new Map;for(let q of W){let N=U.get(q.category)??[];U.set(q.category,[...N,q])}H.layers=[{id:G3().slice(0,8),name:"Infraestrutura",type:"scatter",color:"#00e5cc",opacity:0.8,visible:!0,points:W.map((q)=>({lat:q.position.lat,lng:q.position.lng,value:1,label:`${q.name} (${q.category})`}))}],H.metadata={...H.metadata,enrichedAt:G,poiBreakdown:Object.fromEntries([...U.entries()].map(([q,N])=>[q,N.length]))}}}return b=[...b,H],X2(),V7([Y]),H}function k1($){return b.find((Z)=>Z.id===$||Z.name.toLowerCase()===$.toLowerCase())??null}function t0(){if(!b.length&&DY&&AY(TY()))lK();return b}function nK($){let Z=b.length;if(b=b.filter((Y)=>Y.id!==$&&Y.name.toLowerCase()!==$.toLowerCase()),b.length<Z)return X2(),!0;return!1}function rK($){let Z=$.toLowerCase();return b.map((Y)=>{let Q=0;if(Y.name.toLowerCase().includes(Z))Q+=10;if(Y.city.toLowerCase().includes(Z))Q+=5;if(Y.tags.some((z)=>z.includes(Z)))Q+=3;if(Y.pois.some((z)=>z.name.toLowerCase().includes(Z)))Q+=2;return{neighborhood:Y,score:Q}}).filter((Y)=>Y.score>0).sort((Y,Q)=>Q.score-Y.score)}function aK($,Z,Y,Q,z,J=[],X={}){let K=b.find((H)=>H.id===$||H.name.toLowerCase()===$.toLowerCase());if(!K)return null;let V={id:G3().slice(0,8),name:Z,category:Y,position:{lat:Q,lng:z},tags:J.map((H)=>H.toLowerCase()),metadata:X,createdAt:new Date().toISOString()},G={...K,pois:[...K.pois,V],updatedAt:new Date().toISOString()};return b=b.map((H)=>H.id===K.id?G:H),X2(),V}function sK($,Z){let Y=b.find((J)=>J.id===$||J.name.toLowerCase()===$.toLowerCase());if(!Y)return!1;let Q=Y.pois.length,z={...Y,pois:Y.pois.filter((J)=>J.id!==Z),updatedAt:new Date().toISOString()};if(z.pois.length===Q)return!1;return b=b.map((J)=>J.id===Y.id?z:J),X2(),!0}function tK($,Z,Y,Q="#00ffcc",z=[]){let J=b.find((V)=>V.id===$||V.name.toLowerCase()===$.toLowerCase());if(!J)return null;let X={id:G3().slice(0,8),name:Z,type:Y,color:Q,opacity:0.7,visible:!0,points:z},K={...J,layers:[...J.layers,X],updatedAt:new Date().toISOString()};return b=b.map((V)=>V.id===J.id?K:V),X2(),X}function eK($,Z,Y){let Q=b.find((K)=>K.id===$||K.name.toLowerCase()===$.toLowerCase());if(!Q)return!1;let z=Q.layers.find((K)=>K.id===Z);if(!z)return!1;let J={...z,points:[...z.points,...Y]},X={...Q,layers:Q.layers.map((K)=>K.id===Z?J:K),updatedAt:new Date().toISOString()};return b=b.map((K)=>K.id===Q.id?X:K),X2(),!0}function $V($,Z){let Y=b.find((X)=>X.id===$||X.name.toLowerCase()===$.toLowerCase());if(!Y)return!1;let Q=Y.layers.find((X)=>X.id===Z);if(!Q)return!1;let z={...Q,visible:!Q.visible},J={...Y,layers:Y.layers.map((X)=>X.id===Z?z:X),updatedAt:new Date().toISOString()};return b=b.map((X)=>X.id===Y.id?J:X),X2(),!0}function ZV($,Z){let Y=b.find((J)=>J.id===$||J.name.toLowerCase()===$.toLowerCase());if(!Y)return!1;let Q=Y.layers.length,z={...Y,layers:Y.layers.filter((J)=>J.id!==Z),updatedAt:new Date().toISOString()};if(z.layers.length===Q)return!1;return b=b.map((J)=>J.id===Y.id?z:J),X2(),!0}function YV($){if(!$.length)return"Nenhum bairro cadastrado.";return $.map((Z)=>{let Y=Z.pois.length,Q=Z.layers.length,z=Z.tags.length?` [${Z.tags.join(", ")}]`:"";return`\u2022 ${Z.name} \u2014 ${Z.city}/${Z.state} (${Y} POIs, ${Q} layers)${z} [${Z.id}]`}).join(`
1027
- `)}function QV($){return[`# ${$.name}`,`\uD83D\uDCCD ${$.city}, ${$.state}, ${$.country}`,`\uD83D\uDDFA\uFE0F Centro: ${$.center.lat.toFixed(6)}, ${$.center.lng.toFixed(6)}`,$.boundary?`\uD83D\uDCD0 Limite: ${$.boundary.type}`:"\uD83D\uDCD0 Limite: nao disponivel",$.population?`\uD83D\uDC65 Populacao: ${$.population.toLocaleString("pt-BR")}`:"",$.area_km2?`\uD83D\uDCCF Area: ${$.area_km2} km\xB2`:"",$.tags.length?`\uD83C\uDFF7\uFE0F Tags: ${$.tags.join(", ")}`:"","",`## POIs (${$.pois.length})`,...$.pois.map((Y)=>` \u2022 ${Y.name} (${Y.category}) \u2014 ${Y.position.lat.toFixed(4)}, ${Y.position.lng.toFixed(4)} [${Y.id}]`),"",`## Layers (${$.layers.length})`,...$.layers.map((Y)=>` \u2022 ${Y.name} (${Y.type}) \u2014 ${Y.points.length} pontos \u2014 ${Y.visible?"visivel":"oculto"} [${Y.id}]`)].filter(Boolean).join(`
1028
- `)}function H3($){let Z=[];if($.boundary)Z.push({type:"Feature",properties:{type:"boundary",name:$.name,id:$.id},geometry:$.boundary});for(let Y of $.pois)Z.push({type:"Feature",properties:{type:"poi",name:Y.name,category:Y.category,id:Y.id,tags:Y.tags,...Y.metadata},geometry:{type:"Point",coordinates:[Y.position.lng,Y.position.lat]}});for(let Y of $.layers){if(!Y.visible)continue;for(let Q of Y.points)Z.push({type:"Feature",properties:{type:"layer_point",layerName:Y.name,layerType:Y.type,layerId:Y.id,color:Y.color,value:Q.value,label:Q.label,...Q.metadata??{}},geometry:{type:"Point",coordinates:[Q.lng,Q.lat]}})}return{type:"FeatureCollection",features:Z}}function U9(){return{type:"FeatureCollection",features:b.flatMap((Z)=>{return H3(Z).features??[]})}}var IY=3848,wY=!1,zV=IY;function q9(){if(wY)return;let $=new K3;$.use("*",W9()),$.use("*",async(Z,Y)=>{await Y(),Z.header("Cache-Control","no-store, no-cache, must-revalidate"),Z.header("Pragma","no-cache")}),$.get("/",(Z)=>Z.html(V3())),$.get("/map",(Z)=>Z.html(V3())),$.get("/api/neighborhoods",(Z)=>{let Y=t0();return Z.json(Y)}),$.get("/api/neighborhoods/all/geojson",(Z)=>Z.json(U9())),$.get("/api/neighborhoods/:id",(Z)=>{let Y=k1(Z.req.param("id"));if(!Y)return Z.json({error:"Not found"},404);return Z.json(Y)}),$.get("/api/neighborhoods/:id/geojson",(Z)=>{let Y=k1(Z.req.param("id"));if(!Y)return Z.json({error:"Not found"},404);return Z.json(H3(Y))});for(let Z=IY;Z<IY+10;Z++)try{Bun.serve({port:Z,fetch:(Y,Q)=>$.fetch(Y,Q)}),zV=Z,wY=!0,console.log(` Lokaliza mapa: http://localhost:${Z}/map`);return}catch{}}function SY(){return`http://localhost:${zV}/map`}function JV(){return wY}h();import{existsSync as eO,readFileSync as $C}from"fs";import{join as ZC}from"path";var YC=5,XV=15,QC=3,zC=120,JC=180;var XC={0:20,1:15,2:10,3:10,4:15,5:20,6:35,7:50,8:65,9:80,10:90,11:85,12:60,13:55,14:65,15:75,16:80,17:70,18:60,19:50,20:45,21:40,22:35,23:25},KV="",W3={history:[],profile:{bestHours:[9,10,11,16],avgSessionMin:60,avgBreakInterval:45,totalSessions:0,weekdayPattern:{}}},kY=Date.now(),yY=0,fY=Date.now(),B9=Date.now(),c2=0,bY=[],KC=()=>ZC(KV,"energy.json");function VC(){let $=KC();if(!eO($))return;try{let Z=JSON.parse($C($,"utf-8"));W3={history:Z.history??[],profile:{...W3.profile,...Z.profile}}}catch{}}function VV($){KV=$,VC(),kY=Date.now(),B9=Date.now(),yY=0,c2=0,bY=[]}function GV(){yY++,fY=Date.now()}function HV(){c2++,B9=Date.now()}function l2(){let $=Date.now(),Z=($-kY)/60000,Y=($-B9)/60000,Q=new Date().getHours(),z=XC[Q]??50,J=Math.min(50,Math.pow(Z/60,1.5)*10),X=Math.min(30,Y/45*15),K=($-fY)/60000,V=K<2?5:K<5?0:-10,G=c2*3,W=W3.profile.bestHours.includes(Q)?10:0,U=z-J-X+V+G+W,q=Math.max(0,Math.min(100,Math.round(U)));bY=[...bY,q];let N=q>=70?"alto":q>=45?"medio":q>=25?"baixo":"critico",C=Z<15?"aquecimento":q>=70?"pico":q>=45?"sustentado":q>=25?"declinio":"esgotado",M=GC(N,C,Y,Z,Q);return{level:N,score:q,phase:C,sessionStartedAt:kY,sessionDurationMin:Math.round(Z),interactionCount:yY,lastInteractionAt:fY,lastBreakAt:B9,breaksTaken:c2,currentStreak:Math.round(Y),suggestion:M}}function GC($,Z,Y,Q,z){if($==="critico")return"Energia critica. Pare agora \u2014 descanse 15-20 minutos antes de continuar.";if(Y>=JC)return`${Math.round(Y)} minutos sem pausa. Faca uma pausa longa de ${XV} minutos.`;if(Y>=zC)return`${Math.round(Y)} minutos cont\xEDnuos. Levante, alongue, tome agua.`;if(Y>=45&&c2%QC===0&&c2>0)return`${c2} ciclos completos. Hora de uma pausa longa de ${XV} minutos.`;if(Y>=45)return`${Math.round(Y)} minutos focado. Uma pausa de ${YC} minutos ajudaria.`;if(Z==="aquecimento")return"Fase de aquecimento. Comece com tarefas leves para entrar no ritmo.";if(Z==="pico")return"Voce esta no pico! Aproveite para as tarefas mais complexas.";if(z>=22||z<6)return"Horario tardio. Considere encerrar e descansar.";if($==="baixo")return"Energia em declinio. Alterne para tarefas mais leves ou faca uma pausa.";return"Ritmo bom. Continue focado."}var HC={alto:"\uD83D\uDFE2",medio:"\uD83D\uDFE1",baixo:"\uD83D\uDFE0",critico:"\uD83D\uDD34"},WC={aquecimento:"Aquecimento",pico:"Pico",sustentado:"Sustentado",declinio:"Declinio",esgotado:"Esgotado"};function N9($){return[`${HC[$.level]} Energia: ${$.score}/100 (${$.level})`,`Fase: ${WC[$.phase]}`,`Sessao: ${$.sessionDurationMin} min | Streak: ${$.currentStreak} min`,`Interacoes: ${$.interactionCount} | Pausas: ${$.breaksTaken}`,"",`\uD83D\uDCA1 ${$.suggestion}`].join(`
1029
- `)}function WV(){let $=W3.profile;if($.totalSessions<3)return"Perfil de energia ainda em construcao. Use o smolerclaw por mais alguns dias.";let Z=$.bestHours.map((Q)=>`${Q}h`).join(", "),Y=Object.entries($.weekdayPattern).sort((Q,z)=>z[1]-Q[1]).map(([Q,z])=>` ${Q}: ${z}/100`).join(`
1029
+ </html>`}g();import{existsSync as wY,mkdirSync as XC,readFileSync as KC}from"fs";import{join as VC}from"path";import{randomUUID as H3}from"crypto";var kY="",b=[],fY=()=>VC(kY,"neighborhoods.json");function V2(){j(fY(),JSON.stringify(b,null,2))}function QV(){let $=fY();if(!wY($)){b=[];return}try{b=JSON.parse(KC($,"utf-8"))}catch{b=[]}}function zV($){if(kY=$,!wY($))XC($,{recursive:!0});QV()}async function GC($){let Z=`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent($)}&format=json&limit=1&polygon_geojson=1`;try{let Q=await(await fetch(Z,{headers:{"User-Agent":"smolerclaw/1.7.0"}})).json();if(!Q.length)return null;let z=Q[0];return{lat:parseFloat(z.lat),lng:parseFloat(z.lon),displayName:z.display_name,boundingBox:z.boundingbox.map(Number)}}catch{return null}}async function WC($){let Z=`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent($)}&format=json&limit=1&polygon_geojson=1`;try{let Q=await(await fetch(Z,{headers:{"User-Agent":"smolerclaw/1.7.0"}})).json();if(!Q.length||!Q[0].geojson)return null;let z=Q[0].geojson;if(z.type==="Polygon"||z.type==="MultiPolygon")return z;return null}catch{return null}}var HC=[{category:"escola",osmTag:'"amenity"="school"'},{category:"hospital",osmTag:'"amenity"="hospital"'},{category:"posto de saude",osmTag:'"amenity"="clinic"'},{category:"farmacia",osmTag:'"amenity"="pharmacy"'},{category:"delegacia",osmTag:'"amenity"="police"'},{category:"bombeiros",osmTag:'"amenity"="fire_station"'},{category:"supermercado",osmTag:'"shop"="supermarket"'},{category:"estacao de trem",osmTag:'"railway"="station"'},{category:"ponto de onibus",osmTag:'"highway"="bus_stop"'},{category:"parque",osmTag:'"leisure"="park"'},{category:"igreja",osmTag:'"amenity"="place_of_worship"'},{category:"banco",osmTag:'"amenity"="bank"'}];async function UC($,Z,Y=2000){let Q=[],J=`[out:json][timeout:15];(${HC.map((K)=>`node[${K.osmTag}](around:${Y},${$},${Z});way[${K.osmTag}](around:${Y},${$},${Z});`).join("")});out center 100;`,X=`https://overpass-api.de/api/interpreter?data=${encodeURIComponent(J)}`;try{let V=await(await fetch(X,{headers:{"User-Agent":"smolerclaw/1.7.0"}})).json();if(!V.elements)return Q;for(let G of V.elements){let W=G.lat??G.center?.lat,H=G.lon??G.center?.lon;if(!W||!H)continue;let U=G.tags?.name||G.tags?.["name:pt"]||"";if(!U)continue;let q=qC(G.tags??{});Q.push({id:H3().slice(0,8),name:U,category:q,position:{lat:W,lng:H},tags:BC(G.tags??{}),metadata:{source:"openstreetmap",osmType:G.type,...NC(G.tags??{})},createdAt:new Date().toISOString()})}}catch{}return Q}function qC($){if($.amenity==="school")return"escola";if($.amenity==="hospital")return"hospital";if($.amenity==="clinic")return"posto de saude";if($.amenity==="pharmacy")return"farmacia";if($.amenity==="police")return"delegacia";if($.amenity==="fire_station")return"bombeiros";if($.amenity==="bank")return"banco";if($.amenity==="place_of_worship")return"igreja";if($.shop==="supermarket")return"supermercado";if($.railway==="station")return"estacao de trem";if($.highway==="bus_stop")return"ponto de onibus";if($.leisure==="park")return"parque";return $.amenity||$.shop||$.leisure||"outro"}function BC($){let Z=[];if($.amenity)Z.push($.amenity);if($.shop)Z.push($.shop);if($.leisure)Z.push($.leisure);if($.healthcare)Z.push($.healthcare);if($.railway)Z.push($.railway);return Z}function NC($){let Z=["addr:street","addr:housenumber","phone","website","opening_hours","operator"],Y={};for(let Q of Z)if($[Q])Y[Q]=$[Q];return Y}async function JV($,Z,Y,Q="Brazil",z=[],J=!0){let X=`${$}, ${Z}, ${Y}, ${Q}`,K=await GC(X),V=await WC(X),G=new Date().toISOString(),W={id:H3().slice(0,8),name:$,city:Z,state:Y,country:Q,center:K?{lat:K.lat,lng:K.lng}:{lat:0,lng:0},boundary:V,pois:[],layers:[],tags:z.map((H)=>H.toLowerCase()),metadata:K?{displayName:K.displayName,boundingBox:K.boundingBox}:{},createdAt:G,updatedAt:G};if(J&&K){let H=await UC(K.lat,K.lng,3000);if(W.pois=H,H.length>0){let U=new Map;for(let q of H){let N=U.get(q.category)??[];U.set(q.category,[...N,q])}W.layers=[{id:H3().slice(0,8),name:"Infraestrutura",type:"scatter",color:"#00e5cc",opacity:0.8,visible:!0,points:H.map((q)=>({lat:q.position.lat,lng:q.position.lng,value:1,label:`${q.name} (${q.category})`}))}],W.metadata={...W.metadata,enrichedAt:G,poiBreakdown:Object.fromEntries([...U.entries()].map(([q,N])=>[q,N.length]))}}}return b=[...b,W],V2(),F7([Y]),W}function b1($){return b.find((Z)=>Z.id===$||Z.name.toLowerCase()===$.toLowerCase())??null}function Z1(){if(!b.length&&kY&&wY(fY()))QV();return b}function XV($){let Z=b.length;if(b=b.filter((Y)=>Y.id!==$&&Y.name.toLowerCase()!==$.toLowerCase()),b.length<Z)return V2(),!0;return!1}function KV($){let Z=$.toLowerCase();return b.map((Y)=>{let Q=0;if(Y.name.toLowerCase().includes(Z))Q+=10;if(Y.city.toLowerCase().includes(Z))Q+=5;if(Y.tags.some((z)=>z.includes(Z)))Q+=3;if(Y.pois.some((z)=>z.name.toLowerCase().includes(Z)))Q+=2;return{neighborhood:Y,score:Q}}).filter((Y)=>Y.score>0).sort((Y,Q)=>Q.score-Y.score)}function VV($,Z,Y,Q,z,J=[],X={}){let K=b.find((W)=>W.id===$||W.name.toLowerCase()===$.toLowerCase());if(!K)return null;let V={id:H3().slice(0,8),name:Z,category:Y,position:{lat:Q,lng:z},tags:J.map((W)=>W.toLowerCase()),metadata:X,createdAt:new Date().toISOString()},G={...K,pois:[...K.pois,V],updatedAt:new Date().toISOString()};return b=b.map((W)=>W.id===K.id?G:W),V2(),V}function GV($,Z){let Y=b.find((J)=>J.id===$||J.name.toLowerCase()===$.toLowerCase());if(!Y)return!1;let Q=Y.pois.length,z={...Y,pois:Y.pois.filter((J)=>J.id!==Z),updatedAt:new Date().toISOString()};if(z.pois.length===Q)return!1;return b=b.map((J)=>J.id===Y.id?z:J),V2(),!0}function WV($,Z,Y,Q="#00ffcc",z=[]){let J=b.find((V)=>V.id===$||V.name.toLowerCase()===$.toLowerCase());if(!J)return null;let X={id:H3().slice(0,8),name:Z,type:Y,color:Q,opacity:0.7,visible:!0,points:z},K={...J,layers:[...J.layers,X],updatedAt:new Date().toISOString()};return b=b.map((V)=>V.id===J.id?K:V),V2(),X}function HV($,Z,Y){let Q=b.find((K)=>K.id===$||K.name.toLowerCase()===$.toLowerCase());if(!Q)return!1;let z=Q.layers.find((K)=>K.id===Z);if(!z)return!1;let J={...z,points:[...z.points,...Y]},X={...Q,layers:Q.layers.map((K)=>K.id===Z?J:K),updatedAt:new Date().toISOString()};return b=b.map((K)=>K.id===Q.id?X:K),V2(),!0}function UV($,Z){let Y=b.find((X)=>X.id===$||X.name.toLowerCase()===$.toLowerCase());if(!Y)return!1;let Q=Y.layers.find((X)=>X.id===Z);if(!Q)return!1;let z={...Q,visible:!Q.visible},J={...Y,layers:Y.layers.map((X)=>X.id===Z?z:X),updatedAt:new Date().toISOString()};return b=b.map((X)=>X.id===Y.id?J:X),V2(),!0}function qV($,Z){let Y=b.find((J)=>J.id===$||J.name.toLowerCase()===$.toLowerCase());if(!Y)return!1;let Q=Y.layers.length,z={...Y,layers:Y.layers.filter((J)=>J.id!==Z),updatedAt:new Date().toISOString()};if(z.layers.length===Q)return!1;return b=b.map((J)=>J.id===Y.id?z:J),V2(),!0}function BV($){if(!$.length)return"Nenhum bairro cadastrado.";return $.map((Z)=>{let Y=Z.pois.length,Q=Z.layers.length,z=Z.tags.length?` [${Z.tags.join(", ")}]`:"";return`\u2022 ${Z.name} \u2014 ${Z.city}/${Z.state} (${Y} POIs, ${Q} layers)${z} [${Z.id}]`}).join(`
1030
+ `)}function NV($){return[`# ${$.name}`,`\uD83D\uDCCD ${$.city}, ${$.state}, ${$.country}`,`\uD83D\uDDFA\uFE0F Centro: ${$.center.lat.toFixed(6)}, ${$.center.lng.toFixed(6)}`,$.boundary?`\uD83D\uDCD0 Limite: ${$.boundary.type}`:"\uD83D\uDCD0 Limite: nao disponivel",$.population?`\uD83D\uDC65 Populacao: ${$.population.toLocaleString("pt-BR")}`:"",$.area_km2?`\uD83D\uDCCF Area: ${$.area_km2} km\xB2`:"",$.tags.length?`\uD83C\uDFF7\uFE0F Tags: ${$.tags.join(", ")}`:"","",`## POIs (${$.pois.length})`,...$.pois.map((Y)=>` \u2022 ${Y.name} (${Y.category}) \u2014 ${Y.position.lat.toFixed(4)}, ${Y.position.lng.toFixed(4)} [${Y.id}]`),"",`## Layers (${$.layers.length})`,...$.layers.map((Y)=>` \u2022 ${Y.name} (${Y.type}) \u2014 ${Y.points.length} pontos \u2014 ${Y.visible?"visivel":"oculto"} [${Y.id}]`)].filter(Boolean).join(`
1031
+ `)}function U3($){let Z=[];if($.boundary)Z.push({type:"Feature",properties:{type:"boundary",name:$.name,id:$.id},geometry:$.boundary});for(let Y of $.pois)Z.push({type:"Feature",properties:{type:"poi",name:Y.name,category:Y.category,id:Y.id,tags:Y.tags,...Y.metadata},geometry:{type:"Point",coordinates:[Y.position.lng,Y.position.lat]}});for(let Y of $.layers){if(!Y.visible)continue;for(let Q of Y.points)Z.push({type:"Feature",properties:{type:"layer_point",layerName:Y.name,layerType:Y.type,layerId:Y.id,color:Y.color,value:Q.value,label:Q.label,...Q.metadata??{}},geometry:{type:"Point",coordinates:[Q.lng,Q.lat]}})}return{type:"FeatureCollection",features:Z}}function O9(){return{type:"FeatureCollection",features:b.flatMap((Z)=>{return U3(Z).features??[]})}}var bY=3848,yY=!1,OV=bY;function C9(){if(yY)return;let $=new G3;$.use("*",N9()),$.use("*",async(Z,Y)=>{await Y(),Z.header("Cache-Control","no-store, no-cache, must-revalidate"),Z.header("Pragma","no-cache")}),$.get("/",(Z)=>Z.html(W3())),$.get("/map",(Z)=>Z.html(W3())),$.get("/api/neighborhoods",(Z)=>{let Y=Z1();return Z.json(Y)}),$.get("/api/neighborhoods/all/geojson",(Z)=>Z.json(O9())),$.get("/api/neighborhoods/:id",(Z)=>{let Y=b1(Z.req.param("id"));if(!Y)return Z.json({error:"Not found"},404);return Z.json(Y)}),$.get("/api/neighborhoods/:id/geojson",(Z)=>{let Y=b1(Z.req.param("id"));if(!Y)return Z.json({error:"Not found"},404);return Z.json(U3(Y))});for(let Z=bY;Z<bY+10;Z++)try{Bun.serve({port:Z,fetch:(Y,Q)=>$.fetch(Y,Q)}),OV=Z,yY=!0,console.log(` Lokaliza mapa: http://localhost:${Z}/map`);return}catch{}}function vY(){return`http://localhost:${OV}/map`}function CV(){return yY}g();import{existsSync as OC,readFileSync as CC}from"fs";import{join as MC}from"path";var EC=5,MV=15,FC=3,LC=120,RC=180;var jC={0:20,1:15,2:10,3:10,4:15,5:20,6:35,7:50,8:65,9:80,10:90,11:85,12:60,13:55,14:65,15:75,16:80,17:70,18:60,19:50,20:45,21:40,22:35,23:25},EV="",q3={history:[],profile:{bestHours:[9,10,11,16],avgSessionMin:60,avgBreakInterval:45,totalSessions:0,weekdayPattern:{}}},xY=Date.now(),gY=0,_Y=Date.now(),M9=Date.now(),o2=0,hY=[],PC=()=>MC(EV,"energy.json");function AC(){let $=PC();if(!OC($))return;try{let Z=JSON.parse(CC($,"utf-8"));q3={history:Z.history??[],profile:{...q3.profile,...Z.profile}}}catch{}}function FV($){EV=$,AC(),xY=Date.now(),M9=Date.now(),gY=0,o2=0,hY=[]}function LV(){gY++,_Y=Date.now()}function RV(){o2++,M9=Date.now()}function i2(){let $=Date.now(),Z=($-xY)/60000,Y=($-M9)/60000,Q=new Date().getHours(),z=jC[Q]??50,J=Math.min(50,Math.pow(Z/60,1.5)*10),X=Math.min(30,Y/45*15),K=($-_Y)/60000,V=K<2?5:K<5?0:-10,G=o2*3,H=q3.profile.bestHours.includes(Q)?10:0,U=z-J-X+V+G+H,q=Math.max(0,Math.min(100,Math.round(U)));hY=[...hY,q];let N=q>=70?"alto":q>=45?"medio":q>=25?"baixo":"critico",C=Z<15?"aquecimento":q>=70?"pico":q>=45?"sustentado":q>=25?"declinio":"esgotado",M=DC(N,C,Y,Z,Q);return{level:N,score:q,phase:C,sessionStartedAt:xY,sessionDurationMin:Math.round(Z),interactionCount:gY,lastInteractionAt:_Y,lastBreakAt:M9,breaksTaken:o2,currentStreak:Math.round(Y),suggestion:M}}function DC($,Z,Y,Q,z){if($==="critico")return"Energia critica. Pare agora \u2014 descanse 15-20 minutos antes de continuar.";if(Y>=RC)return`${Math.round(Y)} minutos sem pausa. Faca uma pausa longa de ${MV} minutos.`;if(Y>=LC)return`${Math.round(Y)} minutos cont\xEDnuos. Levante, alongue, tome agua.`;if(Y>=45&&o2%FC===0&&o2>0)return`${o2} ciclos completos. Hora de uma pausa longa de ${MV} minutos.`;if(Y>=45)return`${Math.round(Y)} minutos focado. Uma pausa de ${EC} minutos ajudaria.`;if(Z==="aquecimento")return"Fase de aquecimento. Comece com tarefas leves para entrar no ritmo.";if(Z==="pico")return"Voce esta no pico! Aproveite para as tarefas mais complexas.";if(z>=22||z<6)return"Horario tardio. Considere encerrar e descansar.";if($==="baixo")return"Energia em declinio. Alterne para tarefas mais leves ou faca uma pausa.";return"Ritmo bom. Continue focado."}var TC={alto:"\uD83D\uDFE2",medio:"\uD83D\uDFE1",baixo:"\uD83D\uDFE0",critico:"\uD83D\uDD34"},IC={aquecimento:"Aquecimento",pico:"Pico",sustentado:"Sustentado",declinio:"Declinio",esgotado:"Esgotado"};function E9($){return[`${TC[$.level]} Energia: ${$.score}/100 (${$.level})`,`Fase: ${IC[$.phase]}`,`Sessao: ${$.sessionDurationMin} min | Streak: ${$.currentStreak} min`,`Interacoes: ${$.interactionCount} | Pausas: ${$.breaksTaken}`,"",`\uD83D\uDCA1 ${$.suggestion}`].join(`
1032
+ `)}function jV(){let $=q3.profile;if($.totalSessions<3)return"Perfil de energia ainda em construcao. Use o smolerclaw por mais alguns dias.";let Z=$.bestHours.map((Q)=>`${Q}h`).join(", "),Y=Object.entries($.weekdayPattern).sort((Q,z)=>z[1]-Q[1]).map(([Q,z])=>` ${Q}: ${z}/100`).join(`
1030
1033
  `);return["# Seu Perfil de Energia","",`Sessoes registradas: ${$.totalSessions}`,`Sessao media: ${$.avgSessionMin} min`,`Intervalo medio entre pausas: ${$.avgBreakInterval} min`,`Horarios de pico: ${Z}`,"","## Energia por dia da semana",Y].join(`
1031
- `)}function O9(){return W3.profile}h();import{existsSync as UC,readFileSync as qC}from"fs";import{join as BC}from"path";var qV="",u={focusMode:"desligado",focusUntil:null,notifications:[],dailyDigests:[],blockedToday:0},NC=null,UV="",BV=()=>BC(qV,"attention.json");function vY(){P(BV(),JSON.stringify({focusMode:u.focusMode,focusUntil:u.focusUntil,dailyDigests:u.dailyDigests,blockedToday:u.blockedToday},null,2))}function OC(){let $=BV();if(!UC($))return;try{let Z=JSON.parse(qC($,"utf-8"));u={...u,focusMode:Z.focusMode??"desligado",focusUntil:Z.focusUntil??null,dailyDigests:Z.dailyDigests??[],blockedToday:Z.blockedToday??0}}catch{}}function NV($,Z){qV=$,NC=Z??null,OC();let Y=new Date().toISOString().split("T")[0];if(UV!==Y)u={...u,blockedToday:0},UV=Y;if(u.focusUntil&&Date.now()>u.focusUntil)u={...u,focusMode:"desligado",focusUntil:null},vY()}function OV($,Z){let Y=Z?Date.now()+Z*60000:null;u={...u,focusMode:$,focusUntil:Y},vY();let Q={desligado:"Desligado \u2014 todas as notificacoes ativas",leve:"Leve \u2014 ruido filtrado",profundo:"Profundo \u2014 so urgente e importante",nao_perturbe:"Nao Perturbe \u2014 so urgencias"},z=Z?` por ${Z} minutos`:"";return`Foco: ${Q[$]}${z}`}function CC(){if(u.focusUntil&&Date.now()>u.focusUntil)u={...u,focusMode:"desligado",focusUntil:null},vY();return u.focusMode}function CV(){return u.notifications.filter(($)=>$.delivered&&!$.dismissed)}function MV(){let $=CV();return u={...u,notifications:u.notifications.map((Z)=>Z.delivered&&!Z.dismissed?{...Z,dismissed:!0}:Z)},$.length}function U3(){let $=new Date().toISOString().split("T")[0],Z=u.notifications.filter((Y)=>new Date(Y.timestamp).toISOString().split("T")[0]===$);return{focusMode:CC(),pending:CV().length,blockedToday:u.blockedToday,totalToday:Z.length}}function EV(){let $=U3(),Z={desligado:"Desligado",leve:"Leve",profundo:"Profundo",nao_perturbe:"Nao Perturbe"},Y=u.focusUntil?` (${Math.max(0,Math.round((u.focusUntil-Date.now())/60000))} min restantes)`:"";return[`Modo foco: ${Z[$.focusMode]}${Y}`,`Pendentes: ${$.pending} | Bloqueadas hoje: ${$.blockedToday} | Total hoje: ${$.totalToday}`].join(`
1032
- `)}Z0();z1();Q1();import{writeFileSync as MC,unlinkSync as EC,existsSync as FC}from"fs";import{join as LC}from"path";import{tmpdir as RC}from"os";import{randomUUID as jC}from"crypto";var PC=30000,FV=50000;var AC=[{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)"}],DC=[{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 xY($){for(let{pattern:Z,reason:Y}of AC)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of DC)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function q3($){if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>FV)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${FV}).`,exitCode:1,duration:0};let Z=xY($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};if(!R)return{stdout:"",stderr:"Error: PowerShell scripts only available on Windows.",exitCode:1,duration:0};let Y=jC().slice(0,8),Q=LC(RC(),`smolerclaw-${Y}.ps1`);try{MC(Q,$,"utf-8");let z=await xz(Q,{timeout:PC});return{stdout:z.stdout,stderr:z.timedOut?"Script timeout exceeded":z.stderr,exitCode:z.exitCode,duration:z.duration}}finally{try{if(FC(Q))EC(Q)}catch{}}}async function C9(){if(!R)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await TC();if($.type==="text")return $;return await IC()}async function TC(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await wZ($,{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 IC(){try{let Z=await wZ(`
1034
+ `)}function F9(){return q3.profile}g();import{existsSync as SC,readFileSync as wC}from"fs";import{join as kC}from"path";var AV="",d={focusMode:"desligado",focusUntil:null,notifications:[],dailyDigests:[],blockedToday:0},fC=null,PV="",DV=()=>kC(AV,"attention.json");function mY(){j(DV(),JSON.stringify({focusMode:d.focusMode,focusUntil:d.focusUntil,dailyDigests:d.dailyDigests,blockedToday:d.blockedToday},null,2))}function bC(){let $=DV();if(!SC($))return;try{let Z=JSON.parse(wC($,"utf-8"));d={...d,focusMode:Z.focusMode??"desligado",focusUntil:Z.focusUntil??null,dailyDigests:Z.dailyDigests??[],blockedToday:Z.blockedToday??0}}catch{}}function TV($,Z){AV=$,fC=Z??null,bC();let Y=new Date().toISOString().split("T")[0];if(PV!==Y)d={...d,blockedToday:0},PV=Y;if(d.focusUntil&&Date.now()>d.focusUntil)d={...d,focusMode:"desligado",focusUntil:null},mY()}function IV($,Z){let Y=Z?Date.now()+Z*60000:null;d={...d,focusMode:$,focusUntil:Y},mY();let Q={desligado:"Desligado \u2014 todas as notificacoes ativas",leve:"Leve \u2014 ruido filtrado",profundo:"Profundo \u2014 so urgente e importante",nao_perturbe:"Nao Perturbe \u2014 so urgencias"},z=Z?` por ${Z} minutos`:"";return`Foco: ${Q[$]}${z}`}function yC(){if(d.focusUntil&&Date.now()>d.focusUntil)d={...d,focusMode:"desligado",focusUntil:null},mY();return d.focusMode}function SV(){return d.notifications.filter(($)=>$.delivered&&!$.dismissed)}function wV(){let $=SV();return d={...d,notifications:d.notifications.map((Z)=>Z.delivered&&!Z.dismissed?{...Z,dismissed:!0}:Z)},$.length}function B3(){let $=new Date().toISOString().split("T")[0],Z=d.notifications.filter((Y)=>new Date(Y.timestamp).toISOString().split("T")[0]===$);return{focusMode:yC(),pending:SV().length,blockedToday:d.blockedToday,totalToday:Z.length}}function kV(){let $=B3(),Z={desligado:"Desligado",leve:"Leve",profundo:"Profundo",nao_perturbe:"Nao Perturbe"},Y=d.focusUntil?` (${Math.max(0,Math.round((d.focusUntil-Date.now())/60000))} min restantes)`:"";return[`Modo foco: ${Z[$.focusMode]}${Y}`,`Pendentes: ${$.pending} | Bloqueadas hoje: ${$.blockedToday} | Total hoje: ${$.totalToday}`].join(`
1035
+ `)}Y0();X1();J1();import{writeFileSync as vC,unlinkSync as xC,existsSync as _C}from"fs";import{join as hC}from"path";import{tmpdir as gC}from"os";import{randomUUID as mC}from"crypto";var pC=30000,fV=50000;var uC=[{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)"}],dC=[{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 pY($){for(let{pattern:Z,reason:Y}of uC)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of dC)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function N3($){if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>fV)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${fV}).`,exitCode:1,duration:0};let Z=pY($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};if(!R)return{stdout:"",stderr:"Error: PowerShell scripts only available on Windows.",exitCode:1,duration:0};let Y=mC().slice(0,8),Q=hC(gC(),`smolerclaw-${Y}.ps1`);try{vC(Q,$,"utf-8");let z=await nz(Q,{timeout:pC});return{stdout:z.stdout,stderr:z.timedOut?"Script timeout exceeded":z.stderr,exitCode:z.exitCode,duration:z.duration}}finally{try{if(_C(Q))xC(Q)}catch{}}}async function L9(){if(!R)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await cC();if($.type==="text")return $;return await lC()}async function cC(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await yZ($,{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 lC(){try{let Z=await yZ(`
1033
1036
  Add-Type -AssemblyName System.Windows.Forms
1034
1037
  $img = [System.Windows.Forms.Clipboard]::GetImage()
1035
1038
  if (-not $img) {
@@ -1080,7 +1083,7 @@ try {
1080
1083
  if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
1081
1084
  }
1082
1085
  `,{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]
1083
- ${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function M9(){if(!R)return"Error: screen context analysis only available on Windows.";let $=`
1086
+ ${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function R9(){if(!R)return"Error: screen context analysis only available on Windows.";let $=`
1084
1087
  $sig = @'
1085
1088
  [DllImport("user32.dll")]
1086
1089
  public static extern IntPtr GetForegroundWindow();
@@ -1113,7 +1116,7 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
1113
1116
  $marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
1114
1117
  Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
1115
1118
  }
1116
- `;try{let Z=await q0($,{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 LV($,Z){if(!$?.trim())return{success:!1,error:"Title is required."};if(!Z?.trim())return{success:!1,error:"Message is required."};if(!R)return{success:!1,error:"Notifications only available on Windows."};let Y=$.replace(/'/g,"''"),Q=Z.replace(/'/g,"''"),z=`
1119
+ `;try{let Z=await B0($,{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 bV($,Z){if(!$?.trim())return{success:!1,error:"Title is required."};if(!Z?.trim())return{success:!1,error:"Message is required."};if(!R)return{success:!1,error:"Notifications only available on Windows."};let Y=$.replace(/'/g,"''"),Q=Z.replace(/'/g,"''"),z=`
1117
1120
  $notificationTitle = '${Y}'
1118
1121
  $notificationText = '${Q}'
1119
1122
  [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
@@ -1126,64 +1129,64 @@ $xml.LoadXml($toastXml.OuterXml)
1126
1129
  $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
1127
1130
  [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Smolerclaw').Show($toast)
1128
1131
  Write-Output 'OK'
1129
- `;try{let J=await q3(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)}}}h();import{existsSync as RV,mkdirSync as wC,readFileSync as SC}from"fs";import{join as kC}from"path";import{randomUUID as fC}from"crypto";var jV="",y=[],PV=()=>kC(jV,"recommendations.json");function B3(){P(PV(),JSON.stringify(y,null,2))}function bC(){let $=PV();if(!RV($)){y=[];return}try{let Z=JSON.parse(SC($,"utf-8"));if(!Array.isArray(Z)){y=[];return}y=Z}catch{y=[]}}function AV($){if(jV=$,!RV($))wC($,{recursive:!0});bC()}function DV($,Z,Y,Q=[],z=[],J){let X=new Date().toISOString(),K={id:fC().slice(0,8),type:$,title:Z.trim(),creator:Y.trim(),tags:Q.map((V)=>V.toLowerCase()),moods:z,url:J?.trim()||void 0,rating:null,timesRecommended:0,timesConsumed:0,createdAt:X,updatedAt:X};return y=[...y,K],B3(),K}function TV($,Z){let Y=Math.max(1,Math.min(5,Math.round(Z)));if(!y.find((z)=>z.id===$))return null;return y=y.map((z)=>z.id===$?{...z,rating:Y,updatedAt:new Date().toISOString()}:z),B3(),y.find((z)=>z.id===$)||null}function IV($){if(!y.find((Y)=>Y.id===$))return null;return y=y.map((Y)=>Y.id===$?{...Y,timesConsumed:Y.timesConsumed+1,updatedAt:new Date().toISOString()}:Y),B3(),y.find((Y)=>Y.id===$)||null}function wV($){let Z=y.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return y=[...y.slice(0,Z),...y.slice(Z+1)],B3(),!0}function SV($){let Z=$.toLowerCase().trim();if(!Z)return[...y];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return y.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 _Y($,Z=20){return($?y.filter((Q)=>Q.type===$):[...y]).sort((Q,z)=>new Date(z.updatedAt).getTime()-new Date(Q.updatedAt).getTime()).slice(0,Z)}function kV($,Z,Y=5){if(y.length===0)return[];let J=y.filter((K)=>!Z||K.type===Z).map((K)=>{let V=0,G=[];if($&&K.moods.includes($))V+=30,G.push(`combina com mood "${$}"`);if(K.rating!==null){if(V+=K.rating*5,K.rating>=4)G.push(`avaliado ${K.rating}/5`)}if((Date.now()-new Date(K.createdAt).getTime())/86400000<7)V+=10,G.push("adicionado recentemente");if(K.timesConsumed===0)V+=15,G.push("ainda nao consumido");else if(K.timesConsumed<3)V+=5;if(K.timesRecommended<2)V+=8;if(G.length===0)G.push("item do seu catalogo");return{item:K,reason:G.join(", "),score:V}}).sort((K,V)=>V.score-K.score).slice(0,Y),X=new Set(J.map((K)=>K.item.id));return y=y.map((K)=>X.has(K.id)?{...K,timesRecommended:K.timesRecommended+1}:K),B3(),J}function fV(){let $=y.reduce((K,V)=>({...K,[V.type]:K[V.type]+1}),{video:0,movie:0,music:0}),Z=y.reduce((K,V)=>V.moods.reduce((G,H)=>({...G,[H]:G[H]+1}),K),{relaxar:0,energizar:0,focar:0,inspirar:0,descontrair:0}),Y=y.filter((K)=>K.rating!==null),Q=Y.reduce((K,V)=>K+(V.rating||0),0),z=Y.length,J=[...y].filter((K)=>K.rating!==null).sort((K,V)=>(V.rating||0)-(K.rating||0)).slice(0,5),X=[...y].filter((K)=>K.timesConsumed>0).sort((K,V)=>V.timesConsumed-K.timesConsumed).slice(0,5);return{total:y.length,byType:$,byMood:Z,avgRating:z>0?Math.round(Q/z*10)/10:null,topRated:J,mostConsumed:X}}var E9={video:"[V]",movie:"[F]",music:"[M]"};function F9($){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` ${E9[Y.type]} ${Y.title} \u2014 ${Y.creator}${Q}${z}${J} {${Y.id}}`});return`Catalogo (${$.length}):
1132
+ `;try{let J=await N3(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)}}}g();import{existsSync as yV,mkdirSync as oC,readFileSync as iC}from"fs";import{join as nC}from"path";import{randomUUID as rC}from"crypto";var vV="",y=[],xV=()=>nC(vV,"recommendations.json");function O3(){j(xV(),JSON.stringify(y,null,2))}function aC(){let $=xV();if(!yV($)){y=[];return}try{let Z=JSON.parse(iC($,"utf-8"));if(!Array.isArray(Z)){y=[];return}y=Z}catch{y=[]}}function _V($){if(vV=$,!yV($))oC($,{recursive:!0});aC()}function hV($,Z,Y,Q=[],z=[],J){let X=new Date().toISOString(),K={id:rC().slice(0,8),type:$,title:Z.trim(),creator:Y.trim(),tags:Q.map((V)=>V.toLowerCase()),moods:z,url:J?.trim()||void 0,rating:null,timesRecommended:0,timesConsumed:0,createdAt:X,updatedAt:X};return y=[...y,K],O3(),K}function gV($,Z){let Y=Math.max(1,Math.min(5,Math.round(Z)));if(!y.find((z)=>z.id===$))return null;return y=y.map((z)=>z.id===$?{...z,rating:Y,updatedAt:new Date().toISOString()}:z),O3(),y.find((z)=>z.id===$)||null}function mV($){if(!y.find((Y)=>Y.id===$))return null;return y=y.map((Y)=>Y.id===$?{...Y,timesConsumed:Y.timesConsumed+1,updatedAt:new Date().toISOString()}:Y),O3(),y.find((Y)=>Y.id===$)||null}function pV($){let Z=y.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return y=[...y.slice(0,Z),...y.slice(Z+1)],O3(),!0}function uV($){let Z=$.toLowerCase().trim();if(!Z)return[...y];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return y.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 uY($,Z=20){return($?y.filter((Q)=>Q.type===$):[...y]).sort((Q,z)=>new Date(z.updatedAt).getTime()-new Date(Q.updatedAt).getTime()).slice(0,Z)}function dV($,Z,Y=5){if(y.length===0)return[];let J=y.filter((K)=>!Z||K.type===Z).map((K)=>{let V=0,G=[];if($&&K.moods.includes($))V+=30,G.push(`combina com mood "${$}"`);if(K.rating!==null){if(V+=K.rating*5,K.rating>=4)G.push(`avaliado ${K.rating}/5`)}if((Date.now()-new Date(K.createdAt).getTime())/86400000<7)V+=10,G.push("adicionado recentemente");if(K.timesConsumed===0)V+=15,G.push("ainda nao consumido");else if(K.timesConsumed<3)V+=5;if(K.timesRecommended<2)V+=8;if(G.length===0)G.push("item do seu catalogo");return{item:K,reason:G.join(", "),score:V}}).sort((K,V)=>V.score-K.score).slice(0,Y),X=new Set(J.map((K)=>K.item.id));return y=y.map((K)=>X.has(K.id)?{...K,timesRecommended:K.timesRecommended+1}:K),O3(),J}function cV(){let $=y.reduce((K,V)=>({...K,[V.type]:K[V.type]+1}),{video:0,movie:0,music:0}),Z=y.reduce((K,V)=>V.moods.reduce((G,W)=>({...G,[W]:G[W]+1}),K),{relaxar:0,energizar:0,focar:0,inspirar:0,descontrair:0}),Y=y.filter((K)=>K.rating!==null),Q=Y.reduce((K,V)=>K+(V.rating||0),0),z=Y.length,J=[...y].filter((K)=>K.rating!==null).sort((K,V)=>(V.rating||0)-(K.rating||0)).slice(0,5),X=[...y].filter((K)=>K.timesConsumed>0).sort((K,V)=>V.timesConsumed-K.timesConsumed).slice(0,5);return{total:y.length,byType:$,byMood:Z,avgRating:z>0?Math.round(Q/z*10)/10:null,topRated:J,mostConsumed:X}}var j9={video:"[V]",movie:"[F]",music:"[M]"};function P9($){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` ${j9[Y.type]} ${Y.title} \u2014 ${Y.creator}${Q}${z}${J} {${Y.id}}`});return`Catalogo (${$.length}):
1130
1133
  ${Z.join(`
1131
- `)}`}function bV($,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)}`:"",V=X.url?`
1132
- -> ${X.url}`:"";return` ${J+1}. ${E9[X.type]} ${X.title} \u2014 ${X.creator}${K}
1134
+ `)}`}function lV($,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)}`:"",V=X.url?`
1135
+ -> ${X.url}`:"";return` ${J+1}. ${j9[X.type]} ${X.title} \u2014 ${X.creator}${K}
1133
1136
  ${z.reason}${V} {${X.id}}`});return`${Y}
1134
1137
  ${Q.join(`
1135
- `)}`}function yV($){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(` ${E9[Y.type]} ${Y.title} \u2014 ${"*".repeat(Y.rating||0)}`)}if($.mostConsumed.length>0){Z.push("","Mais consumidos:");for(let Y of $.mostConsumed)Z.push(` ${E9[Y.type]} ${Y.title} (${Y.timesConsumed}x)`)}return Z.join(`
1136
- `)}var N3=50000;function H1($){if($.length<=N3)return $;return $.slice(0,N3)+`
1137
- ... (output truncated)`}function O3($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function hY($){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,V]of Object.entries(J))if(Z.includes(K)){let G=new Date(Y),H=(V-G.getDay()+7)%7||7;return G.setDate(G.getDate()+H),G}let X=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(X){let K=parseInt(X[1]),V=parseInt(X[2])-1,G=X[3]?parseInt(X[3])+(X[3].length===2?2000:0):Y.getFullYear(),H=new Date(G,V,K);if(!isNaN(H.getTime()))return H}return E5(Z)}var R9=[{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:[]}}],j9=[{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"]}}],P9=[{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."},neighborhood:{type:"string",description:"Linked neighborhood name or ID from Lokaliza. Optional."},location:{type:"string",description:"Free-text location (city, region). 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:[]}}],A9=[{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"]}}],D9={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"]}},T9=[{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"]}}],I9=[{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:[]}}],w9=[{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"]}}],S9=[{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"]}}],k9=[{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"]}}],f9=[{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"]}}],b9=[{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"]}}],y9=[{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"]}}],v9=[{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:[]}}],x9=[{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:[]}}],gY=[{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:[]}}],_9=[{name:"add_neighborhood",description:"Register a neighborhood for mapping. Auto-fetches coordinates and boundary polygon from OpenStreetMap. Opens it on the /map web view.",input_schema:{type:"object",properties:{name:{type:"string",description:'Neighborhood name (e.g. "Copacabana")'},city:{type:"string",description:'City (e.g. "Rio de Janeiro")'},state:{type:"string",description:'State (e.g. "RJ")'},country:{type:"string",description:"Country. Default: Brazil."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["name","city","state"]}},{name:"get_neighborhood",description:"Get detailed info about a registered neighborhood by ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Neighborhood ID or name"}},required:["reference"]}},{name:"list_neighborhoods",description:"List all registered neighborhoods.",input_schema:{type:"object",properties:{},required:[]}},{name:"remove_neighborhood",description:"Remove a registered neighborhood by ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Neighborhood ID or name"}},required:["reference"]}},{name:"search_neighborhoods",description:"Search neighborhoods by name, city, tags, or POI names.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}},{name:"add_poi",description:"Add a Point of Interest (commerce, landmark, event) to a neighborhood.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},name:{type:"string",description:"POI name"},category:{type:"string",description:'Category (e.g. "restaurante", "escola", "hospital")'},lat:{type:"number",description:"Latitude"},lng:{type:"number",description:"Longitude"},tags:{type:"array",items:{type:"string"},description:"Tags. Optional."}},required:["neighborhood","name","category","lat","lng"]}},{name:"remove_poi",description:"Remove a POI from a neighborhood.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},poi_id:{type:"string",description:"POI ID"}},required:["neighborhood","poi_id"]}},{name:"add_map_layer",description:"Add a data visualization layer to a neighborhood (heatmap, hexbin, scatter, arc, polygon, icon). Layers are rendered on the Lokaliza map view.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},name:{type:"string",description:'Layer name (e.g. "Densidade Populacional", "Crimes 2024")'},type:{type:"string",enum:["heatmap","hexbin","scatter","arc","polygon","icon"],description:"Visualization type"},color:{type:"string",description:"Hex color. Default: #00ffcc"},points:{type:"array",items:{type:"object",properties:{lat:{type:"number"},lng:{type:"number"},value:{type:"number",description:"Numeric value for heatmap/hexbin intensity"},label:{type:"string",description:"Optional label"}},required:["lat","lng"]},description:"Data points for the layer. Optional \u2014 can add later with add_layer_points."}},required:["neighborhood","name","type"]}},{name:"add_layer_points",description:"Add data points to an existing map layer.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},layer_id:{type:"string",description:"Layer ID"},points:{type:"array",items:{type:"object",properties:{lat:{type:"number"},lng:{type:"number"},value:{type:"number"},label:{type:"string"}},required:["lat","lng"]},description:"Data points to add"}},required:["neighborhood","layer_id","points"]}},{name:"toggle_layer",description:"Toggle visibility of a data layer on the map.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},layer_id:{type:"string",description:"Layer ID"}},required:["neighborhood","layer_id"]}},{name:"remove_layer",description:"Remove a data layer from a neighborhood.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},layer_id:{type:"string",description:"Layer ID"}},required:["neighborhood","layer_id"]}},{name:"open_map",description:"Open the Lokaliza map in the default browser. "+"Automatically resolves the correct URL \u2014 no port needed.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Optional: fly to this neighborhood on open."}},required:[]}},{name:"analyze_neighborhood",description:"Run autonomous multi-step analysis on a neighborhood. Auto-enriches with POIs if not done, generates category breakdown, creates density layers, and produces a structured intelligence report. The report is auto-saved as a memo.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},focus:{type:"string",enum:["infraestrutura","seguranca","educacao","saude","comercio","transporte","geral"],description:"Analysis focus area. Default: geral (all areas)."}},required:["neighborhood"]}},{name:"get_regional_news",description:"Fetch news filtered by the state/region of registered neighborhoods. Automatically uses regional feeds based on Lokaliza data.",input_schema:{type:"object",properties:{state:{type:"string",description:'State code (e.g. "SP", "RJ"). If omitted, uses all registered neighborhoods.'}},required:[]}}],h9=[{name:"check_energy",description:"Check current energy level, cognitive load score, work phase, and get a smart suggestion. Call this proactively when the user seems tired, before complex tasks, or periodically.",input_schema:{type:"object",properties:{},required:[]}},{name:"take_break",description:"Record that the user is taking a break. Resets the work streak timer. Call when the user says they are pausing, going for coffee, stretching, etc.",input_schema:{type:"object",properties:{},required:[]}},{name:"energy_profile",description:"Show the user's learned energy profile \u2014 best hours, avg session duration, "+"weekly energy patterns. Based on historical data.",input_schema:{type:"object",properties:{},required:[]}},{name:"set_focus",description:"Set focus/attention mode to filter notifications. Modes: desligado (all notifications), leve (no noise), profundo (only urgent+important), nao_perturbe (only urgent). Optional duration in minutes.",input_schema:{type:"object",properties:{mode:{type:"string",enum:["desligado","leve","profundo","nao_perturbe"],description:"Focus mode level"},duration_min:{type:"number",description:"Auto-expire after N minutes. Optional \u2014 permanent if omitted."}},required:["mode"]}},{name:"attention_status",description:"Show current attention/notification status \u2014 focus mode, pending notifications, blocked count.",input_schema:{type:"object",properties:{},required:[]}},{name:"dismiss_notifications",description:"Dismiss all pending notifications.",input_schema:{type:"object",properties:{},required:[]}}];async function xV($,Z,Y){switch($){case"open_application":return await S1(Z.name,Z.argument);case"open_file_default":return await g2(Z.path);case"open_url_browser":return await V1(Z.url);case"get_running_apps":return await Z3();case"get_system_info":return await m2();case"get_calendar_events":return await G1();case"get_news":{let Q=Z.category;return await P1(Q?[Q]:void 0)}case"create_task":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let z=Z.time,J=z?E5(z):void 0,X=X6(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=K6(Q);return z?`Concluida: "${z.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,z=s0(Q);return f2(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=E6(z);if(!X)return`Error: invalid time format "${z}". Use HH:MM.`;let K=Z.schedule_type||"once",V;if(Z.date_or_day){let H=Z.date_or_day;if(K==="weekly")V=L6(H)??void 0;else V=F6(H)??void 0}if(K==="once"&&!V){let H=new Date,[W,U]=X.split(":").map(Number),q=new Date(H);if(q.setHours(W,U,0,0),q<=H)q.setDate(q.getDate()+1);V=[String(q.getMonth()+1).padStart(2,"0"),String(q.getDate()).padStart(2,"0"),String(q.getFullYear())].join("/")}let G=await B6(Q,K,X,"toast",J,V);return`Agendamento criado: "${G.name}" [${G.id}] \u2014 ${G.scheduleType} \xE0s ${G.time}`}case"remove_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await N6(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,z=c$(Q);return l$(z)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=await O6(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 C6(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 M6(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=k6(Q,z,Z.role,Z.contact,Z.neighborhood,Z.location),K=X.neighborhood?` \u2014 Bairro: ${X.neighborhood}`:X.location?` \u2014 ${X.location}`:"";return`Pessoa adicionada: ${X.name} (${z})${K} [${X.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let z=A1(Q);if(!z)return`Pessoa nao encontrada: "${Q}"`;return v6(z)}case"list_people":{let Q=Z.group,z=f6(Q);return y6(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?hY(X):void 0;if(!QX(Q,z,J,K||void 0))return`Pessoa nao encontrada: "${Q}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${z} com ${Q}${G}`}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?hY(J):void 0,K=b6(Q,z,X||void 0);if(!K)return`Pessoa nao encontrada: "${Q}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${z}"${V} [${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=zX(Q,z,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${z}`}case"get_people_dashboard":return XX();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let z=Z.tags||[],J=u$(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 b2(d$());let z=V6(Q);return b2(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=i$(Q,z,J,X);if(!K.allowed)return`Error: ${K.blocked}`;let V=o$(Q,z,J,X);n$(Q,z,J);let G=V.type==="entrada"?"+":"-",H=r$(K);return`${G} R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description} [${V.id}]${H?`
1138
- `+H:""}`}case"financial_summary":return j6();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=o7(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 L5(T6());return L5(y2(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=b4(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=y4(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||[],V=v4(Q,z,J,X,K);if(!V)return`Investigacao nao encontrada: "${Q}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=Z.summary;if(!z?.trim())return"Error: summary is required.";let J=x4(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=_4(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return p4(z)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=m4(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return z}case"list_investigations":{let Q=Z.query;if(Q?.trim())return w6(g4(Q));let{status:z,type:J}=Z;return w6(h4(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=H6(X),V=await G6(X);return`${K}
1138
+ `)}`}function oV($){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(` ${j9[Y.type]} ${Y.title} \u2014 ${"*".repeat(Y.rating||0)}`)}if($.mostConsumed.length>0){Z.push("","Mais consumidos:");for(let Y of $.mostConsumed)Z.push(` ${j9[Y.type]} ${Y.title} (${Y.timesConsumed}x)`)}return Z.join(`
1139
+ `)}var C3=50000;function U1($){if($.length<=C3)return $;return $.slice(0,C3)+`
1140
+ ... (output truncated)`}function M3($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function dY($){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,V]of Object.entries(J))if(Z.includes(K)){let G=new Date(Y),W=(V-G.getDay()+7)%7||7;return G.setDate(G.getDate()+W),G}let X=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(X){let K=parseInt(X[1]),V=parseInt(X[2])-1,G=X[3]?parseInt(X[3])+(X[3].length===2?2000:0):Y.getFullYear(),W=new Date(G,V,K);if(!isNaN(W.getTime()))return W}return L5(Z)}var D9=[{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:[]}}],T9=[{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"]}}],I9=[{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."},neighborhood:{type:"string",description:"Linked neighborhood name or ID from Lokaliza. Optional."},location:{type:"string",description:"Free-text location (city, region). 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:[]}}],S9=[{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"]}}],w9={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"]}},k9=[{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"]}}],f9=[{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:[]}}],b9=[{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"]}}],y9=[{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"]}}],v9=[{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"]}}],x9=[{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"]}}],_9=[{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"]}}],h9=[{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"]}}],g9=[{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:[]}}],m9=[{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:[]}}],cY=[{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:[]}}],p9=[{name:"add_neighborhood",description:"Register a neighborhood for mapping. Auto-fetches coordinates and boundary polygon from OpenStreetMap. Opens it on the /map web view.",input_schema:{type:"object",properties:{name:{type:"string",description:'Neighborhood name (e.g. "Copacabana")'},city:{type:"string",description:'City (e.g. "Rio de Janeiro")'},state:{type:"string",description:'State (e.g. "RJ")'},country:{type:"string",description:"Country. Default: Brazil."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["name","city","state"]}},{name:"get_neighborhood",description:"Get detailed info about a registered neighborhood by ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Neighborhood ID or name"}},required:["reference"]}},{name:"list_neighborhoods",description:"List all registered neighborhoods.",input_schema:{type:"object",properties:{},required:[]}},{name:"remove_neighborhood",description:"Remove a registered neighborhood by ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Neighborhood ID or name"}},required:["reference"]}},{name:"search_neighborhoods",description:"Search neighborhoods by name, city, tags, or POI names.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}},{name:"add_poi",description:"Add a Point of Interest (commerce, landmark, event) to a neighborhood.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},name:{type:"string",description:"POI name"},category:{type:"string",description:'Category (e.g. "restaurante", "escola", "hospital")'},lat:{type:"number",description:"Latitude"},lng:{type:"number",description:"Longitude"},tags:{type:"array",items:{type:"string"},description:"Tags. Optional."}},required:["neighborhood","name","category","lat","lng"]}},{name:"remove_poi",description:"Remove a POI from a neighborhood.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},poi_id:{type:"string",description:"POI ID"}},required:["neighborhood","poi_id"]}},{name:"add_map_layer",description:"Add a data visualization layer to a neighborhood (heatmap, hexbin, scatter, arc, polygon, icon). Layers are rendered on the Lokaliza map view.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},name:{type:"string",description:'Layer name (e.g. "Densidade Populacional", "Crimes 2024")'},type:{type:"string",enum:["heatmap","hexbin","scatter","arc","polygon","icon"],description:"Visualization type"},color:{type:"string",description:"Hex color. Default: #00ffcc"},points:{type:"array",items:{type:"object",properties:{lat:{type:"number"},lng:{type:"number"},value:{type:"number",description:"Numeric value for heatmap/hexbin intensity"},label:{type:"string",description:"Optional label"}},required:["lat","lng"]},description:"Data points for the layer. Optional \u2014 can add later with add_layer_points."}},required:["neighborhood","name","type"]}},{name:"add_layer_points",description:"Add data points to an existing map layer.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},layer_id:{type:"string",description:"Layer ID"},points:{type:"array",items:{type:"object",properties:{lat:{type:"number"},lng:{type:"number"},value:{type:"number"},label:{type:"string"}},required:["lat","lng"]},description:"Data points to add"}},required:["neighborhood","layer_id","points"]}},{name:"toggle_layer",description:"Toggle visibility of a data layer on the map.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},layer_id:{type:"string",description:"Layer ID"}},required:["neighborhood","layer_id"]}},{name:"remove_layer",description:"Remove a data layer from a neighborhood.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},layer_id:{type:"string",description:"Layer ID"}},required:["neighborhood","layer_id"]}},{name:"open_map",description:"Open the Lokaliza map in the default browser. "+"Automatically resolves the correct URL \u2014 no port needed.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Optional: fly to this neighborhood on open."}},required:[]}},{name:"analyze_neighborhood",description:"Run autonomous multi-step analysis on a neighborhood. Auto-enriches with POIs if not done, generates category breakdown, creates density layers, and produces a structured intelligence report. The report is auto-saved as a memo.",input_schema:{type:"object",properties:{neighborhood:{type:"string",description:"Neighborhood ID or name"},focus:{type:"string",enum:["infraestrutura","seguranca","educacao","saude","comercio","transporte","geral"],description:"Analysis focus area. Default: geral (all areas)."}},required:["neighborhood"]}},{name:"get_regional_news",description:"Fetch news filtered by the state/region of registered neighborhoods. Automatically uses regional feeds based on Lokaliza data.",input_schema:{type:"object",properties:{state:{type:"string",description:'State code (e.g. "SP", "RJ"). If omitted, uses all registered neighborhoods.'}},required:[]}}],u9=[{name:"check_energy",description:"Check current energy level, cognitive load score, work phase, and get a smart suggestion. Call this proactively when the user seems tired, before complex tasks, or periodically.",input_schema:{type:"object",properties:{},required:[]}},{name:"take_break",description:"Record that the user is taking a break. Resets the work streak timer. Call when the user says they are pausing, going for coffee, stretching, etc.",input_schema:{type:"object",properties:{},required:[]}},{name:"energy_profile",description:"Show the user's learned energy profile \u2014 best hours, avg session duration, "+"weekly energy patterns. Based on historical data.",input_schema:{type:"object",properties:{},required:[]}},{name:"set_focus",description:"Set focus/attention mode to filter notifications. Modes: desligado (all notifications), leve (no noise), profundo (only urgent+important), nao_perturbe (only urgent). Optional duration in minutes.",input_schema:{type:"object",properties:{mode:{type:"string",enum:["desligado","leve","profundo","nao_perturbe"],description:"Focus mode level"},duration_min:{type:"number",description:"Auto-expire after N minutes. Optional \u2014 permanent if omitted."}},required:["mode"]}},{name:"attention_status",description:"Show current attention/notification status \u2014 focus mode, pending notifications, blocked count.",input_schema:{type:"object",properties:{},required:[]}},{name:"dismiss_notifications",description:"Dismiss all pending notifications.",input_schema:{type:"object",properties:{},required:[]}}];async function nV($,Z,Y){switch($){case"open_application":return await f1(Z.name,Z.argument);case"open_file_default":return await p2(Z.path);case"open_url_browser":return await W1(Z.url);case"get_running_apps":return await Q3();case"get_system_info":return await u2();case"get_calendar_events":return await H1();case"get_news":{let Q=Z.category;return await D1(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?L5(z):void 0,X=W6(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=H6(Q);return z?`Concluida: "${z.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,z=$1(Q);return y2(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=j6(z);if(!X)return`Error: invalid time format "${z}". Use HH:MM.`;let K=Z.schedule_type||"once",V;if(Z.date_or_day){let W=Z.date_or_day;if(K==="weekly")V=A6(W)??void 0;else V=P6(W)??void 0}if(K==="once"&&!V){let W=new Date,[H,U]=X.split(":").map(Number),q=new Date(W);if(q.setHours(H,U,0,0),q<=W)q.setDate(q.getDate()+1);V=[String(q.getMonth()+1).padStart(2,"0"),String(q.getDate()).padStart(2,"0"),String(q.getFullYear())].join("/")}let G=await M6(Q,K,X,"toast",J,V);return`Agendamento criado: "${G.name}" [${G.id}] \u2014 ${G.scheduleType} \xE0s ${G.time}`}case"remove_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await E6(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,z=o$(Q);return i$(z)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=await F6(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 L6(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 R6(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=v6(Q,z,Z.role,Z.contact,Z.neighborhood,Z.location),K=X.neighborhood?` \u2014 Bairro: ${X.neighborhood}`:X.location?` \u2014 ${X.location}`:"";return`Pessoa adicionada: ${X.name} (${z})${K} [${X.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let z=T1(Q);if(!z)return`Pessoa nao encontrada: "${Q}"`;return g6(z)}case"list_people":{let Q=Z.group,z=x6(Q);return h6(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?dY(X):void 0;if(!NX(Q,z,J,K||void 0))return`Pessoa nao encontrada: "${Q}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${z} com ${Q}${G}`}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?dY(J):void 0,K=_6(Q,z,X||void 0);if(!K)return`Pessoa nao encontrada: "${Q}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${z}"${V} [${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=OX(Q,z,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${z}`}case"get_people_dashboard":return MX();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let z=Z.tags||[],J=c$(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 v2(l$());let z=U6(Q);return v2(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=r$(Q,z,J,X);if(!K.allowed)return`Error: ${K.blocked}`;let V=n$(Q,z,J,X);a$(Q,z,J);let G=V.type==="entrada"?"+":"-",W=s$(K);return`${G} R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description} [${V.id}]${W?`
1141
+ `+W:""}`}case"financial_summary":return T6();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=zX(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 j5(k6());return j5(x2(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=h4(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=g4(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||[],V=m4(Q,z,J,X,K);if(!V)return`Investigacao nao encontrada: "${Q}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=Z.summary;if(!z?.trim())return"Error: summary is required.";let J=p4(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=u4(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return o4(z)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let z=l4(Q);if(!z)return`Investigacao nao encontrada: "${Q}"`;return z}case"list_investigations":{let Q=Z.query;if(Q?.trim())return b6(c4(Q));let{status:z,type:J}=Z;return b6(d4(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=B6(X),V=await q6(X);return`${K}
1139
1142
 
1140
- ${V}`}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=h6(Q,z,J,X),V=K.tags.length>0?` [${K.tags.map((G)=>"#"+G).join(" ")}]`:"";return`Material salvo: "${K.title}" (${K.category})${V} {${K.id}}`}case"search_materials":{let Q=Z.query;if(!Q?.trim())return $2(P5());let z=j5(Q);return $2(z)}case"list_materials":{let Q=Z.category,z=Z.limit||30,J=P5(z,Q);return $2(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=WX(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 g6(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=xY(Q);if(z.blocked)return`BLOCKED: ${z.reason}
1141
- Esse tipo de operacao nao e permitido.`;if(!z.safe&&z.reason);let J=await q3(Q),X=[];if(J.stdout.trim())X.push(`stdout:
1143
+ ${V}`}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=u6(Q,z,J,X),V=K.tags.length>0?` [${K.tags.map((G)=>"#"+G).join(" ")}]`:"";return`Material salvo: "${K.title}" (${K.category})${V} {${K.id}}`}case"search_materials":{let Q=Z.query;if(!Q?.trim())return Y2(D5());let z=A5(Q);return Y2(z)}case"list_materials":{let Q=Z.category,z=Z.limit||30,J=D5(z,Q);return Y2(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=jX(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 d6(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=pY(Q);if(z.blocked)return`BLOCKED: ${z.reason}
1144
+ Esse tipo de operacao nao e permitido.`;if(!z.safe&&z.reason);let J=await N3(Q),X=[];if(J.stdout.trim())X.push(`stdout:
1142
1145
  ${J.stdout.trim()}`);if(J.stderr.trim())X.push(`stderr:
1143
1146
  ${J.stderr.trim()}`);return X.push(`exit: ${J.exitCode} (${J.duration}ms)`),X.join(`
1144
1147
 
1145
- `)}case"analyze_screen_context":return await M9();case"read_clipboard_content":{let Q=await C9();switch(Q.type){case"text":return`Clipboard (texto):
1146
- ${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 LV(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 z6();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=p$(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 Z6(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 Y6(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 Q6(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=s6(process.cwd());if(!J)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return T5(J.id),`Projeto ativo: "${J.name}" (${J.path}) \u2014 auto-detectado [${J.id}]`}let z=T5(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 G=Y2();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=G.id}let V=await o6(K,z,J);if(!V)return`Projeto nao encontrado: "${K}"`;if(X)return yC(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
1148
+ `)}case"analyze_screen_context":return await R9();case"read_clipboard_content":{let Q=await L9();switch(Q.type){case"text":return`Clipboard (texto):
1149
+ ${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 bV(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 V6();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=d$(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 J6(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 X6(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 K6(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=Z9(process.cwd());if(!J)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return S5(J.id),`Projeto ativo: "${J.name}" (${J.path}) \u2014 auto-detectado [${J.id}]`}let z=S5(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 G=z2();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=G.id}let V=await a6(K,z,J);if(!V)return`Projeto nao encontrado: "${K}"`;if(X)return sC(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
1147
1150
 
1148
- ${V.markdown}`;return V.markdown}case"manage_work_session":{let Q=Z.action,z=Z.notes||"",J=Y2();if(!J)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=d6(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=Q2(J.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=c6(X.id,z);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${J.name}".`}case"status":{let X=Q2(J.id);if(!X)return`Nenhuma sessao aberta para "${J.name}".`;let K=new Date(X.startedAt),V=Math.round((Date.now()-K.getTime())/60000);return`Sessao aberta: "${J.name}" \u2014 ${V} minutos (desde ${K.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let z=Z.path;if(!z?.trim())return"Error: path is required.";let J=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],V=r4(Q,z,J,K,X);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let Q=Z.active_only||!1;return i6(D5(Q))}case"fetch_opportunities":{let{status:Q,tech:z}=Z,J=l6(Q,z);return r6(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",V=Z.deadline||null,G=jX(Q,z,J,X,K,V);return`Oportunidade registrada: "${G.title}" (${G.priority}) [${G.id}]`}case"update_opportunity_status":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=Z.status,J=PX(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,V=await $Y(Q,{scriptKey:z,cwd:K,iterations:J,warmup:X});if(V.exitCode!==0){let G=YY(V);return`AVISO: Comando terminou com exit code ${V.exitCode}. Metricas podem nao ser confiaveis.
1151
+ ${V.markdown}`;return V.markdown}case"manage_work_session":{let Q=Z.action,z=Z.notes||"",J=z2();if(!J)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=i6(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=J2(J.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=n6(X.id,z);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${J.name}".`}case"status":{let X=J2(J.id);if(!X)return`Nenhuma sessao aberta para "${J.name}".`;let K=new Date(X.startedAt),V=Math.round((Date.now()-K.getTime())/60000);return`Sessao aberta: "${J.name}" \u2014 ${V} minutos (desde ${K.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let z=Z.path;if(!z?.trim())return"Error: path is required.";let J=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],V=$Y(Q,z,J,K,X);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let Q=Z.active_only||!1;return s6(I5(Q))}case"fetch_opportunities":{let{status:Q,tech:z}=Z,J=r6(Q,z);return e6(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",V=Z.deadline||null,G=vX(Q,z,J,X,K,V);return`Oportunidade registrada: "${G.title}" (${G.priority}) [${G.id}]`}case"update_opportunity_status":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=Z.status,J=xX(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,V=await JY(Q,{scriptKey:z,cwd:K,iterations:J,warmup:X});if(V.exitCode!==0){let G=KY(V);return`AVISO: Comando terminou com exit code ${V.exitCode}. Metricas podem nao ser confiaveis.
1149
1152
 
1150
- ${G.markdown}`}return YY(V).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,V=Z.cwd,G=await $Y(Q,{scriptKey:z,cwd:V,iterations:J,warmup:!0});if(G.exitCode!==0)return`Error: Comando falhou (exit code ${G.exitCode}). Corrija o comando antes de salvar baseline.
1151
- `+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let H=K?yX(G,X):fX(G,X),W=H.metrics.durationNs/1e6;return`Baseline salvo: "${H.scriptKey}" (${H.runs} run${H.runs>1?"s":""})
1152
- Duracao: ${W.toFixed(2)}ms
1153
- Memoria: ${(H.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
1154
- CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return xX(bX());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return ZY(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=L9(Z.project_dir||process.cwd()),J=L9(z,Q);if(!J.startsWith(z+vV))return"Error: file must be inside project_dir.";try{let X=zY(z),K=JY(X,J);return uX(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=L9(Z.project_dir||process.cwd()),J=L9(z,Q);if(!J.startsWith(z+vV))return"Error: file must be inside project_dir.";try{let X=zY(z),K=pX(X,J);return cX(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"):"",V=X?`${X.messageCount} msgs`:"";return` ${J.padEnd(20)} ${V.padEnd(10)} ${K}`});return`Sessoes arquivadas (${Q.length}):
1153
+ ${G.markdown}`}return KY(V).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,V=Z.cwd,G=await JY(Q,{scriptKey:z,cwd:V,iterations:J,warmup:!0});if(G.exitCode!==0)return`Error: Comando falhou (exit code ${G.exitCode}). Corrija o comando antes de salvar baseline.
1154
+ `+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let W=K?oX(G,X):cX(G,X),H=W.metrics.durationNs/1e6;return`Baseline salvo: "${W.scriptKey}" (${W.runs} run${W.runs>1?"s":""})
1155
+ Duracao: ${H.toFixed(2)}ms
1156
+ Memoria: ${(W.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
1157
+ CPU (user): ${(W.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return nX(lX());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return XY(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=A9(Z.project_dir||process.cwd()),J=A9(z,Q);if(!J.startsWith(z+iV))return"Error: file must be inside project_dir.";try{let X=GY(z),K=WY(X,J);return $K(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=A9(Z.project_dir||process.cwd()),J=A9(z,Q);if(!J.startsWith(z+iV))return"Error: file must be inside project_dir.";try{let X=GY(z),K=eX(X,J);return YK(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"):"",V=X?`${X.messageCount} msgs`:"";return` ${J.padEnd(20)} ${V.padEnd(10)} ${K}`});return`Sessoes arquivadas (${Q.length}):
1155
1158
  ${z.join(`
1156
- `)}`}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((W)=>({name:W.name.trim(),description:W.description.trim(),scores:W.scores,pros:W.pros||[],cons:W.cons||[]})),V=Z.custom_criteria,G=V&&V.length>0?V:KY;return sX(X,K,G).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let z=Z.stacktrace;return tX(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=eX(Q,z,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
1159
+ `)}`}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((H)=>({name:H.name.trim(),description:H.description.trim(),scores:H.scores,pros:H.pros||[],cons:H.cons||[]})),V=Z.custom_criteria,G=V&&V.length>0?V:UY;return GK(X,K,G).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let z=Z.stacktrace;return WK(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=HK(Q,z,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
1157
1160
  Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
1158
- Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,z=Z.query,J=z?QK(z).slice(0,Q):YK(Q);return JK(J)}case"list_incidents":{let Q=Z.limit||10,z=Z.query,J=z?$K(z).slice(0,Q):ZK(Q);return XK(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=zK(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 CK(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})
1159
- Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return MK(Q)}case"trigger_self_reflection":{let Q=await w5();return LK(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),z=OK(Q);return RK(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||[],V=Z.moods||[],G=Z.url,H=DV(Q,J,X,K,V,G),W=H.moods.length>0?` (${H.moods.join(", ")})`:"",U=H.tags.length>0?` [${H.tags.map((q)=>"#"+q).join(" ")}]`:"";return`Conteudo adicionado: "${H.title}" \u2014 ${H.creator}${W}${U} {${H.id}}`}case"get_recommendations":{let{mood:Q,type:z}=Z,J=Math.min(Math.max(Z.limit||5,1),20),X=kV(Q,z,J);return bV(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=TV(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=IV(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 F9(_Y());let z=SV(Q),J=Z.type;if(J)z=z.filter((X)=>X.type===J);return F9(z)}case"list_catalog":{let Q=Z.type,z=Math.min(Math.max(Z.limit||20,1),100);return F9(_Y(Q,z))}case"remove_content":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";return wV(Q)?"Conteudo removido do catalogo.":`Conteudo nao encontrado: "${Q}"`}case"content_stats":return yV(fV());case"add_neighborhood":{let{name:Q,city:z,state:J}=Z;if(!Q?.trim()||!z?.trim()||!J?.trim())return"Error: name, city, and state are required.";let X=Z.country||"Brazil",K=Z.tags||[],V=await iK(Q,z,J,X,K),G=V.center.lat!==0,H=!!V.boundary,W=V.pois.length,U=V.layers.length,q=V.metadata?.poiBreakdown,N=q?Object.entries(q).map(([C,M])=>`${C}: ${M}`).join(", "):"";return[`Bairro registrado: "${V.name}" \u2014 ${V.city}/${V.state} [${V.id}]`,G?`\uD83D\uDCCD ${V.center.lat.toFixed(6)}, ${V.center.lng.toFixed(6)}`:"\u26A0\uFE0F Coordenadas nao encontradas",H?"\uD83D\uDCD0 Limite poligonal obtido":"\uD83D\uDCD0 Sem limite poligonal",W>0?`\uD83D\uDCCA Auto-enriquecido: ${W} POIs encontrados (${N})`:"",U>0?`\uD83D\uDDC2\uFE0F ${U} camada(s) de dados criada(s) automaticamente`:"",`
1160
- \uD83D\uDDFA\uFE0F Abra ${SY()} para visualizar no mapa.`].filter(Boolean).join(`
1161
- `)}case"get_neighborhood":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=k1(Q);if(!z)return`Bairro nao encontrado: "${Q}"`;return QV(z)}case"list_neighborhoods":{let Q=t0();return YV(Q)}case"remove_neighborhood":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return nK(Q)?`Bairro removido: "${Q}"`:`Bairro nao encontrado: "${Q}"`}case"search_neighborhoods":{let Q=Z.query;if(!Q?.trim())return"Error: query is required.";let z=rK(Q);if(!z.length)return`Nenhum bairro encontrado para "${Q}"`;return z.map((J)=>`\u2022 ${J.neighborhood.name} \u2014 ${J.neighborhood.city}/${J.neighborhood.state} (score: ${J.score}) [${J.neighborhood.id}]`).join(`
1162
- `)}case"add_poi":{let{neighborhood:Q,name:z,category:J,lat:X,lng:K}=Z;if(!Q||!z||!J||X==null||K==null)return"Error: neighborhood, name, category, lat, lng are required.";let V=Z.tags||[],G=aK(Q,z,J,X,K,V);if(!G)return`Bairro nao encontrado: "${Q}"`;return`POI adicionado: "${G.name}" (${G.category}) at ${X.toFixed(4)}, ${K.toFixed(4)} [${G.id}]`}case"remove_poi":{let{neighborhood:Q,poi_id:z}=Z;if(!Q||!z)return"Error: neighborhood and poi_id are required.";return sK(Q,z)?`POI removido: ${z}`:"POI nao encontrado."}case"add_map_layer":{let{neighborhood:Q,name:z,type:J}=Z;if(!Q||!z||!J)return"Error: neighborhood, name, type are required.";let X=Z.color||"#00ffcc",K=Z.points||[],V=tK(Q,z,J,X,K);if(!V)return`Bairro nao encontrado: "${Q}"`;return`Layer adicionada: "${V.name}" (${V.type}) \u2014 ${V.points.length} pontos [${V.id}]`}case"add_layer_points":{let{neighborhood:Q,layer_id:z,points:J}=Z;if(!Q||!z||!J?.length)return"Error: neighborhood, layer_id, points are required.";return eK(Q,z,J)?`${J.length} pontos adicionados.`:"Layer ou bairro nao encontrado."}case"toggle_layer":{let{neighborhood:Q,layer_id:z}=Z;if(!Q||!z)return"Error: neighborhood and layer_id are required.";return $V(Q,z)?"Visibilidade alternada.":"Layer ou bairro nao encontrado."}case"remove_layer":{let{neighborhood:Q,layer_id:z}=Z;if(!Q||!z)return"Error: neighborhood and layer_id are required.";return ZV(Q,z)?`Layer removida: ${z}`:"Layer ou bairro nao encontrado."}case"open_map":{if(!JV())q9();let Q=SY(),z=Z.neighborhood,J=z?`${Q}#${encodeURIComponent(z)}`:Q;return await V1(J),`Mapa aberto: ${J}`}case"analyze_neighborhood":{let Q=Z.neighborhood;if(!Q?.trim())return"Error: neighborhood is required.";let z=k1(Q);if(!z)return`Bairro nao encontrado: "${Q}"`;let J=Z.focus||"geral",X=new Map;for(let q of z.pois)X.set(q.category,(X.get(q.category)??0)+1);let V={infraestrutura:["escola","hospital","posto de saude","delegacia","bombeiros","banco"],seguranca:["delegacia","bombeiros"],educacao:["escola"],saude:["hospital","posto de saude","farmacia"],comercio:["supermercado","banco"],transporte:["estacao de trem","ponto de onibus"],geral:[]}[J]??[],G=V.length>0?z.pois.filter((q)=>V.includes(q.category)):z.pois,H=[`# Relatorio de Inteligencia \u2014 ${z.name}`,`\uD83D\uDCCD ${z.city}/${z.state} | Foco: ${J}`,`\uD83D\uDCC5 ${new Date().toLocaleDateString("pt-BR")}`,"","## Resumo",`- Total de POIs: ${z.pois.length}`,`- Camadas de dados: ${z.layers.length}`,`- Limite poligonal: ${z.boundary?"Disponivel":"Indisponivel"}`,z.tags.length?`- Tags: ${z.tags.join(", ")}`:"","","## Distribuicao por Categoria",...[...X.entries()].sort((q,N)=>N[1]-q[1]).map(([q,N])=>` \u2022 ${q}: ${N}`),""];if(J!=="geral"){if(H.push(`## Analise: ${J.charAt(0).toUpperCase()+J.slice(1)}`),G.length===0)H.push(` Nenhum POI encontrado para a categoria "${J}".`);else{H.push(` ${G.length} ponto(s) relevante(s):`);for(let q of G.slice(0,20)){let N=q.metadata?.["addr:street"]||"";H.push(` \u2022 ${q.name}${N?` \u2014 ${N}`:""} (${q.position.lat.toFixed(4)}, ${q.position.lng.toFixed(4)})`)}}H.push("")}let W=Math.min(10,Math.round((X.get("escola")??0)*1.5+(X.get("hospital")??0)*2+(X.get("posto de saude")??0)*1.5+(X.get("farmacia")??0)*0.5+(X.get("delegacia")??0)*1+(X.get("estacao de trem")??0)*2+(X.get("ponto de onibus")??0)*0.3+(X.get("supermercado")??0)*0.5+(X.get("banco")??0)*0.5+(X.get("parque")??0)*0.5));H.push("## Indice de Infraestrutura"),H.push(` Score: ${W}/10`),H.push(` ${W>=7?"Boa cobertura":W>=4?"Cobertura moderada":"Cobertura insuficiente"}`),H.push("");let U=H.filter(Boolean).join(`
1163
- `);return u$(U,["lokaliza",z.name.toLowerCase(),J,"analise"]),U+`
1161
+ Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,z=Z.query,J=z?NK(z).slice(0,Q):BK(Q);return CK(J)}case"list_incidents":{let Q=Z.limit||10,z=Z.query,J=z?UK(z).slice(0,Q):qK(Q);return MK(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let z=OK(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 SK(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})
1162
+ Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return wK(Q)}case"trigger_self_reflection":{let Q=await k5();return bK(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),z=IK(Q);return yK(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||[],V=Z.moods||[],G=Z.url,W=hV(Q,J,X,K,V,G),H=W.moods.length>0?` (${W.moods.join(", ")})`:"",U=W.tags.length>0?` [${W.tags.map((q)=>"#"+q).join(" ")}]`:"";return`Conteudo adicionado: "${W.title}" \u2014 ${W.creator}${H}${U} {${W.id}}`}case"get_recommendations":{let{mood:Q,type:z}=Z,J=Math.min(Math.max(Z.limit||5,1),20),X=dV(Q,z,J);return lV(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=gV(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=mV(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 P9(uY());let z=uV(Q),J=Z.type;if(J)z=z.filter((X)=>X.type===J);return P9(z)}case"list_catalog":{let Q=Z.type,z=Math.min(Math.max(Z.limit||20,1),100);return P9(uY(Q,z))}case"remove_content":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";return pV(Q)?"Conteudo removido do catalogo.":`Conteudo nao encontrado: "${Q}"`}case"content_stats":return oV(cV());case"add_neighborhood":{let{name:Q,city:z,state:J}=Z;if(!Q?.trim()||!z?.trim()||!J?.trim())return"Error: name, city, and state are required.";let X=Z.country||"Brazil",K=Z.tags||[],V=await JV(Q,z,J,X,K),G=V.center.lat!==0,W=!!V.boundary,H=V.pois.length,U=V.layers.length,q=V.metadata?.poiBreakdown,N=q?Object.entries(q).map(([C,M])=>`${C}: ${M}`).join(", "):"";return[`Bairro registrado: "${V.name}" \u2014 ${V.city}/${V.state} [${V.id}]`,G?`\uD83D\uDCCD ${V.center.lat.toFixed(6)}, ${V.center.lng.toFixed(6)}`:"\u26A0\uFE0F Coordenadas nao encontradas",W?"\uD83D\uDCD0 Limite poligonal obtido":"\uD83D\uDCD0 Sem limite poligonal",H>0?`\uD83D\uDCCA Auto-enriquecido: ${H} POIs encontrados (${N})`:"",U>0?`\uD83D\uDDC2\uFE0F ${U} camada(s) de dados criada(s) automaticamente`:"",`
1163
+ \uD83D\uDDFA\uFE0F Abra ${vY()} para visualizar no mapa.`].filter(Boolean).join(`
1164
+ `)}case"get_neighborhood":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let z=b1(Q);if(!z)return`Bairro nao encontrado: "${Q}"`;return NV(z)}case"list_neighborhoods":{let Q=Z1();return BV(Q)}case"remove_neighborhood":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return XV(Q)?`Bairro removido: "${Q}"`:`Bairro nao encontrado: "${Q}"`}case"search_neighborhoods":{let Q=Z.query;if(!Q?.trim())return"Error: query is required.";let z=KV(Q);if(!z.length)return`Nenhum bairro encontrado para "${Q}"`;return z.map((J)=>`\u2022 ${J.neighborhood.name} \u2014 ${J.neighborhood.city}/${J.neighborhood.state} (score: ${J.score}) [${J.neighborhood.id}]`).join(`
1165
+ `)}case"add_poi":{let{neighborhood:Q,name:z,category:J,lat:X,lng:K}=Z;if(!Q||!z||!J||X==null||K==null)return"Error: neighborhood, name, category, lat, lng are required.";let V=Z.tags||[],G=VV(Q,z,J,X,K,V);if(!G)return`Bairro nao encontrado: "${Q}"`;return`POI adicionado: "${G.name}" (${G.category}) at ${X.toFixed(4)}, ${K.toFixed(4)} [${G.id}]`}case"remove_poi":{let{neighborhood:Q,poi_id:z}=Z;if(!Q||!z)return"Error: neighborhood and poi_id are required.";return GV(Q,z)?`POI removido: ${z}`:"POI nao encontrado."}case"add_map_layer":{let{neighborhood:Q,name:z,type:J}=Z;if(!Q||!z||!J)return"Error: neighborhood, name, type are required.";let X=Z.color||"#00ffcc",K=Z.points||[],V=WV(Q,z,J,X,K);if(!V)return`Bairro nao encontrado: "${Q}"`;return`Layer adicionada: "${V.name}" (${V.type}) \u2014 ${V.points.length} pontos [${V.id}]`}case"add_layer_points":{let{neighborhood:Q,layer_id:z,points:J}=Z;if(!Q||!z||!J?.length)return"Error: neighborhood, layer_id, points are required.";return HV(Q,z,J)?`${J.length} pontos adicionados.`:"Layer ou bairro nao encontrado."}case"toggle_layer":{let{neighborhood:Q,layer_id:z}=Z;if(!Q||!z)return"Error: neighborhood and layer_id are required.";return UV(Q,z)?"Visibilidade alternada.":"Layer ou bairro nao encontrado."}case"remove_layer":{let{neighborhood:Q,layer_id:z}=Z;if(!Q||!z)return"Error: neighborhood and layer_id are required.";return qV(Q,z)?`Layer removida: ${z}`:"Layer ou bairro nao encontrado."}case"open_map":{if(!CV())C9();let Q=vY(),z=Z.neighborhood,J=z?`${Q}#${encodeURIComponent(z)}`:Q;return await W1(J),`Mapa aberto: ${J}`}case"analyze_neighborhood":{let Q=Z.neighborhood;if(!Q?.trim())return"Error: neighborhood is required.";let z=b1(Q);if(!z)return`Bairro nao encontrado: "${Q}"`;let J=Z.focus||"geral",X=new Map;for(let q of z.pois)X.set(q.category,(X.get(q.category)??0)+1);let V={infraestrutura:["escola","hospital","posto de saude","delegacia","bombeiros","banco"],seguranca:["delegacia","bombeiros"],educacao:["escola"],saude:["hospital","posto de saude","farmacia"],comercio:["supermercado","banco"],transporte:["estacao de trem","ponto de onibus"],geral:[]}[J]??[],G=V.length>0?z.pois.filter((q)=>V.includes(q.category)):z.pois,W=[`# Relatorio de Inteligencia \u2014 ${z.name}`,`\uD83D\uDCCD ${z.city}/${z.state} | Foco: ${J}`,`\uD83D\uDCC5 ${new Date().toLocaleDateString("pt-BR")}`,"","## Resumo",`- Total de POIs: ${z.pois.length}`,`- Camadas de dados: ${z.layers.length}`,`- Limite poligonal: ${z.boundary?"Disponivel":"Indisponivel"}`,z.tags.length?`- Tags: ${z.tags.join(", ")}`:"","","## Distribuicao por Categoria",...[...X.entries()].sort((q,N)=>N[1]-q[1]).map(([q,N])=>` \u2022 ${q}: ${N}`),""];if(J!=="geral"){if(W.push(`## Analise: ${J.charAt(0).toUpperCase()+J.slice(1)}`),G.length===0)W.push(` Nenhum POI encontrado para a categoria "${J}".`);else{W.push(` ${G.length} ponto(s) relevante(s):`);for(let q of G.slice(0,20)){let N=q.metadata?.["addr:street"]||"";W.push(` \u2022 ${q.name}${N?` \u2014 ${N}`:""} (${q.position.lat.toFixed(4)}, ${q.position.lng.toFixed(4)})`)}}W.push("")}let H=Math.min(10,Math.round((X.get("escola")??0)*1.5+(X.get("hospital")??0)*2+(X.get("posto de saude")??0)*1.5+(X.get("farmacia")??0)*0.5+(X.get("delegacia")??0)*1+(X.get("estacao de trem")??0)*2+(X.get("ponto de onibus")??0)*0.3+(X.get("supermercado")??0)*0.5+(X.get("banco")??0)*0.5+(X.get("parque")??0)*0.5));W.push("## Indice de Infraestrutura"),W.push(` Score: ${H}/10`),W.push(` ${H>=7?"Boa cobertura":H>=4?"Cobertura moderada":"Cobertura insuficiente"}`),W.push("");let U=W.filter(Boolean).join(`
1166
+ `);return c$(U,["lokaliza",z.name.toLowerCase(),J,"analise"]),U+`
1164
1167
 
1165
- \uD83D\uDCDD Relatorio salvo como memo (tags: lokaliza, ${z.name.toLowerCase()}, ${J}, analise)`}case"get_regional_news":{let Q=Z.state;if(Q)return await E4(Q);let z=t0();if(!z.length)return"Nenhum bairro cadastrado. Adicione bairros primeiro.";let J=[...new Set(z.map((K)=>K.state))],X=[];for(let K of J){let V=await E4(K,2);X.push(V)}return X.join(`
1168
+ \uD83D\uDCDD Relatorio salvo como memo (tags: lokaliza, ${z.name.toLowerCase()}, ${J}, analise)`}case"get_regional_news":{let Q=Z.state;if(Q)return await P4(Q);let z=Z1();if(!z.length)return"Nenhum bairro cadastrado. Adicione bairros primeiro.";let J=[...new Set(z.map((K)=>K.state))],X=[];for(let K of J){let V=await P4(K,2);X.push(V)}return X.join(`
1166
1169
 
1167
- `)}case"check_energy":{GV();let Q=l2();return N9(Q)}case"take_break":return HV(),"Pausa registrada! Aproveite para descansar. O streak foi reiniciado.";case"energy_profile":return WV();case"set_focus":{let Q=Z.mode;if(!["desligado","leve","profundo","nao_perturbe"].includes(Q))return"Error: modo invalido.";let J=Z.duration_min;return OV(Q,J)}case"attention_status":return EV();case"dismiss_notifications":{let Q=MV();return Q>0?`${Q} notificacao(oes) dispensada(s).`:"Nenhuma notificacao pendente."}default:return null}}h();var g9=[{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 _V($,Z){switch($){case"vault_status":{if(!i5())return"Vault nao inicializado.";return N8(B8())}case"vault_backup":{if(!i5())return"Vault nao inicializado.";let Y=Z.message||void 0;return await Q5(Y)}case"sync_cloud_context":{if(!i5())return"Vault nao inicializado.";return await C8()}case"vault_init_backup":{if(!i5())return"Vault nao inicializado.";return await O8()}default:return null}}h();import{existsSync as i2,mkdirSync as vC,readFileSync as k5,readdirSync as xC}from"fs";import{join as o2}from"path";import{createHash as _C}from"crypto";var mV=1,mY=400,hC=80,hV=1.5,gV=0.75,gC=10,mC=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"]),C3="",m9="",N0=[],f1={},b1=0,y1={},p9=!1,uY=()=>o2(m9,"rag-index.json");function pV($){if(C3=$,m9=o2($,"rag"),!i2(m9))vC(m9,{recursive:!0});iC(),p9=!0}function u9(){return p9}function d9(){return{chunks:N0.length,sources:Object.keys(y1).length,builtAt:N0.length>0?nC()?.builtAt??null:null}}function c9(){if(!p9)throw Error("Memory not initialized. Call initMemory() first.");let $=cC(),Z=0,Y=0,Q={},z=new Set;for(let[X,K]of Object.entries($)){let V=rC(K);if(Q[X]=V,y1[X]!==V)z.add(X)}let J=Object.keys(y1).filter((X)=>!(X in $));if(z.size===0&&J.length===0)return{indexed:0,skipped:Object.keys($).length,total:N0.length};N0=N0.filter((X)=>{let K=`${X.source}:${X.sourceId}`;return!z.has(K)&&!J.includes(K)});for(let X of z){let K=$[X],V=X.indexOf(":");if(V===-1)continue;let G=X.slice(0,V),H=X.slice(V+1);if(!["memo","material","session","decision"].includes(G))continue;let U=aC(G,H,K),q=dC(K,G,H,U);N0=[...N0,...q],Z++}return Y=Object.keys($).length-Z,lC(),y1=Q,oC(),{indexed:Z,skipped:Y,total:N0.length}}function l9($,Z=3){if(N0.length===0)return[];let Y=pY($);if(Y.length===0)return[];return N0.map((z)=>{let J=pC(Y,z),X=uC(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,gC))}function o9($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let z=sC(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}%)
1170
+ `)}case"check_energy":{LV();let Q=i2();return E9(Q)}case"take_break":return RV(),"Pausa registrada! Aproveite para descansar. O streak foi reiniciado.";case"energy_profile":return jV();case"set_focus":{let Q=Z.mode;if(!["desligado","leve","profundo","nao_perturbe"].includes(Q))return"Error: modo invalido.";let J=Z.duration_min;return IV(Q,J)}case"attention_status":return kV();case"dismiss_notifications":{let Q=wV();return Q>0?`${Q} notificacao(oes) dispensada(s).`:"Nenhuma notificacao pendente."}default:return null}}g();var d9=[{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 rV($,Z){switch($){case"vault_status":{if(!r5())return"Vault nao inicializado.";return E8(M8())}case"vault_backup":{if(!r5())return"Vault nao inicializado.";let Y=Z.message||void 0;return await J5(Y)}case"sync_cloud_context":{if(!r5())return"Vault nao inicializado.";return await L8()}case"vault_init_backup":{if(!r5())return"Vault nao inicializado.";return await F8()}default:return null}}g();import{existsSync as r2,mkdirSync as tC,readFileSync as b5,readdirSync as eC}from"fs";import{join as n2}from"path";import{createHash as $M}from"crypto";var tV=1,lY=400,ZM=80,aV=1.5,sV=0.75,YM=10,QM=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"]),E3="",c9="",O0=[],y1={},v1=0,x1={},l9=!1,iY=()=>n2(c9,"rag-index.json");function eV($){if(E3=$,c9=n2($,"rag"),!r2(c9))tC(c9,{recursive:!0});WM(),l9=!0}function o9(){return l9}function i9(){return{chunks:O0.length,sources:Object.keys(x1).length,builtAt:O0.length>0?HM()?.builtAt??null:null}}function n9(){if(!l9)throw Error("Memory not initialized. Call initMemory() first.");let $=KM(),Z=0,Y=0,Q={},z=new Set;for(let[X,K]of Object.entries($)){let V=UM(K);if(Q[X]=V,x1[X]!==V)z.add(X)}let J=Object.keys(x1).filter((X)=>!(X in $));if(z.size===0&&J.length===0)return{indexed:0,skipped:Object.keys($).length,total:O0.length};O0=O0.filter((X)=>{let K=`${X.source}:${X.sourceId}`;return!z.has(K)&&!J.includes(K)});for(let X of z){let K=$[X],V=X.indexOf(":");if(V===-1)continue;let G=X.slice(0,V),W=X.slice(V+1);if(!["memo","material","session","decision"].includes(G))continue;let U=qM(G,W,K),q=XM(K,G,W,U);O0=[...O0,...q],Z++}return Y=Object.keys($).length-Z,VM(),x1=Q,GM(),{indexed:Z,skipped:Y,total:O0.length}}function r9($,Z=3){if(O0.length===0)return[];let Y=oY($);if(Y.length===0)return[];return O0.map((z)=>{let J=zM(Y,z),X=JM(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,YM))}function a9($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let z=BM(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}%)
1168
1171
  ${X}`});return`Resultados da memoria (${$.length}):
1169
1172
 
1170
1173
  ${Z.join(`
1171
1174
 
1172
- `)}`}function pC($,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=f1[J]??0;if(K===0)continue;let V=X*(hV+1),G=X+hV*(1-gV+gV*(Y/b1));z+=K*(V/G)}return z}function uC($,Z){let Y=new Map;for(let G of $)Y.set(G,(Y.get(G)??0)+1);let Q=new Map;for(let G of Z.tokens)Q.set(G,(Q.get(G)??0)+1);let z=new Set([...$,...Z.tokens]),J=0,X=0,K=0;for(let G of z){let H=f1[G]??0,W=(Y.get(G)??0)*H,U=(Q.get(G)??0)*H;J+=W*U,X+=W*W,K+=U*U}let V=Math.sqrt(X)*Math.sqrt(K);return V>0?J/V:0}function pY($){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&&!mC.has(Z))}function dC($,Z,Y,Q){let z=$.trim();if(z.length===0)return[];if(z.length<=mY)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:z,tokens:pY(z)}];let J=[],X=0,K=0;while(X<z.length){let V=Math.min(X+mY,z.length),G=z.slice(X,V);J.push({id:`${Z}:${Y}:${K}`,source:Z,sourceId:Y,title:Q,content:G,tokens:pY(G)}),X+=mY-hC,K++}return J}function cC(){let $={},Z=o2(C3,"memos.json");if(i2(Z))try{let J=JSON.parse(k5(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 V=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`memo:${K.id}`]=`${K.content}${V}`}}catch{}let Y=o2(C3,"materials.json");if(i2(Y))try{let J=JSON.parse(k5(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 V=typeof K.category==="string"?K.category:"geral",G=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`material:${K.id}`]=`${K.title}
1175
+ `)}`}function zM($,Z){let Y=Z.tokens.length;if(Y===0||v1===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=y1[J]??0;if(K===0)continue;let V=X*(aV+1),G=X+aV*(1-sV+sV*(Y/v1));z+=K*(V/G)}return z}function JM($,Z){let Y=new Map;for(let G of $)Y.set(G,(Y.get(G)??0)+1);let Q=new Map;for(let G of Z.tokens)Q.set(G,(Q.get(G)??0)+1);let z=new Set([...$,...Z.tokens]),J=0,X=0,K=0;for(let G of z){let W=y1[G]??0,H=(Y.get(G)??0)*W,U=(Q.get(G)??0)*W;J+=H*U,X+=H*H,K+=U*U}let V=Math.sqrt(X)*Math.sqrt(K);return V>0?J/V:0}function oY($){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&&!QM.has(Z))}function XM($,Z,Y,Q){let z=$.trim();if(z.length===0)return[];if(z.length<=lY)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:z,tokens:oY(z)}];let J=[],X=0,K=0;while(X<z.length){let V=Math.min(X+lY,z.length),G=z.slice(X,V);J.push({id:`${Z}:${Y}:${K}`,source:Z,sourceId:Y,title:Q,content:G,tokens:oY(G)}),X+=lY-ZM,K++}return J}function KM(){let $={},Z=n2(E3,"memos.json");if(r2(Z))try{let J=JSON.parse(b5(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 V=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`memo:${K.id}`]=`${K.content}${V}`}}catch{}let Y=n2(E3,"materials.json");if(r2(Y))try{let J=JSON.parse(b5(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 V=typeof K.category==="string"?K.category:"geral",G=Array.isArray(K.tags)&&K.tags.length>0?` [${K.tags.join(", ")}]`:"";$[`material:${K.id}`]=`${K.title}
1173
1176
  ${V}
1174
- ${K.content}${G}`}}catch{}let Q=o2(C3,"decisions.json");if(i2(Q))try{let J=JSON.parse(k5(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 V=[K.title,K.context,`Escolha: ${K.chosen}`];if(typeof K.alternatives==="string")V.push(`Alternativas: ${K.alternatives}`);if(Array.isArray(K.tags)&&K.tags.length>0)V.push(`[${K.tags.join(", ")}]`);$[`decision:${K.id}`]=V.join(`
1175
- `)}}catch{}let z=o2(C3,"sessions");if(i2(z))try{let J=xC(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=o2(z,X);try{let V=JSON.parse(k5(K,"utf-8"));if(!V||typeof V!=="object"||!Array.isArray(V.messages))continue;let G=V.messages.filter((H)=>{if(!H||typeof H!=="object")return!1;let W=H;return W.role==="assistant"&&typeof W.content==="string"&&W.content.length>50}).map((H)=>H.content).join(`
1177
+ ${K.content}${G}`}}catch{}let Q=n2(E3,"decisions.json");if(r2(Q))try{let J=JSON.parse(b5(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 V=[K.title,K.context,`Escolha: ${K.chosen}`];if(typeof K.alternatives==="string")V.push(`Alternativas: ${K.alternatives}`);if(Array.isArray(K.tags)&&K.tags.length>0)V.push(`[${K.tags.join(", ")}]`);$[`decision:${K.id}`]=V.join(`
1178
+ `)}}catch{}let z=n2(E3,"sessions");if(r2(z))try{let J=eC(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=n2(z,X);try{let V=JSON.parse(b5(K,"utf-8"));if(!V||typeof V!=="object"||!Array.isArray(V.messages))continue;let G=V.messages.filter((W)=>{if(!W||typeof W!=="object")return!1;let H=W;return H.role==="assistant"&&typeof H.content==="string"&&H.content.length>50}).map((W)=>W.content).join(`
1176
1179
  ---
1177
- `);if(G.length>0)$[`session:${V.id}`]=G}catch{}}}catch{}return $}function lC(){let $=N0.length;if($===0){f1={},b1=0;return}let Z=new Map,Y=0;for(let z of N0){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);f1=Q}function oC(){if(!p9)return;let $={chunks:N0,idf:f1,avgDocLength:b1,sourceHashes:y1,builtAt:new Date().toISOString(),version:mV};P(uY(),JSON.stringify($))}function iC(){let $=uY();if(!i2($)){N0=[],f1={},b1=0,y1={};return}try{let Z=JSON.parse(k5($,"utf-8"));if(Z.version!==mV){N0=[],f1={},b1=0,y1={};return}N0=Z.chunks,f1=Z.idf,b1=Z.avgDocLength,y1=Z.sourceHashes}catch{N0=[],f1={},b1=0,y1={}}}function nC(){let $=uY();if(!i2($))return null;try{return{builtAt:JSON.parse(k5($,"utf-8")).builtAt}}catch{return null}}function rC($){return _C("sha256").update($).digest("hex").slice(0,16)}function aC($,Z,Y){switch($){case"material":{let Q=Y.split(`
1180
+ `);if(G.length>0)$[`session:${V.id}`]=G}catch{}}}catch{}return $}function VM(){let $=O0.length;if($===0){y1={},v1=0;return}let Z=new Map,Y=0;for(let z of O0){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}v1=Y/$;let Q={};for(let[z,J]of Z)Q[z]=Math.log(($-J+0.5)/(J+0.5)+1);y1=Q}function GM(){if(!l9)return;let $={chunks:O0,idf:y1,avgDocLength:v1,sourceHashes:x1,builtAt:new Date().toISOString(),version:tV};j(iY(),JSON.stringify($))}function WM(){let $=iY();if(!r2($)){O0=[],y1={},v1=0,x1={};return}try{let Z=JSON.parse(b5($,"utf-8"));if(Z.version!==tV){O0=[],y1={},v1=0,x1={};return}O0=Z.chunks,y1=Z.idf,v1=Z.avgDocLength,x1=Z.sourceHashes}catch{O0=[],y1={},v1=0,x1={}}}function HM(){let $=iY();if(!r2($))return null;try{return{builtAt:JSON.parse(b5($,"utf-8")).builtAt}}catch{return null}}function UM($){return $M("sha256").update($).digest("hex").slice(0,16)}function qM($,Z,Y){switch($){case"material":{let Q=Y.split(`
1178
1181
  `)[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(`
1179
- `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function sC($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var i9=[{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 uV($,Z){switch($){case"recall_memory":{if(!u9())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=l9(Y,Q);return o9(z)}case"index_memory":{if(!u9())return"Error: memory not initialized.";let Y=c9();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!u9())return"Memory: nao inicializada.";let Y=d9(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
1182
+ `)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function BM($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var s9=[{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 $G($,Z){switch($){case"recall_memory":{if(!o9())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=r9(Y,Q);return a9(z)}case"index_memory":{if(!o9())return"Error: memory not initialized.";let Y=n9();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!o9())return"Memory: nao inicializada.";let Y=i9(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
1180
1183
  Chunks: ${Y.chunks}
1181
1184
  Fontes: ${Y.sources}
1182
- Ultima indexacao: ${Q}`}default:return null}}h();z1();import{join as tC}from"path";import{createHash as eC}from"crypto";var $M={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},M3={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"]},ZM=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],YM="",A=null,dY=[],oV={...$M},iV=!1,dV=null,QM=()=>tC(YM,"plan-history.json");function v1(){return iV}function cY($,Z){let Y=$.toLowerCase(),Q=zM(Y),z=Z?.files||[],J=Z?.modules||[],X=[],K=[];for(let H of z)for(let W of ZM)if(W.test(H))X.push(`Modifying sensitive file: ${H}`);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 V=oV.requireApprovalFor.includes(Q),G=V?`Task classified as "${Q}" \u2014 requires explicit approval`:`Task classified as "${Q}" \u2014 can proceed with auto-approval`;return{complexity:Q,filesAffected:z,modulesAffected:J,risks:X,assumptions:K,requiresApproval:V,reason:G}}function zM($){for(let Z of M3.architectural)if($.includes(Z))return"architectural";for(let Z of M3.complex)if($.includes(Z))return"complex";for(let Z of M3.moderate)if($.includes(Z))return"moderate";for(let Z of M3.simple)if($.includes(Z))return"simple";for(let Z of M3.trivial)if($.includes(Z))return"trivial";return"moderate"}function nV($,Z,Y){let Q=cY($),z={id:lV(),objective:$,strategy:Z.map((J,X)=>({...J,id:lV(),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,p1().emit("planning:started",{planId:z.id,objective:$,timestamp:Date.now()}),z}async function rV(){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()},oV.autoApproveComplexity.includes(A.complexity))return cV("Auto-approved based on complexity classification");if(dV)if(await dV(A))return cV("Approved by user");else return JM("Rejected by user");return{success:!0,plan:A,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function cV($){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:$},p1().emit("planning:approved",{planId:A.id,feedback:$,timestamp:Date.now()}),{success:!0,plan:A,message:"Plan approved \u2014 execution may proceed"}}function JM($){if(!A)return{success:!1,plan:null,message:"No active plan to reject"};return A={...A,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},p1().emit("planning:rejected",{planId:A.id,feedback:$,timestamp:Date.now()}),$G(A),A=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function aV(){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 sV($,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,V)=>V===Y?{...K,status:"completed",result:Z}:K);A={...A,strategy:Q,updatedAt:new Date().toISOString()},p1().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"))XM();return{success:!0,message:`Step completed: ${J}`,nextStep:z}}function tV($,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()},p1().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 XM(){if(!A)return;A={...A,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},p1().emit("planning:completed",{planId:A.id,stepsCompleted:A.strategy.filter(($)=>$.status==="completed").length,timestamp:Date.now()}),$G(A),A=null}function E3(){return A?{...A}:null}function lY($){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(`
1185
+ Ultima indexacao: ${Q}`}default:return null}}g();X1();import{join as NM}from"path";import{createHash as OM}from"crypto";var CM={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},F3={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"]},MM=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],EM="",A=null,nY=[],zG={...CM},JG=!1,ZG=null,FM=()=>NM(EM,"plan-history.json");function _1(){return JG}function rY($,Z){let Y=$.toLowerCase(),Q=LM(Y),z=Z?.files||[],J=Z?.modules||[],X=[],K=[];for(let W of z)for(let H of MM)if(H.test(W))X.push(`Modifying sensitive file: ${W}`);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 V=zG.requireApprovalFor.includes(Q),G=V?`Task classified as "${Q}" \u2014 requires explicit approval`:`Task classified as "${Q}" \u2014 can proceed with auto-approval`;return{complexity:Q,filesAffected:z,modulesAffected:J,risks:X,assumptions:K,requiresApproval:V,reason:G}}function LM($){for(let Z of F3.architectural)if($.includes(Z))return"architectural";for(let Z of F3.complex)if($.includes(Z))return"complex";for(let Z of F3.moderate)if($.includes(Z))return"moderate";for(let Z of F3.simple)if($.includes(Z))return"simple";for(let Z of F3.trivial)if($.includes(Z))return"trivial";return"moderate"}function XG($,Z,Y){let Q=rY($),z={id:QG(),objective:$,strategy:Z.map((J,X)=>({...J,id:QG(),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,d1().emit("planning:started",{planId:z.id,objective:$,timestamp:Date.now()}),z}async function KG(){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()},zG.autoApproveComplexity.includes(A.complexity))return YG("Auto-approved based on complexity classification");if(ZG)if(await ZG(A))return YG("Approved by user");else return RM("Rejected by user");return{success:!0,plan:A,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function YG($){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:$},d1().emit("planning:approved",{planId:A.id,feedback:$,timestamp:Date.now()}),{success:!0,plan:A,message:"Plan approved \u2014 execution may proceed"}}function RM($){if(!A)return{success:!1,plan:null,message:"No active plan to reject"};return A={...A,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},d1().emit("planning:rejected",{planId:A.id,feedback:$,timestamp:Date.now()}),UG(A),A=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function VG(){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 GG($,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,V)=>V===Y?{...K,status:"completed",result:Z}:K);A={...A,strategy:Q,updatedAt:new Date().toISOString()},d1().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"))jM();return{success:!0,message:`Step completed: ${J}`,nextStep:z}}function WG($,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()},d1().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 jM(){if(!A)return;A={...A,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},d1().emit("planning:completed",{planId:A.id,stepsCompleted:A.strategy.filter(($)=>$.status==="completed").length,timestamp:Date.now()}),UG(A),A=null}function L3(){return A?{...A}:null}function aY($){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(`
1183
1186
  `):" (nenhuma)",Q=$.risks.length>0?$.risks.map((z)=>` - ${z}`).join(`
1184
1187
  `):" (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(`
1185
- `)}function eV($){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(`
1186
- `)}function $G($){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};dY=[...dY,Z],KM()}function KM(){if(!iV)return;P(QM(),JSON.stringify(dY,null,2))}function lV(){return eC("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function ZG(){return`
1188
+ `)}function HG($){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(`
1189
+ `)}function UG($){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};nY=[...nY,Z],PM()}function PM(){if(!JG)return;j(FM(),JSON.stringify(nY,null,2))}function QG(){return OM("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function qG(){return`
1187
1190
  ## Protocolo de Alta Ag\xEAncia
1188
1191
 
1189
1192
  Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
@@ -1225,43 +1228,43 @@ Ao usar \`propose_plan\`, estruture assim:
1225
1228
  - **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
1226
1229
  - **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
1227
1230
  - **Bloqueio**: Sempre termine com "Posso prosseguir com este plano?"
1228
- `.trim()}var n9=[{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 YG($,Z){switch($){case"propose_plan":{if(!v1())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((V,G)=>({action:V.action,target:V.target,description:V.description,estimatedImpact:V.estimatedImpact||"low",dependencies:V.dependencies||[],order:G+1})),J=nV(Y,z,{assumptions:Z.assumptions,risks:Z.risks}),X=await rV();if(!X.success)return`Error creating plan: ${X.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
1231
+ `.trim()}var t9=[{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 BG($,Z){switch($){case"propose_plan":{if(!_1())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((V,G)=>({action:V.action,target:V.target,description:V.description,estimatedImpact:V.estimatedImpact||"low",dependencies:V.dependencies||[],order:G+1})),J=XG(Y,z,{assumptions:Z.assumptions,risks:Z.risks}),X=await KG();if(!X.success)return`Error creating plan: ${X.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
1229
1232
 
1230
- ${lY(J)}`}case"check_plan_status":{if(!v1())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=aV(),Q=E3();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${eV(Q)}
1233
+ ${aY(J)}`}case"check_plan_status":{if(!_1())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=VG(),Q=L3();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${HG(Q)}
1231
1234
 
1232
1235
  Execu\xE7\xE3o: ${Y.allowed?"PERMITIDA":"BLOQUEADA"}
1233
- Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!v1())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=E3();if(!J)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let X=Z.step_id,K=X?J.strategy.find((V)=>V.id===X):J.strategy.find((V)=>V.status==="in_progress"||V.status==="pending");if(K)tV(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(`
1234
- `)}case"complete_plan_step":{if(!v1())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=sV(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let z=E3(),J=z?`Progresso: ${z.strategy.filter((K)=>K.status==="completed").length}/${z.strategy.length}`:"",X=Q.nextStep?`
1236
+ Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!_1())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=L3();if(!J)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let X=Z.step_id,K=X?J.strategy.find((V)=>V.id===X):J.strategy.find((V)=>V.status==="in_progress"||V.status==="pending");if(K)WG(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(`
1237
+ `)}case"complete_plan_step":{if(!_1())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=GG(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let z=L3(),J=z?`Progresso: ${z.strategy.filter((K)=>K.status==="completed").length}/${z.strategy.length}`:"",X=Q.nextStep?`
1235
1238
  Pr\xF3ximo passo: ${Q.nextStep.action} \u2192 ${Q.nextStep.target}`:`
1236
1239
  Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Q.message}
1237
- ${J}${X}`}case"get_current_plan":{if(!v1())return"Agency engine not initialized. No planning features available.";let Y=E3();if(!Y)return"Nenhum plano ativo no momento.";return lY(Y)}case"analyze_task_complexity":{if(!v1())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=cY(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(`
1238
- `)}default:return null}}import{existsSync as r9}from"fs";import{join as F3}from"path";var VM=30000,GM=200000,HM=[/^Log in to Microsoft 365 first$/i,/not logged in/i,/token has expired/i],L3=null,a9="m365";function WM(){let $=F3(process.cwd(),"node_modules",".bin"),Z=F3($,"m365.exe");if(r9(Z))return Z;let Y=F3($,"m365.cmd");if(r9(Y))return Y;let Q=F3($,"m365.bunx");if(r9(Q))return Q;let z=F3($,"m365");if(r9(z))return z;return"m365"}async function R3(){if(L3!==null)return L3;a9=WM();try{let $=Bun.spawn([a9,"--version"],{stdout:"pipe",stderr:"pipe"}),Z=setTimeout(()=>$.kill(),5000);await new Response($.stdout).text(),await $.exited,clearTimeout(Z),L3=$.exitCode===0}catch{L3=!1}return L3}async function t($,Z={}){let Y=Z.timeout??VM,Q=Z.jsonOutput!==!1;if(!await R3())return{success:!1,data:null,error:"M365 CLI not found. Run: bun install",raw:"",duration:0};let J=[a9,...$];if(Q)J.push("--output","json");let X=performance.now();try{let K=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>K.kill(),Y),[G,H]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]);await K.exited,clearTimeout(V);let W=Math.round(performance.now()-X),U=G.trim().slice(0,GM);if(K.exitCode!==0){let q=H.trim()||U||"Unknown error";if(UM(q))return{success:!1,data:null,error:"Not logged in. Run /m365 login first.",raw:q,duration:W};return{success:!1,data:null,error:q,raw:q,duration:W}}if(Q&&U)try{return{success:!0,data:JSON.parse(U),error:null,raw:U,duration:W}}catch{return{success:!0,data:U,error:null,raw:U,duration:W}}return{success:!0,data:U,error:null,raw:U,duration:W}}catch(K){let V=Math.round(performance.now()-X),G=K instanceof Error?K.message:String(K);return{success:!1,data:null,error:G.includes("timed out")||G.includes("killed")?`Command timed out after ${Y}ms`:G,raw:"",duration:V}}}async function j3($,Z){return t($,{timeout:Z,jsonOutput:!1})}async function oY($,Z,Y=180000){if(!await R3())return{success:!1,exitCode:1,output:"M365 CLI not found."};let z=[a9,...$],J=[];try{let X=Bun.spawn(z,{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),Y),V=new TextDecoder,G=(async()=>{let W=X.stderr.getReader();while(!0){let{done:U,value:q}=await W.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})(),H=(async()=>{let W=X.stdout.getReader();while(!0){let{done:U,value:q}=await W.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})();return await Promise.all([G,H]),await X.exited,clearTimeout(K),{success:X.exitCode===0,exitCode:X.exitCode??1,output:J.join("")}}catch{return{success:!1,exitCode:1,output:J.join("")}}}function UM($){return HM.some((Z)=>Z.test($))}var QG={emails:120000,calendar:300000,files:300000,contacts:1800000,todo:180000,onenote:600000,status:60000};var W1=new Map;function l0($){let Z=W1.get($);if(!Z)return null;if(Date.now()>Z.expiresAt)return W1.delete($),null;return Z.data}function o0($,Z,Y,Q){let z=Q??QG[Y]??300000;W1.set($,{data:Z,expiresAt:Date.now()+z,key:$})}function iY($){let Z=0;for(let Y of W1.keys())if(Y.startsWith($))W1.delete(Y),Z++;return Z}function P3(){W1.clear()}function nY(){let $=Date.now();for(let[Z,Y]of W1)if($>Y.expiresAt)W1.delete(Z);return{size:W1.size,keys:[...W1.keys()]}}var JG="14d82eec-204b-4c2f-b7e8-296a70dab67e",A3=null,zG=!1;async function s9(){let $=await t(["status"]);if(!$.success){let z={status:"disconnected",connectedAs:null,tenantId:null,authType:null};return A3=z,z}let Z=$.data,Y=Z&&typeof Z==="object"&&"connectedAs"in Z,Q={status:Y?"connected":"disconnected",connectedAs:Y?String(Z.connectedAs??""):null,tenantId:Y?String(Z.tenantId??""):null,authType:Y?String(Z.authType??""):null};return A3=Q,Q}async function rY(){return(A3??await s9()).status==="connected"}async function qM(){if(zG)return;let $=await t(["cli","config","list"]),Z=$.success&&$.data?$.data:{};if(Z.autoOpenLinksInBrowser!==!1)await j3(["cli","config","set","--key","autoOpenLinksInBrowser","--value","false"],1e4);if(Z.copyDeviceCodeToClipboard!==!1)await j3(["cli","config","set","--key","copyDeviceCodeToClipboard","--value","false"],1e4);if(Z.output!=="json")await j3(["cli","config","set","--key","output","--value","json"],1e4);zG=!0}async function aY($,Z){await qM();let Y=await t(["cli","config","list"]),Q=Y.success&&Y.data?Y.data:{},z=Boolean(Q.clientId),J=Q.authType?String(Q.authType):null,X=["login"];if(Z)X.push("--appId",Z,"--authType","deviceCode");else if(z&&J);else X.push("--appId",JG,"--authType","deviceCode");let K=await oY(X,(G)=>{let H=G.trim();if(H&&$)$(H)},180000);if(A3=null,K.success)return"Login successful. Use /m365 status to verify.";let V=K.output.trim();if(V.includes("AADSTS7000215")||V.includes("Invalid client secret"))return["Invalid client secret. In Azure Portal:","App registrations > your app > Certificates & secrets","Copy the secret VALUE (not the Secret ID).","Then: m365 cli config set --key clientSecret --value <secret-value>"].join(`
1240
+ ${J}${X}`}case"get_current_plan":{if(!_1())return"Agency engine not initialized. No planning features available.";let Y=L3();if(!Y)return"Nenhum plano ativo no momento.";return aY(Y)}case"analyze_task_complexity":{if(!_1())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=rY(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(`
1241
+ `)}default:return null}}import{existsSync as e9}from"fs";import{join as R3}from"path";var AM=30000,DM=200000,TM=[/^Log in to Microsoft 365 first$/i,/not logged in/i,/token has expired/i],j3=null,$Z="m365";function IM(){let $=R3(process.cwd(),"node_modules",".bin"),Z=R3($,"m365.exe");if(e9(Z))return Z;let Y=R3($,"m365.cmd");if(e9(Y))return Y;let Q=R3($,"m365.bunx");if(e9(Q))return Q;let z=R3($,"m365");if(e9(z))return z;return"m365"}async function P3(){if(j3!==null)return j3;$Z=IM();try{let $=Bun.spawn([$Z,"--version"],{stdout:"pipe",stderr:"pipe"}),Z=setTimeout(()=>$.kill(),5000);await new Response($.stdout).text(),await $.exited,clearTimeout(Z),j3=$.exitCode===0}catch{j3=!1}return j3}async function e($,Z={}){let Y=Z.timeout??AM,Q=Z.jsonOutput!==!1;if(!await P3())return{success:!1,data:null,error:"M365 CLI not found. Run: bun install",raw:"",duration:0};let J=[$Z,...$];if(Q)J.push("--output","json");let X=performance.now();try{let K=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>K.kill(),Y),[G,W]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]);await K.exited,clearTimeout(V);let H=Math.round(performance.now()-X),U=G.trim().slice(0,DM);if(K.exitCode!==0){let q=W.trim()||U||"Unknown error";if(SM(q))return{success:!1,data:null,error:"Not logged in. Run /m365 login first.",raw:q,duration:H};return{success:!1,data:null,error:q,raw:q,duration:H}}if(Q&&U)try{return{success:!0,data:JSON.parse(U),error:null,raw:U,duration:H}}catch{return{success:!0,data:U,error:null,raw:U,duration:H}}return{success:!0,data:U,error:null,raw:U,duration:H}}catch(K){let V=Math.round(performance.now()-X),G=K instanceof Error?K.message:String(K);return{success:!1,data:null,error:G.includes("timed out")||G.includes("killed")?`Command timed out after ${Y}ms`:G,raw:"",duration:V}}}async function A3($,Z){return e($,{timeout:Z,jsonOutput:!1})}async function sY($,Z,Y=180000){if(!await P3())return{success:!1,exitCode:1,output:"M365 CLI not found."};let z=[$Z,...$],J=[];try{let X=Bun.spawn(z,{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),Y),V=new TextDecoder,G=(async()=>{let H=X.stderr.getReader();while(!0){let{done:U,value:q}=await H.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})(),W=(async()=>{let H=X.stdout.getReader();while(!0){let{done:U,value:q}=await H.read();if(U)break;let N=V.decode(q,{stream:!0});J.push(N),Z(N)}})();return await Promise.all([G,W]),await X.exited,clearTimeout(K),{success:X.exitCode===0,exitCode:X.exitCode??1,output:J.join("")}}catch{return{success:!1,exitCode:1,output:J.join("")}}}function SM($){return TM.some((Z)=>Z.test($))}var NG={emails:120000,calendar:300000,files:300000,contacts:1800000,todo:180000,onenote:600000,status:60000};var q1=new Map;function i0($){let Z=q1.get($);if(!Z)return null;if(Date.now()>Z.expiresAt)return q1.delete($),null;return Z.data}function n0($,Z,Y,Q){let z=Q??NG[Y]??300000;q1.set($,{data:Z,expiresAt:Date.now()+z,key:$})}function tY($){let Z=0;for(let Y of q1.keys())if(Y.startsWith($))q1.delete(Y),Z++;return Z}function D3(){q1.clear()}function eY(){let $=Date.now();for(let[Z,Y]of q1)if($>Y.expiresAt)q1.delete(Z);return{size:q1.size,keys:[...q1.keys()]}}var CG="14d82eec-204b-4c2f-b7e8-296a70dab67e",T3=null,OG=!1;async function ZZ(){let $=await e(["status"]);if(!$.success){let z={status:"disconnected",connectedAs:null,tenantId:null,authType:null};return T3=z,z}let Z=$.data,Y=Z&&typeof Z==="object"&&"connectedAs"in Z,Q={status:Y?"connected":"disconnected",connectedAs:Y?String(Z.connectedAs??""):null,tenantId:Y?String(Z.tenantId??""):null,authType:Y?String(Z.authType??""):null};return T3=Q,Q}async function $Q(){return(T3??await ZZ()).status==="connected"}async function wM(){if(OG)return;let $=await e(["cli","config","list"]),Z=$.success&&$.data?$.data:{};if(Z.autoOpenLinksInBrowser!==!1)await A3(["cli","config","set","--key","autoOpenLinksInBrowser","--value","false"],1e4);if(Z.copyDeviceCodeToClipboard!==!1)await A3(["cli","config","set","--key","copyDeviceCodeToClipboard","--value","false"],1e4);if(Z.output!=="json")await A3(["cli","config","set","--key","output","--value","json"],1e4);OG=!0}async function ZQ($,Z){await wM();let Y=await e(["cli","config","list"]),Q=Y.success&&Y.data?Y.data:{},z=Boolean(Q.clientId),J=Q.authType?String(Q.authType):null,X=["login"];if(Z)X.push("--appId",Z,"--authType","deviceCode");else if(z&&J);else X.push("--appId",CG,"--authType","deviceCode");let K=await sY(X,(G)=>{let W=G.trim();if(W&&$)$(W)},180000);if(T3=null,K.success)return"Login successful. Use /m365 status to verify.";let V=K.output.trim();if(V.includes("AADSTS7000215")||V.includes("Invalid client secret"))return["Invalid client secret. In Azure Portal:","App registrations > your app > Certificates & secrets","Copy the secret VALUE (not the Secret ID).","Then: m365 cli config set --key clientSecret --value <secret-value>"].join(`
1239
1242
  `);if(V.includes("invalid_grant")||V.includes("AADSTS"))return`Login failed: ${V.split(`
1240
1243
  `)[0]}`;if(V.includes("clipboardy")||V.includes("Expected a string"))return"Login crashed. Run /m365 login again (clipboard issue fixed).";if(V)return`Login failed: ${V.split(`
1241
- `)[0]}`;return"Login failed or timed out. Try again with /m365 login"}async function sY(){let $=await j3(["logout"]);if(P3(),A3={status:"disconnected",connectedAs:null,tenantId:null,authType:null},$.success)return"Disconnected from Microsoft 365.";return $.error??"Logout completed."}function tY($){let Z=$??JG,Y=["Mail.Read","Mail.Send","Calendars.ReadWrite","Tasks.ReadWrite","Files.Read","Notes.Read","User.Read"].join(" ");return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${new URLSearchParams({client_id:Z,response_type:"code",scope:Y,redirect_uri:"https://login.microsoftonline.com/common/oauth2/nativeclient",prompt:"consent"}).toString()}`}function eY($){if($.status==="connected"){let Z=["--- Microsoft 365 ---","Status: Connected",`Account: ${$.connectedAs}`];if($.tenantId)Z.push(`Tenant: ${$.tenantId}`);if($.authType)Z.push(`Auth: ${$.authType}`);return Z.push("---------------------"),Z.join(`
1244
+ `)[0]}`;return"Login failed or timed out. Try again with /m365 login"}async function YQ(){let $=await A3(["logout"]);if(D3(),T3={status:"disconnected",connectedAs:null,tenantId:null,authType:null},$.success)return"Disconnected from Microsoft 365.";return $.error??"Logout completed."}function QQ($){let Z=$??CG,Y=["Mail.Read","Mail.Send","Calendars.ReadWrite","Tasks.ReadWrite","Files.Read","Notes.Read","User.Read"].join(" ");return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${new URLSearchParams({client_id:Z,response_type:"code",scope:Y,redirect_uri:"https://login.microsoftonline.com/common/oauth2/nativeclient",prompt:"consent"}).toString()}`}function zQ($){if($.status==="connected"){let Z=["--- Microsoft 365 ---","Status: Connected",`Account: ${$.connectedAs}`];if($.tenantId)Z.push(`Tenant: ${$.tenantId}`);if($.authType)Z.push(`Auth: ${$.authType}`);return Z.push("---------------------"),Z.join(`
1242
1245
  `)}return["--- Microsoft 365 ---","Status: Disconnected","Run /m365 login to connect.","---------------------"].join(`
1243
- `)}function D3($){if(!$)return"(unknown)";if(typeof $==="string")return $;if(typeof $==="object"){let Y=$.emailAddress;if(Y)return`${Y.name??""} <${Y.address??""}>`.trim()}return String($)}function o($,Z=""){if($===void 0||$===null)return Z;return String($)}async function x1($={}){if(!$.fresh){let Q=l0("outlook:message:list");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await t(["outlook","message","list","--folderName","inbox"]);if(Y.success&&Y.data){let Q=Y.data.map((z)=>{let J=z;return{id:o(J.id,""),subject:o(J.subject,"(no subject)"),from:D3(J.from),receivedDateTime:o(J.receivedDateTime),isRead:J.isRead===!0,bodyPreview:o(J.bodyPreview),importance:o(J.importance,"normal")}});return o0("outlook:message:list",Q,"emails"),{success:!0,data:Q,error:null,raw:Y.raw,duration:Y.duration}}return Y}async function T3($){let Z=await t(["outlook","message","get","--id",$]);if(Z.success&&Z.data){let Y=Z.data,Q=Array.isArray(Y.toRecipients)?Y.toRecipients.map(D3):[],z=Array.isArray(Y.ccRecipients)?Y.ccRecipients.map(D3):[],J=typeof Y.body==="object"&&Y.body?o(Y.body.content):o(Y.bodyPreview);return{success:!0,data:{id:o(Y.id),subject:o(Y.subject,"(no subject)"),from:D3(Y.from),to:Q,cc:z,receivedDateTime:o(Y.receivedDateTime),isRead:Y.isRead===!0,body:J,importance:o(Y.importance,"normal"),hasAttachments:Y.hasAttachments===!0},error:null,raw:Z.raw,duration:Z.duration}}return Z}async function I3($){let Z=["outlook","mail","send","--to",$.to,"--subject",$.subject,"--bodyContents",$.body];if($.cc)Z.push("--cc",$.cc);if($.importance&&$.importance!=="normal")Z.push("--importance",$.importance);return t(Z,{jsonOutput:!1})}function K2($){if($.length===0)return"No emails found.";let Z=["--- Inbox ---"];for(let Y of $){let Q=Y.isRead?" ":"*",z=Y.id?Y.id.slice(-6):"------",J=Y.receivedDateTime?new Date(Y.receivedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"",X=Y.bodyPreview?.slice(0,60)??"";if(Z.push(`${Q} [${z}] ${J} | ${Y.from}`),Z.push(` ${Y.subject}`),X)Z.push(` ${X}...`)}return Z.push(`--- ${$.filter((Y)=>!Y.isRead).length} unread ---`),Z.join(`
1244
- `)}async function V2($={}){if(!$.fresh){let Q=l0("outlook:event:list");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await t(["outlook","event","list"]);if(Y.success&&Y.data){let Q=Y.data.map((z)=>{let J=z,X=typeof J.start==="object"&&J.start?o(J.start.dateTime):o(J.start),K=typeof J.end==="object"&&J.end?o(J.end.dateTime):o(J.end);return{id:o(J.id),subject:o(J.subject,"(no subject)"),start:X,end:K,location:typeof J.location==="object"&&J.location?o(J.location.displayName):o(J.location),organizer:D3(J.organizer),isAllDay:J.isAllDay===!0,status:o(J.showAs??J.status,"")}});return o0("outlook:event:list",Q,"calendar"),{success:!0,data:Q,error:null,raw:Y.raw,duration:Y.duration}}return Y}async function w3($){let Z=["outlook","event","add","--subject",$.subject,"--startDateTime",$.start,"--endDateTime",$.end];if($.location)Z.push("--location",$.location);if($.body)Z.push("--bodyContents",$.body);if($.isAllDay)Z.push("--isAllDay");return t(Z,{jsonOutput:!1})}function n2($){if($.length===0)return"No events found.";let Z=["--- Calendar ---"];for(let Y of $){let Q=Y.start?new Date(Y.start).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",z=Y.end?new Date(Y.end).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",J=Y.location?` @ ${Y.location}`:"";Z.push(` ${Q}-${z} ${Y.subject}${J}`)}return Z.push("----------------"),Z.join(`
1245
- `)}async function $Q($={}){if(!$.fresh){let Q=l0("outlook:contact:list");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await t(["outlook","contact","list"]);if(Y.success&&Y.data){let Q=Y.data.map((z)=>{let J=z;return{id:o(J.id),displayName:o(J.displayName,"(unnamed)"),emailAddresses:Array.isArray(J.emailAddresses)?J.emailAddresses.map((X)=>{if(typeof X==="string")return X;if(typeof X==="object"&&X)return o(X.address);return""}).filter(Boolean):[],phoneNumbers:Array.isArray(J.phones)?J.phones.map((X)=>{if(typeof X==="string")return X;if(typeof X==="object"&&X)return o(X.number);return""}).filter(Boolean):[],company:J.companyName?o(J.companyName):null,jobTitle:J.jobTitle?o(J.jobTitle):null}});return o0("outlook:contact:list",Q,"contacts"),{success:!0,data:Q,error:null,raw:Y.raw,duration:Y.duration}}return Y}function ZQ($){if($.length===0)return"No contacts found.";let Z=["--- Contacts ---"];for(let Y of $){let Q=Y.emailAddresses[0]??"",z=Y.jobTitle?` (${Y.jobTitle})`:"";Z.push(` ${Y.displayName}${z} - ${Q}`)}return Z.push("----------------"),Z.join(`
1246
- `)}async function YQ($={}){if(!$.fresh){let Q=l0("todo:lists");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await t(["todo","list","list"]);if(Y.success&&Y.data)o0("todo:lists",Y.data,"todo");return Y}async function G2($,Z={}){let Y=`todo:tasks:${$??"default"}`;if(!Z.fresh){let J=l0(Y);if(J)return{success:!0,data:J,error:null,raw:"",duration:0}}let Q=["todo","task","list"];if($)Q.push("--listId",$);else Q.push("--listName","Tasks");let z=await t(Q);if(z.success&&z.data)o0(Y,z.data,"todo");return z}async function S3($){let Z=["todo","task","add","--title",$.title];if($.listId)Z.push("--listId",$.listId);if($.dueDateTime)Z.push("--dueDateTime",$.dueDateTime);if($.importance)Z.push("--importance",$.importance);let Y=await t(Z,{jsonOutput:!1});if(Y.success)iY("todo:");return Y}async function k3($,Z){let Y=["todo","task","set","--id",$,"--status","completed"];if(Z)Y.push("--listId",Z);let Q=await t(Y,{jsonOutput:!1});if(Q.success)iY("todo:");return Q}function r2($){if($.length===0)return"No tasks found.";let Z=$.filter((z)=>z.status!=="completed"),Y=$.filter((z)=>z.status==="completed"),Q=["--- To Do ---"];if(Z.length>0)for(let z of Z){let J=z.dueDateTime?` (due: ${new Date(z.dueDateTime).toLocaleDateString("pt-BR")})`:"",X=z.importance==="high"?" !":"";Q.push(` [ ] ${z.title}${J}${X}`)}if(Y.length>0)Q.push(` --- ${Y.length} completed ---`);return Q.push("-------------"),Q.join(`
1247
- `)}function QQ($){if($.length===0)return"No task lists found.";let Z=["--- To Do Lists ---"];for(let Y of $){let Q=Y.isShared?" (shared)":"";Z.push(` ${Y.displayName}${Q} [${Y.id.slice(-6)}]`)}return Z.push("-------------------"),Z.join(`
1248
- `)}async function f5($,Z={}){let Q=`onedrive:list:${$??"/"}`;if(!Z.fresh){let X=l0(Q);if(X)return{success:!0,data:X,error:null,raw:"",duration:0}}let z=["onedrive","list"];if($)z.push("--folderUrl",$);let J=await t(z);if(J.success&&J.data)o0(Q,J.data,"files");return J}function b5($){if($.length===0)return"No files found.";let Z=["--- OneDrive ---"];for(let Y of $){let Q=Y.isFolder?"[D]":"[F]",z=Y.isFolder?"":` (${BM(Y.size)})`,J=new Date(Y.lastModifiedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` ${Q} ${Y.name}${z} - ${J}`)}return Z.push("----------------"),Z.join(`
1249
- `)}function BM($){if($===0)return"0 B";let Z=1024,Y=["B","KB","MB","GB"],Q=Math.floor(Math.log($)/Math.log(Z));return`${($/Math.pow(Z,Q)).toFixed(1)} ${Y[Q]}`}async function zQ($={}){if(!$.fresh){let Q=l0("onenote:notebooks");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await t(["onenote","notebook","list"]);if(Y.success&&Y.data)o0("onenote:notebooks",Y.data,"onenote");return Y}async function JQ($,Z={}){let Y=`onenote:pages:${$}`;if(!Z.fresh){let z=l0(Y);if(z)return{success:!0,data:z,error:null,raw:"",duration:0}}let Q=await t(["onenote","page","list","--name",$]);if(Q.success&&Q.data)o0(Y,Q.data,"onenote");return Q}function XQ($){if($.length===0)return"No notebooks found.";let Z=["--- OneNote ---"];for(let Y of $){let Q=Y.isShared?" (shared)":"",z=new Date(Y.lastModifiedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` ${Y.displayName}${Q} - ${z}`)}return Z.push("---------------"),Z.join(`
1250
- `)}function KQ($){if($.length===0)return"No pages found.";let Z=["--- Pages ---"];for(let Y of $){let Q=new Date(Y.lastModifiedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` ${Y.title} - ${Q}`)}return Z.push("-------------"),Z.join(`
1251
- `)}async function f3($={}){let Z=$.fresh??!1,[Y,Q,z]=await Promise.all([x1({top:10,fresh:Z}),V2({fresh:Z}),G2(void 0,{fresh:Z})]),J=Y.success&&Y.data?Y.data.filter((H)=>!H.isRead):[],X=Q.success&&Q.data?Q.data:[],K=z.success&&z.data?z.data.filter((H)=>H.status!=="completed"):[],V={unreadEmails:J,todayEvents:X,pendingTodos:K,timestamp:Date.now()},G=["=== M365 Briefing ===",""];if(!Y.success)G.push(`Emails: Error - ${Y.error}`);else if(J.length===0)G.push("Emails: Inbox clear");else G.push(`Emails: ${J.length} unread`),G.push(K2(J));if(G.push(""),!Q.success)G.push(`Calendar: Error - ${Q.error}`);else if(X.length===0)G.push("Calendar: No events today");else G.push(`Calendar: ${X.length} events`),G.push(n2(X));if(G.push(""),!z.success)G.push(`To Do: Error - ${z.error}`);else if(K.length===0)G.push("To Do: All clear");else G.push(`To Do: ${K.length} pending`),G.push(r2(K));return G.push(""),G.push("====================="),{success:!0,data:V,formatted:G.join(`
1252
- `)}}async function VQ(){let[$,Z,Y]=await Promise.all([x1({top:50,fresh:!0}),V2({fresh:!0}),G2(void 0,{fresh:!0})]),Q=$.success&&$.data?$.data.length:0,z=Z.success&&Z.data?Z.data.length:0,J=Y.success&&Y.data?Y.data.filter((V)=>V.status==="completed").length:0,X=Y.success&&Y.data?Y.data.filter((V)=>V.status!=="completed").length:0;return{success:!0,formatted:["=== M365 Weekly Digest ===","",`Emails received: ${Q}`,`Calendar events: ${z}`,`Tasks completed: ${J}`,`Tasks pending: ${X}`,"","=========================="].join(`
1253
- `)}}async function GQ($){if(!$.trim())return{success:!1,formatted:"Error: search query is required."};let Z=await x1({top:50,fresh:!0}),Y=Z.success&&Z.data?Z.data.filter((z)=>{let J=$.toLowerCase();return z.subject.toLowerCase().includes(J)||z.bodyPreview.toLowerCase().includes(J)||z.from.toLowerCase().includes(J)}):[],Q=[`=== M365 Search: "${$}" ===`,""];if(Y.length>0)Q.push(`Emails: ${Y.length} matches`),Q.push(K2(Y));else Q.push("Emails: no matches");return Q.push(""),Q.push("=============================="),{success:!0,formatted:Q.join(`
1254
- `)}}var t9=[{name:"m365_list_emails",description:"List recent inbox emails from Microsoft 365. Returns subject, sender, date, and preview. Requires M365 CLI login via /m365 login.",input_schema:{type:"object",properties:{top:{type:"number",description:"Number of emails to fetch (default: 20, max: 50)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_read_email",description:"Read a specific email by ID from Microsoft 365. Returns full body and metadata.",input_schema:{type:"object",properties:{id:{type:"string",description:"Email ID (from m365_list_emails)"}},required:["id"]}},{name:"m365_send_email",description:"Send an email via Microsoft 365.",input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC email address (optional)"},importance:{type:"string",description:"low, normal, or high (default: normal)"}},required:["to","subject","body"]}},{name:"m365_list_events",description:"List calendar events from Microsoft 365 Outlook.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_create_event",description:"Create a calendar event in Microsoft 365 Outlook.",input_schema:{type:"object",properties:{subject:{type:"string",description:"Event title"},start:{type:"string",description:"Start datetime (ISO 8601)"},end:{type:"string",description:"End datetime (ISO 8601)"},location:{type:"string",description:"Event location (optional)"},body:{type:"string",description:"Event description (optional)"}},required:["subject","start","end"]}},{name:"m365_list_todos",description:"List tasks from Microsoft To Do.",input_schema:{type:"object",properties:{listId:{type:"string",description:"To Do list ID (optional, uses default list)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_create_todo",description:"Create a task in Microsoft To Do.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task title"},listId:{type:"string",description:"To Do list ID (optional)"},dueDateTime:{type:"string",description:"Due date (ISO 8601, optional)"},importance:{type:"string",description:"low, normal, or high (default: normal)"}},required:["title"]}},{name:"m365_complete_todo",description:"Mark a Microsoft To Do task as completed.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"},listId:{type:"string",description:"To Do list ID (optional)"}},required:["taskId"]}},{name:"m365_list_files",description:"List files in OneDrive.",input_schema:{type:"object",properties:{folder:{type:"string",description:"Folder path (optional, defaults to root)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_briefing",description:"Get a combined Microsoft 365 briefing: unread emails, today's calendar events, and pending To Do tasks. Fetches all data in parallel.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}}];async function HQ($,Z){if(!$.startsWith("m365_"))return null;if(!await rY())return"Not connected to Microsoft 365. Run /m365 login to authenticate.";switch($){case"m365_list_emails":{let Q=typeof Z.top==="number"?Z.top:void 0,z=Z.fresh===!0,J=await x1({top:Q,fresh:z});if(!J.success)return`Error: ${J.error}`;return K2(J.data??[])}case"m365_read_email":{let Q=String(Z.id??"");if(!Q)return"Error: email ID is required.";let z=await T3(Q);if(!z.success)return`Error: ${z.error}`;let J=z.data;if(!J)return"Error: email not found.";return[`From: ${J.from}`,`To: ${J.to.join(", ")}`,J.cc.length?`CC: ${J.cc.join(", ")}`:"",`Subject: ${J.subject}`,`Date: ${J.receivedDateTime}`,`Importance: ${J.importance}`,`Attachments: ${J.hasAttachments?"Yes":"No"}`,"",J.body].filter(Boolean).join(`
1255
- `)}case"m365_send_email":{let Q=String(Z.to??""),z=String(Z.subject??""),J=String(Z.body??"");if(!Q||!z||!J)return"Error: to, subject, and body are required.";let X=await I3({to:Q,subject:z,body:J,cc:Z.cc?String(Z.cc):void 0,importance:Z.importance??void 0});if(!X.success)return`Error: ${X.error}`;return"Email sent successfully."}case"m365_list_events":{let Q=Z.fresh===!0,z=await V2({fresh:Q});if(!z.success)return`Error: ${z.error}`;return n2(z.data??[])}case"m365_create_event":{let Q=String(Z.subject??""),z=String(Z.start??""),J=String(Z.end??"");if(!Q||!z||!J)return"Error: subject, start, and end are required.";let X=await w3({subject:Q,start:z,end:J,location:Z.location?String(Z.location):void 0,body:Z.body?String(Z.body):void 0});if(!X.success)return`Error: ${X.error}`;return"Event created successfully."}case"m365_list_todos":{let Q=Z.listId?String(Z.listId):void 0,z=Z.fresh===!0,J=await G2(Q,{fresh:z});if(!J.success)return`Error: ${J.error}`;return r2(J.data??[])}case"m365_create_todo":{let Q=String(Z.title??"");if(!Q)return"Error: title is required.";let z=await S3({title:Q,listId:Z.listId?String(Z.listId):void 0,dueDateTime:Z.dueDateTime?String(Z.dueDateTime):void 0,importance:Z.importance??void 0});if(!z.success)return`Error: ${z.error}`;return"Task created successfully."}case"m365_complete_todo":{let Q=String(Z.taskId??"");if(!Q)return"Error: taskId is required.";let z=await k3(Q,Z.listId?String(Z.listId):void 0);if(!z.success)return`Error: ${z.error}`;return"Task marked as completed."}case"m365_list_files":{let Q=Z.folder?String(Z.folder):void 0,z=Z.fresh===!0,J=await f5(Q,{fresh:z});if(!J.success)return`Error: ${J.error}`;return b5(J.data??[])}case"m365_briefing":{let Q=Z.fresh===!0;return(await f3({fresh:Q})).formatted}default:return null}}async function WQ($,Z){let Y=$[0]?.toLowerCase()??"help",Q=$.slice(1);if(Y!=="help"){if(!await R3())return Z.showError(`M365 CLI not found.
1246
+ `)}function I3($){if(!$)return"(unknown)";if(typeof $==="string")return $;if(typeof $==="object"){let Y=$.emailAddress;if(Y)return`${Y.name??""} <${Y.address??""}>`.trim()}return String($)}function i($,Z=""){if($===void 0||$===null)return Z;return String($)}async function h1($={}){if(!$.fresh){let Q=i0("outlook:message:list");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await e(["outlook","message","list","--folderName","inbox"]);if(Y.success&&Y.data){let Q=Y.data.map((z)=>{let J=z;return{id:i(J.id,""),subject:i(J.subject,"(no subject)"),from:I3(J.from),receivedDateTime:i(J.receivedDateTime),isRead:J.isRead===!0,bodyPreview:i(J.bodyPreview),importance:i(J.importance,"normal")}});return n0("outlook:message:list",Q,"emails"),{success:!0,data:Q,error:null,raw:Y.raw,duration:Y.duration}}return Y}async function S3($){let Z=await e(["outlook","message","get","--id",$]);if(Z.success&&Z.data){let Y=Z.data,Q=Array.isArray(Y.toRecipients)?Y.toRecipients.map(I3):[],z=Array.isArray(Y.ccRecipients)?Y.ccRecipients.map(I3):[],J=typeof Y.body==="object"&&Y.body?i(Y.body.content):i(Y.bodyPreview);return{success:!0,data:{id:i(Y.id),subject:i(Y.subject,"(no subject)"),from:I3(Y.from),to:Q,cc:z,receivedDateTime:i(Y.receivedDateTime),isRead:Y.isRead===!0,body:J,importance:i(Y.importance,"normal"),hasAttachments:Y.hasAttachments===!0},error:null,raw:Z.raw,duration:Z.duration}}return Z}async function w3($){let Z=["outlook","mail","send","--to",$.to,"--subject",$.subject,"--bodyContents",$.body];if($.cc)Z.push("--cc",$.cc);if($.importance&&$.importance!=="normal")Z.push("--importance",$.importance);return e(Z,{jsonOutput:!1})}function G2($){if($.length===0)return"No emails found.";let Z=["--- Inbox ---"];for(let Y of $){let Q=Y.isRead?" ":"*",z=Y.id?Y.id.slice(-6):"------",J=Y.receivedDateTime?new Date(Y.receivedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"",X=Y.bodyPreview?.slice(0,60)??"";if(Z.push(`${Q} [${z}] ${J} | ${Y.from}`),Z.push(` ${Y.subject}`),X)Z.push(` ${X}...`)}return Z.push(`--- ${$.filter((Y)=>!Y.isRead).length} unread ---`),Z.join(`
1247
+ `)}async function W2($={}){if(!$.fresh){let Q=i0("outlook:event:list");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await e(["outlook","event","list"]);if(Y.success&&Y.data){let Q=Y.data.map((z)=>{let J=z,X=typeof J.start==="object"&&J.start?i(J.start.dateTime):i(J.start),K=typeof J.end==="object"&&J.end?i(J.end.dateTime):i(J.end);return{id:i(J.id),subject:i(J.subject,"(no subject)"),start:X,end:K,location:typeof J.location==="object"&&J.location?i(J.location.displayName):i(J.location),organizer:I3(J.organizer),isAllDay:J.isAllDay===!0,status:i(J.showAs??J.status,"")}});return n0("outlook:event:list",Q,"calendar"),{success:!0,data:Q,error:null,raw:Y.raw,duration:Y.duration}}return Y}async function k3($){let Z=["outlook","event","add","--subject",$.subject,"--startDateTime",$.start,"--endDateTime",$.end];if($.location)Z.push("--location",$.location);if($.body)Z.push("--bodyContents",$.body);if($.isAllDay)Z.push("--isAllDay");return e(Z,{jsonOutput:!1})}function a2($){if($.length===0)return"No events found.";let Z=["--- Calendar ---"];for(let Y of $){let Q=Y.start?new Date(Y.start).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",z=Y.end?new Date(Y.end).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",J=Y.location?` @ ${Y.location}`:"";Z.push(` ${Q}-${z} ${Y.subject}${J}`)}return Z.push("----------------"),Z.join(`
1248
+ `)}async function JQ($={}){if(!$.fresh){let Q=i0("outlook:contact:list");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await e(["outlook","contact","list"]);if(Y.success&&Y.data){let Q=Y.data.map((z)=>{let J=z;return{id:i(J.id),displayName:i(J.displayName,"(unnamed)"),emailAddresses:Array.isArray(J.emailAddresses)?J.emailAddresses.map((X)=>{if(typeof X==="string")return X;if(typeof X==="object"&&X)return i(X.address);return""}).filter(Boolean):[],phoneNumbers:Array.isArray(J.phones)?J.phones.map((X)=>{if(typeof X==="string")return X;if(typeof X==="object"&&X)return i(X.number);return""}).filter(Boolean):[],company:J.companyName?i(J.companyName):null,jobTitle:J.jobTitle?i(J.jobTitle):null}});return n0("outlook:contact:list",Q,"contacts"),{success:!0,data:Q,error:null,raw:Y.raw,duration:Y.duration}}return Y}function XQ($){if($.length===0)return"No contacts found.";let Z=["--- Contacts ---"];for(let Y of $){let Q=Y.emailAddresses[0]??"",z=Y.jobTitle?` (${Y.jobTitle})`:"";Z.push(` ${Y.displayName}${z} - ${Q}`)}return Z.push("----------------"),Z.join(`
1249
+ `)}async function KQ($={}){if(!$.fresh){let Q=i0("todo:lists");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await e(["todo","list","list"]);if(Y.success&&Y.data)n0("todo:lists",Y.data,"todo");return Y}async function H2($,Z={}){let Y=`todo:tasks:${$??"default"}`;if(!Z.fresh){let J=i0(Y);if(J)return{success:!0,data:J,error:null,raw:"",duration:0}}let Q=["todo","task","list"];if($)Q.push("--listId",$);else Q.push("--listName","Tasks");let z=await e(Q);if(z.success&&z.data)n0(Y,z.data,"todo");return z}async function f3($){let Z=["todo","task","add","--title",$.title];if($.listId)Z.push("--listId",$.listId);if($.dueDateTime)Z.push("--dueDateTime",$.dueDateTime);if($.importance)Z.push("--importance",$.importance);let Y=await e(Z,{jsonOutput:!1});if(Y.success)tY("todo:");return Y}async function b3($,Z){let Y=["todo","task","set","--id",$,"--status","completed"];if(Z)Y.push("--listId",Z);let Q=await e(Y,{jsonOutput:!1});if(Q.success)tY("todo:");return Q}function s2($){if($.length===0)return"No tasks found.";let Z=$.filter((z)=>z.status!=="completed"),Y=$.filter((z)=>z.status==="completed"),Q=["--- To Do ---"];if(Z.length>0)for(let z of Z){let J=z.dueDateTime?` (due: ${new Date(z.dueDateTime).toLocaleDateString("pt-BR")})`:"",X=z.importance==="high"?" !":"";Q.push(` [ ] ${z.title}${J}${X}`)}if(Y.length>0)Q.push(` --- ${Y.length} completed ---`);return Q.push("-------------"),Q.join(`
1250
+ `)}function VQ($){if($.length===0)return"No task lists found.";let Z=["--- To Do Lists ---"];for(let Y of $){let Q=Y.isShared?" (shared)":"";Z.push(` ${Y.displayName}${Q} [${Y.id.slice(-6)}]`)}return Z.push("-------------------"),Z.join(`
1251
+ `)}async function y5($,Z={}){let Q=`onedrive:list:${$??"/"}`;if(!Z.fresh){let X=i0(Q);if(X)return{success:!0,data:X,error:null,raw:"",duration:0}}let z=["onedrive","list"];if($)z.push("--folderUrl",$);let J=await e(z);if(J.success&&J.data)n0(Q,J.data,"files");return J}function v5($){if($.length===0)return"No files found.";let Z=["--- OneDrive ---"];for(let Y of $){let Q=Y.isFolder?"[D]":"[F]",z=Y.isFolder?"":` (${kM(Y.size)})`,J=new Date(Y.lastModifiedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` ${Q} ${Y.name}${z} - ${J}`)}return Z.push("----------------"),Z.join(`
1252
+ `)}function kM($){if($===0)return"0 B";let Z=1024,Y=["B","KB","MB","GB"],Q=Math.floor(Math.log($)/Math.log(Z));return`${($/Math.pow(Z,Q)).toFixed(1)} ${Y[Q]}`}async function GQ($={}){if(!$.fresh){let Q=i0("onenote:notebooks");if(Q)return{success:!0,data:Q,error:null,raw:"",duration:0}}let Y=await e(["onenote","notebook","list"]);if(Y.success&&Y.data)n0("onenote:notebooks",Y.data,"onenote");return Y}async function WQ($,Z={}){let Y=`onenote:pages:${$}`;if(!Z.fresh){let z=i0(Y);if(z)return{success:!0,data:z,error:null,raw:"",duration:0}}let Q=await e(["onenote","page","list","--name",$]);if(Q.success&&Q.data)n0(Y,Q.data,"onenote");return Q}function HQ($){if($.length===0)return"No notebooks found.";let Z=["--- OneNote ---"];for(let Y of $){let Q=Y.isShared?" (shared)":"",z=new Date(Y.lastModifiedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` ${Y.displayName}${Q} - ${z}`)}return Z.push("---------------"),Z.join(`
1253
+ `)}function UQ($){if($.length===0)return"No pages found.";let Z=["--- Pages ---"];for(let Y of $){let Q=new Date(Y.lastModifiedDateTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` ${Y.title} - ${Q}`)}return Z.push("-------------"),Z.join(`
1254
+ `)}async function y3($={}){let Z=$.fresh??!1,[Y,Q,z]=await Promise.all([h1({top:10,fresh:Z}),W2({fresh:Z}),H2(void 0,{fresh:Z})]),J=Y.success&&Y.data?Y.data.filter((W)=>!W.isRead):[],X=Q.success&&Q.data?Q.data:[],K=z.success&&z.data?z.data.filter((W)=>W.status!=="completed"):[],V={unreadEmails:J,todayEvents:X,pendingTodos:K,timestamp:Date.now()},G=["=== M365 Briefing ===",""];if(!Y.success)G.push(`Emails: Error - ${Y.error}`);else if(J.length===0)G.push("Emails: Inbox clear");else G.push(`Emails: ${J.length} unread`),G.push(G2(J));if(G.push(""),!Q.success)G.push(`Calendar: Error - ${Q.error}`);else if(X.length===0)G.push("Calendar: No events today");else G.push(`Calendar: ${X.length} events`),G.push(a2(X));if(G.push(""),!z.success)G.push(`To Do: Error - ${z.error}`);else if(K.length===0)G.push("To Do: All clear");else G.push(`To Do: ${K.length} pending`),G.push(s2(K));return G.push(""),G.push("====================="),{success:!0,data:V,formatted:G.join(`
1255
+ `)}}async function qQ(){let[$,Z,Y]=await Promise.all([h1({top:50,fresh:!0}),W2({fresh:!0}),H2(void 0,{fresh:!0})]),Q=$.success&&$.data?$.data.length:0,z=Z.success&&Z.data?Z.data.length:0,J=Y.success&&Y.data?Y.data.filter((V)=>V.status==="completed").length:0,X=Y.success&&Y.data?Y.data.filter((V)=>V.status!=="completed").length:0;return{success:!0,formatted:["=== M365 Weekly Digest ===","",`Emails received: ${Q}`,`Calendar events: ${z}`,`Tasks completed: ${J}`,`Tasks pending: ${X}`,"","=========================="].join(`
1256
+ `)}}async function BQ($){if(!$.trim())return{success:!1,formatted:"Error: search query is required."};let Z=await h1({top:50,fresh:!0}),Y=Z.success&&Z.data?Z.data.filter((z)=>{let J=$.toLowerCase();return z.subject.toLowerCase().includes(J)||z.bodyPreview.toLowerCase().includes(J)||z.from.toLowerCase().includes(J)}):[],Q=[`=== M365 Search: "${$}" ===`,""];if(Y.length>0)Q.push(`Emails: ${Y.length} matches`),Q.push(G2(Y));else Q.push("Emails: no matches");return Q.push(""),Q.push("=============================="),{success:!0,formatted:Q.join(`
1257
+ `)}}var YZ=[{name:"m365_list_emails",description:"List recent inbox emails from Microsoft 365. Returns subject, sender, date, and preview. Requires M365 CLI login via /m365 login.",input_schema:{type:"object",properties:{top:{type:"number",description:"Number of emails to fetch (default: 20, max: 50)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_read_email",description:"Read a specific email by ID from Microsoft 365. Returns full body and metadata.",input_schema:{type:"object",properties:{id:{type:"string",description:"Email ID (from m365_list_emails)"}},required:["id"]}},{name:"m365_send_email",description:"Send an email via Microsoft 365.",input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC email address (optional)"},importance:{type:"string",description:"low, normal, or high (default: normal)"}},required:["to","subject","body"]}},{name:"m365_list_events",description:"List calendar events from Microsoft 365 Outlook.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_create_event",description:"Create a calendar event in Microsoft 365 Outlook.",input_schema:{type:"object",properties:{subject:{type:"string",description:"Event title"},start:{type:"string",description:"Start datetime (ISO 8601)"},end:{type:"string",description:"End datetime (ISO 8601)"},location:{type:"string",description:"Event location (optional)"},body:{type:"string",description:"Event description (optional)"}},required:["subject","start","end"]}},{name:"m365_list_todos",description:"List tasks from Microsoft To Do.",input_schema:{type:"object",properties:{listId:{type:"string",description:"To Do list ID (optional, uses default list)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_create_todo",description:"Create a task in Microsoft To Do.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task title"},listId:{type:"string",description:"To Do list ID (optional)"},dueDateTime:{type:"string",description:"Due date (ISO 8601, optional)"},importance:{type:"string",description:"low, normal, or high (default: normal)"}},required:["title"]}},{name:"m365_complete_todo",description:"Mark a Microsoft To Do task as completed.",input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"},listId:{type:"string",description:"To Do list ID (optional)"}},required:["taskId"]}},{name:"m365_list_files",description:"List files in OneDrive.",input_schema:{type:"object",properties:{folder:{type:"string",description:"Folder path (optional, defaults to root)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"m365_briefing",description:"Get a combined Microsoft 365 briefing: unread emails, today's calendar events, and pending To Do tasks. Fetches all data in parallel.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}}];async function NQ($,Z){if(!$.startsWith("m365_"))return null;if(!await $Q())return"Not connected to Microsoft 365. Run /m365 login to authenticate.";switch($){case"m365_list_emails":{let Q=typeof Z.top==="number"?Z.top:void 0,z=Z.fresh===!0,J=await h1({top:Q,fresh:z});if(!J.success)return`Error: ${J.error}`;return G2(J.data??[])}case"m365_read_email":{let Q=String(Z.id??"");if(!Q)return"Error: email ID is required.";let z=await S3(Q);if(!z.success)return`Error: ${z.error}`;let J=z.data;if(!J)return"Error: email not found.";return[`From: ${J.from}`,`To: ${J.to.join(", ")}`,J.cc.length?`CC: ${J.cc.join(", ")}`:"",`Subject: ${J.subject}`,`Date: ${J.receivedDateTime}`,`Importance: ${J.importance}`,`Attachments: ${J.hasAttachments?"Yes":"No"}`,"",J.body].filter(Boolean).join(`
1258
+ `)}case"m365_send_email":{let Q=String(Z.to??""),z=String(Z.subject??""),J=String(Z.body??"");if(!Q||!z||!J)return"Error: to, subject, and body are required.";let X=await w3({to:Q,subject:z,body:J,cc:Z.cc?String(Z.cc):void 0,importance:Z.importance??void 0});if(!X.success)return`Error: ${X.error}`;return"Email sent successfully."}case"m365_list_events":{let Q=Z.fresh===!0,z=await W2({fresh:Q});if(!z.success)return`Error: ${z.error}`;return a2(z.data??[])}case"m365_create_event":{let Q=String(Z.subject??""),z=String(Z.start??""),J=String(Z.end??"");if(!Q||!z||!J)return"Error: subject, start, and end are required.";let X=await k3({subject:Q,start:z,end:J,location:Z.location?String(Z.location):void 0,body:Z.body?String(Z.body):void 0});if(!X.success)return`Error: ${X.error}`;return"Event created successfully."}case"m365_list_todos":{let Q=Z.listId?String(Z.listId):void 0,z=Z.fresh===!0,J=await H2(Q,{fresh:z});if(!J.success)return`Error: ${J.error}`;return s2(J.data??[])}case"m365_create_todo":{let Q=String(Z.title??"");if(!Q)return"Error: title is required.";let z=await f3({title:Q,listId:Z.listId?String(Z.listId):void 0,dueDateTime:Z.dueDateTime?String(Z.dueDateTime):void 0,importance:Z.importance??void 0});if(!z.success)return`Error: ${z.error}`;return"Task created successfully."}case"m365_complete_todo":{let Q=String(Z.taskId??"");if(!Q)return"Error: taskId is required.";let z=await b3(Q,Z.listId?String(Z.listId):void 0);if(!z.success)return`Error: ${z.error}`;return"Task marked as completed."}case"m365_list_files":{let Q=Z.folder?String(Z.folder):void 0,z=Z.fresh===!0,J=await y5(Q,{fresh:z});if(!J.success)return`Error: ${J.error}`;return v5(J.data??[])}case"m365_briefing":{let Q=Z.fresh===!0;return(await y3({fresh:Q})).formatted}default:return null}}async function OQ($,Z){let Y=$[0]?.toLowerCase()??"help",Q=$.slice(1);if(Y!=="help"){if(!await P3())return Z.showError(`M365 CLI not found.
1256
1259
  Run: bun install
1257
- Docs: https://pnp.github.io/cli-microsoft365/`),!0}switch(Y){case"login":{let z=Q[0]||void 0;Z.showSystem("Starting M365 login...");let J=await aY((X)=>Z.showSystem(X),z);return Z.showSystem(J),!0}case"logout":{let z=await sY();return Z.showSystem(z),!0}case"status":{let z=await s9();return Z.showSystem(eY(z)),!0}case"consent":{let z=tY();return Z.showSystem(`Open this URL in your browser to grant permissions:
1260
+ Docs: https://pnp.github.io/cli-microsoft365/`),!0}switch(Y){case"login":{let z=Q[0]||void 0;Z.showSystem("Starting M365 login...");let J=await ZQ((X)=>Z.showSystem(X),z);return Z.showSystem(J),!0}case"logout":{let z=await YQ();return Z.showSystem(z),!0}case"status":{let z=await ZZ();return Z.showSystem(zQ(z)),!0}case"consent":{let z=QQ();return Z.showSystem(`Open this URL in your browser to grant permissions:
1258
1261
 
1259
1262
  `+z+`
1260
1263
 
1261
- After consenting, run /m365 login again.`),!0}case"refresh":return P3(),Z.showSystem("M365 cache cleared."),!0;case"cache":{let z=nY();return Z.showSystem(`Cache: ${z.size} entries
1264
+ After consenting, run /m365 login again.`),!0}case"refresh":return D3(),Z.showSystem("M365 cache cleared."),!0;case"cache":{let z=eY();return Z.showSystem(`Cache: ${z.size} entries
1262
1265
  ${z.keys.map((J)=>` ${J}`).join(`
1263
- `)||" (empty)"}`),!0}case"emails":{let z=Q.includes("--fresh"),J=OM(Q,"--top")??20;Z.showSystem("Fetching emails...");let X=await x1({top:J,fresh:z});if(!X.success){if(X.error?.includes("Access is denied"))Z.showError("Access denied. Run /m365 consent to grant email permissions, then /m365 login again.");else Z.showError(X.error??"Failed to fetch emails.");return!0}return Z.showSystem(K2(X.data??[])),!0}case"email":{let z=Q[0]?.toLowerCase();if(z==="read"&&Q[1]){Z.showSystem("Fetching email...");let J=await T3(Q[1]);if(!J.success)return Z.showError(J.error??"Failed to fetch email."),!0;let X=J.data;if(!X)return Z.showError("Email not found."),!0;return Z.showSystem([`From: ${X.from}`,`To: ${X.to.join(", ")}`,X.cc.length?`CC: ${X.cc.join(", ")}`:"",`Subject: ${X.subject}`,`Date: ${X.receivedDateTime}`,"",X.body].filter(Boolean).join(`
1264
- `)),!0}if(z==="send"){let J=H2(Q,"--to"),X=H2(Q,"--subject"),K=H2(Q,"--body");if(!J||!X||!K)return Z.showError("Usage: /m365 email send --to <email> --subject <text> --body <text>"),!0;Z.showSystem("Sending email...");let V=await I3({to:J,subject:X,body:K});return Z.showSystem(V.success?"Email sent.":`Error: ${V.error}`),!0}return Z.showError("Usage: /m365 email read <id> | /m365 email send --to ... --subject ... --body ..."),!0}case"calendar":{if(Q[0]?.toLowerCase()==="add"){let K=H2(Q,"--subject"),V=H2(Q,"--start"),G=H2(Q,"--end"),H=H2(Q,"--location");if(!K||!V||!G)return Z.showError("Usage: /m365 calendar add --subject <text> --start <datetime> --end <datetime>"),!0;Z.showSystem("Creating event...");let W=await w3({subject:K,start:V,end:G,location:H??void 0});return Z.showSystem(W.success?"Event created.":`Error: ${W.error}`),!0}let J=Q.includes("--fresh");Z.showSystem("Fetching calendar...");let X=await V2({fresh:J});if(!X.success)return Z.showError(X.error??"Failed to fetch calendar."),!0;return Z.showSystem(n2(X.data??[])),!0}case"contacts":{let z=Q.includes("--fresh");Z.showSystem("Fetching contacts...");let J=await $Q({fresh:z});if(!J.success)return Z.showError(J.error??"Failed to fetch contacts."),!0;return Z.showSystem(ZQ(J.data??[])),!0}case"todo":{let z=Q[0]?.toLowerCase();if(z==="lists"){Z.showSystem("Fetching To Do lists...");let K=await YQ();if(!K.success)return Z.showError(K.error??"Failed to fetch lists."),!0;return Z.showSystem(QQ(K.data??[])),!0}if(z==="add"){let K=Q.slice(1).join(" ");if(!K)return Z.showError("Usage: /m365 todo add <task title>"),!0;Z.showSystem("Creating task...");let V=await S3({title:K});return Z.showSystem(V.success?"Task created.":`Error: ${V.error}`),!0}if(z==="done"&&Q[1]){Z.showSystem("Completing task...");let K=await k3(Q[1]);return Z.showSystem(K.success?"Task completed.":`Error: ${K.error}`),!0}let J=Q.includes("--fresh");Z.showSystem("Fetching tasks...");let X=await G2(void 0,{fresh:J});if(!X.success)return Z.showError(X.error??"Failed to fetch tasks."),!0;return Z.showSystem(r2(X.data??[])),!0}case"onedrive":{let z=Q[0]?.toLowerCase(),J=Q.includes("--fresh");if(z==="get"&&Q[1]){Z.showSystem(`Fetching file info: ${Q[1]}...`);let V=await f5(Q[1],{fresh:J});if(!V.success)return Z.showError(V.error??"Failed to fetch file."),!0;return Z.showSystem(b5(V.data??[])),!0}let X=z&&z!=="--fresh"?z:void 0;Z.showSystem("Fetching OneDrive files...");let K=await f5(X,{fresh:J});if(!K.success)return Z.showError(K.error??"Failed to fetch files."),!0;return Z.showSystem(b5(K.data??[])),!0}case"onenote":{if(Q[0]?.toLowerCase()==="pages"&&Q[1]){let X=Q.slice(1).join(" ");Z.showSystem(`Fetching pages from "${X}"...`);let K=await JQ(X);if(!K.success)return Z.showError(K.error??"Failed to fetch pages."),!0;return Z.showSystem(KQ(K.data??[])),!0}Z.showSystem("Fetching notebooks...");let J=await zQ();if(!J.success)return Z.showError(J.error??"Failed to fetch notebooks."),!0;return Z.showSystem(XQ(J.data??[])),!0}case"briefing":{let z=Q.includes("--fresh");Z.showSystem("Building M365 briefing...");let J=await f3({fresh:z});return Z.showSystem(J.formatted),!0}case"digest":{Z.showSystem("Building M365 weekly digest...");let z=await VQ();return Z.showSystem(z.formatted),!0}case"search":{let z=Q.join(" ");if(!z)return Z.showError("Usage: /m365 search <query>"),!0;Z.showSystem(`Searching M365 for "${z}"...`);let J=await GQ(z);return Z.showSystem(J.formatted),!0}case"help":default:return Z.showSystem(NM),!0}}var NM=`
1266
+ `)||" (empty)"}`),!0}case"emails":{let z=Q.includes("--fresh"),J=bM(Q,"--top")??20;Z.showSystem("Fetching emails...");let X=await h1({top:J,fresh:z});if(!X.success){if(X.error?.includes("Access is denied"))Z.showError("Access denied. Run /m365 consent to grant email permissions, then /m365 login again.");else Z.showError(X.error??"Failed to fetch emails.");return!0}return Z.showSystem(G2(X.data??[])),!0}case"email":{let z=Q[0]?.toLowerCase();if(z==="read"&&Q[1]){Z.showSystem("Fetching email...");let J=await S3(Q[1]);if(!J.success)return Z.showError(J.error??"Failed to fetch email."),!0;let X=J.data;if(!X)return Z.showError("Email not found."),!0;return Z.showSystem([`From: ${X.from}`,`To: ${X.to.join(", ")}`,X.cc.length?`CC: ${X.cc.join(", ")}`:"",`Subject: ${X.subject}`,`Date: ${X.receivedDateTime}`,"",X.body].filter(Boolean).join(`
1267
+ `)),!0}if(z==="send"){let J=U2(Q,"--to"),X=U2(Q,"--subject"),K=U2(Q,"--body");if(!J||!X||!K)return Z.showError("Usage: /m365 email send --to <email> --subject <text> --body <text>"),!0;Z.showSystem("Sending email...");let V=await w3({to:J,subject:X,body:K});return Z.showSystem(V.success?"Email sent.":`Error: ${V.error}`),!0}return Z.showError("Usage: /m365 email read <id> | /m365 email send --to ... --subject ... --body ..."),!0}case"calendar":{if(Q[0]?.toLowerCase()==="add"){let K=U2(Q,"--subject"),V=U2(Q,"--start"),G=U2(Q,"--end"),W=U2(Q,"--location");if(!K||!V||!G)return Z.showError("Usage: /m365 calendar add --subject <text> --start <datetime> --end <datetime>"),!0;Z.showSystem("Creating event...");let H=await k3({subject:K,start:V,end:G,location:W??void 0});return Z.showSystem(H.success?"Event created.":`Error: ${H.error}`),!0}let J=Q.includes("--fresh");Z.showSystem("Fetching calendar...");let X=await W2({fresh:J});if(!X.success)return Z.showError(X.error??"Failed to fetch calendar."),!0;return Z.showSystem(a2(X.data??[])),!0}case"contacts":{let z=Q.includes("--fresh");Z.showSystem("Fetching contacts...");let J=await JQ({fresh:z});if(!J.success)return Z.showError(J.error??"Failed to fetch contacts."),!0;return Z.showSystem(XQ(J.data??[])),!0}case"todo":{let z=Q[0]?.toLowerCase();if(z==="lists"){Z.showSystem("Fetching To Do lists...");let K=await KQ();if(!K.success)return Z.showError(K.error??"Failed to fetch lists."),!0;return Z.showSystem(VQ(K.data??[])),!0}if(z==="add"){let K=Q.slice(1).join(" ");if(!K)return Z.showError("Usage: /m365 todo add <task title>"),!0;Z.showSystem("Creating task...");let V=await f3({title:K});return Z.showSystem(V.success?"Task created.":`Error: ${V.error}`),!0}if(z==="done"&&Q[1]){Z.showSystem("Completing task...");let K=await b3(Q[1]);return Z.showSystem(K.success?"Task completed.":`Error: ${K.error}`),!0}let J=Q.includes("--fresh");Z.showSystem("Fetching tasks...");let X=await H2(void 0,{fresh:J});if(!X.success)return Z.showError(X.error??"Failed to fetch tasks."),!0;return Z.showSystem(s2(X.data??[])),!0}case"onedrive":{let z=Q[0]?.toLowerCase(),J=Q.includes("--fresh");if(z==="get"&&Q[1]){Z.showSystem(`Fetching file info: ${Q[1]}...`);let V=await y5(Q[1],{fresh:J});if(!V.success)return Z.showError(V.error??"Failed to fetch file."),!0;return Z.showSystem(v5(V.data??[])),!0}let X=z&&z!=="--fresh"?z:void 0;Z.showSystem("Fetching OneDrive files...");let K=await y5(X,{fresh:J});if(!K.success)return Z.showError(K.error??"Failed to fetch files."),!0;return Z.showSystem(v5(K.data??[])),!0}case"onenote":{if(Q[0]?.toLowerCase()==="pages"&&Q[1]){let X=Q.slice(1).join(" ");Z.showSystem(`Fetching pages from "${X}"...`);let K=await WQ(X);if(!K.success)return Z.showError(K.error??"Failed to fetch pages."),!0;return Z.showSystem(UQ(K.data??[])),!0}Z.showSystem("Fetching notebooks...");let J=await GQ();if(!J.success)return Z.showError(J.error??"Failed to fetch notebooks."),!0;return Z.showSystem(HQ(J.data??[])),!0}case"briefing":{let z=Q.includes("--fresh");Z.showSystem("Building M365 briefing...");let J=await y3({fresh:z});return Z.showSystem(J.formatted),!0}case"digest":{Z.showSystem("Building M365 weekly digest...");let z=await qQ();return Z.showSystem(z.formatted),!0}case"search":{let z=Q.join(" ");if(!z)return Z.showError("Usage: /m365 search <query>"),!0;Z.showSystem(`Searching M365 for "${z}"...`);let J=await BQ(z);return Z.showSystem(J.formatted),!0}case"help":default:return Z.showSystem(fM),!0}}var fM=`
1265
1268
  === Microsoft 365 Commands ===
1266
1269
 
1267
1270
  Auth:
@@ -1304,38 +1307,38 @@ Composite:
1304
1307
 
1305
1308
  Flags: --fresh (skip cache)
1306
1309
  ===============================
1307
- `.trim();function H2($,Z){let Y=$.indexOf(Z);if(Y===-1||Y>=$.length-1)return null;return $[Y+1]}function OM($,Z){let Y=H2($,Z);if(Y===null)return null;let Q=parseInt(Y,10);return Number.isNaN(Q)?null:Q}a2();t2();import{existsSync as OQ,readFileSync as AM,writeFileSync as DM,mkdirSync as TM}from"fs";import{join as h3}from"path";import{createServer as IM}from"http";var v5=null;async function YZ(){let $=await I0(["gmail","users","getProfile","--params",JSON.stringify({userId:"me"})],{timeout:15000});if(!$.success){let z={status:"disconnected",connectedAs:null,scopes:[]};return v5=z,z}let Z=$.data,Y=Z&&typeof Z==="object"&&"emailAddress"in Z?String(Z.emailAddress):null,Q={status:Y?"connected":"disconnected",connectedAs:Y,scopes:[]};return v5=Q,Q}async function CQ(){return(v5??await YZ()).status==="connected"}async function MQ($){let Z=await $Z(["auth","setup"],(Q)=>{let z=Q.trim();if(z&&$)$(z)},300000);if(v5=null,Z.success)return"Google Workspace setup complete. Use /gws status to verify.";let Y=Z.output.trim();if(Y.includes("OAuth client creation")||Y.includes("validationError")||Y.includes("manual setup"))return $?.(`
1310
+ `.trim();function U2($,Z){let Y=$.indexOf(Z);if(Y===-1||Y>=$.length-1)return null;return $[Y+1]}function bM($,Z){let Y=U2($,Z);if(Y===null)return null;let Q=parseInt(Y,10);return Number.isNaN(Q)?null:Q}t2();$5();import{existsSync as LQ,readFileSync as uM,writeFileSync as dM,mkdirSync as cM}from"fs";import{join as m3}from"path";import{createServer as lM}from"http";var _5=null;async function XZ(){let $=await S0(["gmail","users","getProfile","--params",JSON.stringify({userId:"me"})],{timeout:15000});if(!$.success){let z={status:"disconnected",connectedAs:null,scopes:[]};return _5=z,z}let Z=$.data,Y=Z&&typeof Z==="object"&&"emailAddress"in Z?String(Z.emailAddress):null,Q={status:Y?"connected":"disconnected",connectedAs:Y,scopes:[]};return _5=Q,Q}async function RQ(){return(_5??await XZ()).status==="connected"}async function jQ($){let Z=await zZ(["auth","setup"],(Q)=>{let z=Q.trim();if(z&&$)$(z)},300000);if(_5=null,Z.success)return"Google Workspace setup complete. Use /gws status to verify.";let Y=Z.output.trim();if(Y.includes("OAuth client creation")||Y.includes("validationError")||Y.includes("manual setup"))return $?.(`
1308
1311
  OAuth client auto-creation failed. Starting guided setup...
1309
- `),QZ($);if(Y)return`Setup failed: ${Y.split(`
1310
- `)[0]}`;return"Setup failed or timed out. Try again with /gws setup"}var wM=["gmail.googleapis.com","calendar-json.googleapis.com","drive.googleapis.com","people.googleapis.com"];async function QZ($){let Z=(V)=>$?.(V);Z("Step 1/4: Checking gcloud CLI...");let Y=await kM();if(!Y)return["gcloud CLI not found or no project configured.","","Install: https://cloud.google.com/sdk/docs/install","Then: gcloud auth login && gcloud config set project <your-project>"].join(`
1312
+ `),KZ($);if(Y)return`Setup failed: ${Y.split(`
1313
+ `)[0]}`;return"Setup failed or timed out. Try again with /gws setup"}var oM=["gmail.googleapis.com","calendar-json.googleapis.com","drive.googleapis.com","people.googleapis.com"];async function KZ($){let Z=(V)=>$?.(V);Z("Step 1/4: Checking gcloud CLI...");let Y=await nM();if(!Y)return["gcloud CLI not found or no project configured.","","Install: https://cloud.google.com/sdk/docs/install","Then: gcloud auth login && gcloud config set project <your-project>"].join(`
1311
1314
  `);Z(` Project: ${Y}`),Z(`
1312
- Step 2/4: Enabling Google Workspace APIs...`);let Q=await SM(Y,Z);if(!Q.every((V)=>V.success)){let V=Q.filter((G)=>!G.success);Z(` Warning: ${V.length} API(s) failed to enable. You may need to enable them manually.`)}let J=zZ(),X=h3(J,"client_secret.json");if(OQ(X))return Z(`
1315
+ Step 2/4: Enabling Google Workspace APIs...`);let Q=await iM(Y,Z);if(!Q.every((V)=>V.success)){let V=Q.filter((G)=>!G.success);Z(` Warning: ${V.length} API(s) failed to enable. You may need to enable them manually.`)}let J=VZ(),X=m3(J,"client_secret.json");if(LQ(X))return Z(`
1313
1316
  Step 3/4: client_secret.json found!`),Z("Step 4/4: Ready to login."),["APIs enabled and client_secret.json detected.","Run /gws login to authenticate."].join(`
1314
1317
  `);return Z(`
1315
1318
  Step 3/4: OAuth client setup needed (manual step)`),["--- APIs enabled successfully ---","","Now create an OAuth client in Google Cloud Console:","",`1. Open: ${`https://console.cloud.google.com/apis/credentials?project=${Y}`}`,"","2. Configure OAuth consent screen (if not done):"," - User type: External (or Internal for Workspace)"," - App name: smolerclaw"," - Scopes: Gmail, Calendar, Drive, People"," - Test users: add your email","","3. Create OAuth client:",' - Click "Create Credentials" > "OAuth client ID"'," - Application type: Desktop app"," - Name: smolerclaw"," - Download the JSON file","","4. Save the downloaded JSON as:",` ${X}`,"","5. Then run: /gws login","","--- Waiting for client_secret.json ---"].join(`
1316
- `)}async function SM($,Z){let Y=[];for(let Q of wM){Z?.(` Enabling ${Q}...`);try{let z=Bun.spawn(["gcloud","services","enable",Q,"--project",$],{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>z.kill(),30000);await z.exited,clearTimeout(J);let X=z.exitCode===0;Z?.(X?` \u2713 ${Q}`:` \u2717 ${Q} (exit ${z.exitCode})`),Y.push({api:Q,success:X})}catch{Z?.(` \u2717 ${Q} (error)`),Y.push({api:Q,success:!1})}}return Y}async function kM(){try{let $=Bun.spawn(["gcloud","config","get-value","project"],{stdout:"pipe",stderr:"pipe"}),Z=setTimeout(()=>$.kill(),1e4),Y=await new Response($.stdout).text();if(await $.exited,clearTimeout(Z),$.exitCode!==0)return null;let Q=Y.trim();return Q&&Q!=="(unset)"?Q:null}catch{return null}}function zZ(){let $=process.env.USERPROFILE??process.env.HOME??"/root";return h3($,".config","gws")}function EQ(){let $=h3(zZ(),"client_secret.json");return OQ($)}function g3(){return h3(zZ(),"client_secret.json")}var fM=["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/drive.readonly"];var ZZ=null,VG=null,GG=0;async function FQ($,Z){x3();let Y=(W)=>$?.(W);Y("Reading client credentials...");let Q=xM();if(!Q)return["client_secret.json not found or invalid.",`Expected at: ${g3()}`,"Run /gws setup-guide for instructions."].join(`
1317
- `);Y(` Client ID: ${Q.clientId.slice(0,20)}...`),Y("Starting local OAuth callback server...");let{port:z,codePromise:J,server:X}=await yM(),K=`http://localhost:${z}`;Y(` Listening on ${K}`);let V=bM(Q.clientId,K,fM);Y(`
1319
+ `)}async function iM($,Z){let Y=[];for(let Q of oM){Z?.(` Enabling ${Q}...`);try{let z=Bun.spawn(["gcloud","services","enable",Q,"--project",$],{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>z.kill(),30000);await z.exited,clearTimeout(J);let X=z.exitCode===0;Z?.(X?` \u2713 ${Q}`:` \u2717 ${Q} (exit ${z.exitCode})`),Y.push({api:Q,success:X})}catch{Z?.(` \u2717 ${Q} (error)`),Y.push({api:Q,success:!1})}}return Y}async function nM(){try{let $=Bun.spawn(["gcloud","config","get-value","project"],{stdout:"pipe",stderr:"pipe"}),Z=setTimeout(()=>$.kill(),1e4),Y=await new Response($.stdout).text();if(await $.exited,clearTimeout(Z),$.exitCode!==0)return null;let Q=Y.trim();return Q&&Q!=="(unset)"?Q:null}catch{return null}}function VZ(){let $=process.env.USERPROFILE??process.env.HOME??"/root";return m3($,".config","gws")}function PQ(){let $=m3(VZ(),"client_secret.json");return LQ($)}function p3(){return m3(VZ(),"client_secret.json")}var rM=["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/drive.readonly"];var JZ=null,FG=null,LG=0;async function AQ($,Z){h3();let Y=(H)=>$?.(H);Y("Reading client credentials...");let Q=eM();if(!Q)return["client_secret.json not found or invalid.",`Expected at: ${p3()}`,"Run /gws setup-guide for instructions."].join(`
1320
+ `);Y(` Client ID: ${Q.clientId.slice(0,20)}...`),Y("Starting local OAuth callback server...");let{port:z,codePromise:J,server:X}=await sM(),K=`http://localhost:${z}`;Y(` Listening on ${K}`);let V=aM(Q.clientId,K,rM);Y(`
1318
1321
  Opening browser for authentication...`),Y(`(URL: ${V.slice(0,60)}...)
1319
1322
  `);try{if(process.platform==="win32")Bun.spawn(["rundll32","url.dll,FileProtocolHandler",V],{stdout:"ignore",stderr:"ignore"});else if(process.platform==="darwin")Bun.spawn(["open",V],{stdout:"ignore",stderr:"ignore"});else Bun.spawn(["xdg-open",V],{stdout:"ignore",stderr:"ignore"})}catch{Y(`Could not open browser. Open this URL manually:
1320
- `),Y(V)}Y("Waiting for authentication...");let G;try{G=await Promise.race([J,new Promise((W,U)=>setTimeout(()=>U(Error("timeout")),180000))])}catch(W){if(X.close(),W instanceof Error&&W.message==="timeout")return"Login timed out (3 minutes). Try /gws login again.";return`Login failed: ${W instanceof Error?W.message:String(W)}`}finally{X.close()}Y(`
1321
- Authorization code received. Exchanging for tokens...`);let H=await vM(Q.clientId,Q.clientSecret,G,K);if(!H)return"Failed to exchange authorization code for tokens.";return ZZ=H.access_token,VG=H.refresh_token??null,GG=Date.now()+H.expires_in*1000,hM(),BQ(ZZ),v5=null,Y("Tokens saved successfully."),"Login successful. Use /gws status to verify."}function bM($,Z,Y){return`https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({client_id:$,redirect_uri:Z,response_type:"code",scope:Y.join(" "),access_type:"offline",prompt:"consent"}).toString()}`}function yM(){return new Promise(($,Z)=>{let Y,Q,z=new Promise((X,K)=>{Y=X,Q=K}),J=IM((X,K)=>{let V=new URL(X.url??"/","http://127.0.0.1"),G=V.searchParams.get("code"),H=V.searchParams.get("error");if(H){K.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),K.end(`<html><body><h2>Authentication failed</h2><p>${H}</p><p>You can close this tab.</p></body></html>`),Q(Error(`OAuth error: ${H}`));return}if(G){K.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),K.end("<html><body><h2>Authentication successful!</h2><p>You can close this tab and return to smolerclaw.</p></body></html>"),Y(G);return}K.writeHead(200,{"Content-Type":"text/plain"}),K.end("Waiting for OAuth callback...")});J.listen(0,"127.0.0.1",()=>{let X=J.address();if(X&&typeof X==="object")$({port:X.port,codePromise:z,server:J});else Z(Error("Failed to start callback server"))}),J.on("error",Z)})}async function vM($,Z,Y,Q){try{let z=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:Y,client_id:$,client_secret:Z,redirect_uri:Q,grant_type:"authorization_code"})});if(!z.ok)return null;return await z.json()}catch{return null}}function xM(){let $=g3();if(!OQ($))return null;try{let Z=AM($,"utf-8"),Y=JSON.parse(Z),Q=Y.installed??Y.web;if(Q?.client_id&&Q?.client_secret)return{clientId:String(Q.client_id),clientSecret:String(Q.client_secret)};if(Y.client_id&&Y.client_secret)return{clientId:String(Y.client_id),clientSecret:String(Y.client_secret)}}catch{}return null}var _M="smolerclaw_tokens.json";function hM(){if(!ZZ)return;let $=zZ();TM($,{recursive:!0});let Z={access_token:ZZ,refresh_token:VG,token_expiry:GG,saved_at:Date.now()};DM(h3($,_M),JSON.stringify(Z,null,2),"utf-8")}async function LQ(){let $=await $Z(["auth","logout"],()=>{},15000);if(_3(),v5={status:"disconnected",connectedAs:null,scopes:[]},$.success)return"Disconnected from Google Workspace.";return $.output.trim()||"Logout completed."}function RQ($){if($.status==="connected"){let Z=["--- Google Workspace ---","Status: Connected",`Account: ${$.connectedAs}`];if($.scopes.length>0)Z.push(`Scopes: ${$.scopes.join(", ")}`);return Z.push("------------------------"),Z.join(`
1323
+ `),Y(V)}Y("Waiting for authentication...");let G;try{G=await Promise.race([J,new Promise((H,U)=>setTimeout(()=>U(Error("timeout")),180000))])}catch(H){if(X.close(),H instanceof Error&&H.message==="timeout")return"Login timed out (3 minutes). Try /gws login again.";return`Login failed: ${H instanceof Error?H.message:String(H)}`}finally{X.close()}Y(`
1324
+ Authorization code received. Exchanging for tokens...`);let W=await tM(Q.clientId,Q.clientSecret,G,K);if(!W)return"Failed to exchange authorization code for tokens.";return JZ=W.access_token,FG=W.refresh_token??null,LG=Date.now()+W.expires_in*1000,ZE(),EQ(JZ),_5=null,Y("Tokens saved successfully."),"Login successful. Use /gws status to verify."}function aM($,Z,Y){return`https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({client_id:$,redirect_uri:Z,response_type:"code",scope:Y.join(" "),access_type:"offline",prompt:"consent"}).toString()}`}function sM(){return new Promise(($,Z)=>{let Y,Q,z=new Promise((X,K)=>{Y=X,Q=K}),J=lM((X,K)=>{let V=new URL(X.url??"/","http://127.0.0.1"),G=V.searchParams.get("code"),W=V.searchParams.get("error");if(W){K.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),K.end(`<html><body><h2>Authentication failed</h2><p>${W}</p><p>You can close this tab.</p></body></html>`),Q(Error(`OAuth error: ${W}`));return}if(G){K.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),K.end("<html><body><h2>Authentication successful!</h2><p>You can close this tab and return to smolerclaw.</p></body></html>"),Y(G);return}K.writeHead(200,{"Content-Type":"text/plain"}),K.end("Waiting for OAuth callback...")});J.listen(0,"127.0.0.1",()=>{let X=J.address();if(X&&typeof X==="object")$({port:X.port,codePromise:z,server:J});else Z(Error("Failed to start callback server"))}),J.on("error",Z)})}async function tM($,Z,Y,Q){try{let z=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:Y,client_id:$,client_secret:Z,redirect_uri:Q,grant_type:"authorization_code"})});if(!z.ok)return null;return await z.json()}catch{return null}}function eM(){let $=p3();if(!LQ($))return null;try{let Z=uM($,"utf-8"),Y=JSON.parse(Z),Q=Y.installed??Y.web;if(Q?.client_id&&Q?.client_secret)return{clientId:String(Q.client_id),clientSecret:String(Q.client_secret)};if(Y.client_id&&Y.client_secret)return{clientId:String(Y.client_id),clientSecret:String(Y.client_secret)}}catch{}return null}var $E="smolerclaw_tokens.json";function ZE(){if(!JZ)return;let $=VZ();cM($,{recursive:!0});let Z={access_token:JZ,refresh_token:FG,token_expiry:LG,saved_at:Date.now()};dM(m3($,$E),JSON.stringify(Z,null,2),"utf-8")}async function DQ(){let $=await zZ(["auth","logout"],()=>{},15000);if(g3(),_5={status:"disconnected",connectedAs:null,scopes:[]},$.success)return"Disconnected from Google Workspace.";return $.output.trim()||"Logout completed."}function TQ($){if($.status==="connected"){let Z=["--- Google Workspace ---","Status: Connected",`Account: ${$.connectedAs}`];if($.scopes.length>0)Z.push(`Scopes: ${$.scopes.join(", ")}`);return Z.push("------------------------"),Z.join(`
1322
1325
  `)}return["--- Google Workspace ---","Status: Disconnected","Run /gws login to connect.","First time? Run /gws setup","------------------------"].join(`
1323
- `)}a2();t2();a2();t2();function q1($,Z=""){if($===void 0||$===null)return Z;return String($)}function q2($,Z){if(!Array.isArray($))return"";let Y=$.find((Q)=>{if(typeof Q==="object"&&Q)return Q.name===Z;return!1});if(Y&&typeof Y==="object")return q1(Y.value);return""}async function _1($={}){if(!$.fresh){let V=y5("gmail:messages:list");if(V)return{success:!0,data:V,error:null,raw:"",duration:0}}let Y=$.maxResults??20,Q=await I0(["gmail","users","messages","list","--params",JSON.stringify({userId:"me",maxResults:Y,labelIds:["INBOX"]})]);if(!Q.success)return Q;let z=Q.data&&typeof Q.data==="object"&&"messages"in Q.data?Q.data.messages:Array.isArray(Q.data)?Q.data:[];if(!z||z.length===0){let V=[];return s2("gmail:messages:list",V,"gmail"),{success:!0,data:V,error:null,raw:Q.raw,duration:Q.duration}}let J=[],X=z.slice(0,Y).map((V)=>{if(typeof V==="object"&&V)return q1(V.id);return""}).filter(Boolean),K=await Promise.all(X.map((V)=>I0(["gmail","users","messages","get","--params",JSON.stringify({userId:"me",id:V,format:"metadata",metadataHeaders:["From","Subject","Date"]})])));for(let V of K){if(!V.success||!V.data)continue;let G=V.data,W=G.payload?.headers??[],U=Array.isArray(G.labelIds)?G.labelIds:[];J.push({id:q1(G.id),threadId:q1(G.threadId),subject:q2(W,"Subject")||"(no subject)",from:q2(W,"From"),date:q2(W,"Date"),snippet:q1(G.snippet),isUnread:U.includes("UNREAD"),labelIds:U})}return s2("gmail:messages:list",J,"gmail"),{success:!0,data:J,error:null,raw:Q.raw,duration:Q.duration}}async function m3($){let Z=await I0(["gmail","users","messages","get","--params",JSON.stringify({userId:"me",id:$,format:"full"})]);if(!Z.success||!Z.data)return Z;let Y=Z.data,Q=Y.payload,z=Q?.headers??[],J=Array.isArray(Y.labelIds)?Y.labelIds:[],X=gM(Q),K=q2(z,"To"),V=q2(z,"Cc");return{success:!0,data:{id:q1(Y.id),threadId:q1(Y.threadId),subject:q2(z,"Subject")||"(no subject)",from:q2(z,"From"),to:K?K.split(",").map((H)=>H.trim()):[],cc:V?V.split(",").map((H)=>H.trim()):[],date:q2(z,"Date"),body:X,isUnread:J.includes("UNREAD"),hasAttachments:mM(Q)},error:null,raw:Z.raw,duration:Z.duration}}async function p3($){let Z=["gmail","+send","--params",JSON.stringify({userId:"me",to:$.to,subject:$.subject,body:$.body,...$.cc?{cc:$.cc}:{}})];return I0(Z)}function B2($){if($.length===0)return"Nenhum email encontrado.";let Z=["--- Gmail ---"];for(let Y of $){let Q=Y.isUnread?"*":" ",z=Y.id?Y.id.slice(-6):"------",J=Y.date?new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"",X=Y.snippet?.slice(0,60)??"";if(Z.push(`${Q} [${z}] ${J} | ${Y.from}`),Z.push(` ${Y.subject}`),X)Z.push(` ${X}...`)}return Z.push(`--- ${$.filter((Y)=>Y.isUnread).length} nao lidos ---`),Z.join(`
1324
- `)}function gM($){if(!$)return"";let Z=$.body;if(Z?.data)return jQ(q1(Z.data));let Y=$.parts;if(!Y)return"";for(let Q of Y){if(typeof Q!=="object"||!Q)continue;let z=Q;if(z.mimeType==="text/plain"){let J=z.body;if(J?.data)return jQ(q1(J.data))}}for(let Q of Y){if(typeof Q!=="object"||!Q)continue;let z=Q;if(z.mimeType==="text/html"){let J=z.body;if(J?.data)return jQ(q1(J.data))}}return""}function mM($){if(!$)return!1;let Z=$.parts;if(!Z)return!1;return Z.some((Y)=>{if(typeof Y!=="object"||!Y)return!1;return Y.filename!==""})}function jQ($){try{let Z=$.replace(/-/g,"+").replace(/_/g,"/");return atob(Z)}catch{return $}}a2();t2();function e0($,Z=""){if($===void 0||$===null)return Z;return String($)}async function N2($={}){if(!$.fresh){let V=y5("calendar:events:list");if(V)return{success:!0,data:V,error:null,raw:"",duration:0}}let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),z=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()+1),J=await I0(["calendar","events","list","--params",JSON.stringify({calendarId:"primary",timeMin:Q.toISOString(),timeMax:z.toISOString(),singleEvents:!0,orderBy:"startTime"})]);if(!J.success)return J;let K=((J.data&&typeof J.data==="object"&&"items"in J.data?J.data.items:Array.isArray(J.data)?J.data:[])??[]).map((V)=>{let G=V,H=typeof G.start==="object"&&G.start?e0(G.start.dateTime??G.start.date):e0(G.start),W=typeof G.end==="object"&&G.end?e0(G.end.dateTime??G.end.date):e0(G.end),U=typeof G.organizer==="object"&&G.organizer?e0(G.organizer.email):e0(G.organizer);return{id:e0(G.id),summary:e0(G.summary,"(no title)"),start:H,end:W,location:e0(G.location),organizer:U,status:e0(G.status),htmlLink:e0(G.htmlLink)}});return s2("calendar:events:list",K,"calendar"),{success:!0,data:K,error:null,raw:J.raw,duration:J.duration}}async function u3($){let Z={summary:$.summary,start:{dateTime:$.start},end:{dateTime:$.end}};if($.location)Z.location=$.location;if($.description)Z.description=$.description;return I0(["calendar","events","insert","--params",JSON.stringify({calendarId:"primary"}),"--json",JSON.stringify(Z)])}function e2($){if($.length===0)return"Nenhum evento encontrado.";let Z=["--- Agenda ---"];for(let Y of $){let Q=Y.start?new Date(Y.start).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",z=Y.end?new Date(Y.end).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",J=Y.location?` @ ${Y.location}`:"";Z.push(` ${Q}-${z} ${Y.summary}${J}`)}return Z.push("-----------------------"),Z.join(`
1325
- `)}_5();_5();var d3={"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:","gws.gmail":"Gmail","gws.agenda":"Calendar","gws.drive":"Drive","gws.panel_title":"Google Workspace Dashboard","gws.press_any_key":"Press any key to return","gws.unread_total":"{{unread}} unread / {{total}} total","gws.events_today":"{{count}} events today","gws.no_events":"No events scheduled","gws.items":"{{count}} items","gws.no_files":"No files found","gws.no_emails":"No emails found.","gws.inbox_clear":"Inbox clear","gws.no_events_today":"No events today","gws.no_recent_files":"No recent files","gws.unread":"{{count}} unread","gws.events":"{{count}} events","gws.recent_files":"{{count}} recent files","gws.briefing_title":"Google Workspace Briefing","gws.error":"Error: {{msg}}"};var WG={"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:","gws.gmail":"Gmail","gws.agenda":"Agenda","gws.drive":"Drive","gws.panel_title":"Painel Google Workspace","gws.press_any_key":"Pressione qualquer tecla para voltar","gws.unread_total":"{{unread}} nao lidos / {{total}} total","gws.events_today":"{{count}} eventos hoje","gws.no_events":"Nenhum evento agendado","gws.items":"{{count}} itens","gws.no_files":"Nenhum arquivo encontrado","gws.no_emails":"Nenhum email encontrado.","gws.inbox_clear":"Caixa limpa","gws.no_events_today":"Nenhum evento hoje","gws.no_recent_files":"Nenhum arquivo recente","gws.unread":"{{count}} nao lidos","gws.events":"{{count}} eventos","gws.recent_files":"{{count}} arquivos recentes","gws.briefing_title":"Resumo Google Workspace","gws.error":"Erro: {{msg}}"};function UG($){if($!=="auto")return PQ($);try{let Y=Intl.DateTimeFormat().resolvedOptions().locale;if(Y){let Q=PQ(Y);if(Q!=="en")return Q}}catch{}let Z=process.env.LANG||process.env.LC_ALL||process.env.LANGUAGE||"";if(Z)return PQ(Z);return"en"}function PQ($){if($.toLowerCase().replace(/_/g,"-").startsWith("pt"))return"pt";return"en"}var uM={en:d3,pt:WG},qG="en",AQ=d3;function BG($){qG=UG($),AQ=uM[qG]||d3}function w($,Z){let Y=AQ[$]||d3[$]||$;if(Z)for(let[Q,z]of Object.entries(Z))Y=Y.replace(new RegExp(`\\{\\{${Q}\\}\\}`,"g"),String(z));return Y}function NG(){return{...AQ}}async function c3($={}){let Z=$.fresh??!1,[Y,Q,z]=await Promise.all([_1({maxResults:10,fresh:Z}),N2({fresh:Z}),h1(void 0,{fresh:Z})]),J=Y.success&&Y.data?Y.data.filter((H)=>H.isUnread):[],X=Q.success&&Q.data?Q.data:[],K=z.success&&z.data?z.data.slice(0,10):[],V={unreadEmails:J,todayEvents:X,recentFiles:K,timestamp:Date.now()},G=[`=== ${w("gws.briefing_title")} ===`,""];if(!Y.success)G.push(`${w("gws.gmail")}: ${w("gws.error",{msg:Y.error??""})}`);else if(J.length===0)G.push(`${w("gws.gmail")}: ${w("gws.inbox_clear")}`);else G.push(`${w("gws.gmail")}: ${w("gws.unread",{count:J.length})}`),G.push(B2(J));if(G.push(""),!Q.success)G.push(`${w("gws.agenda")}: ${w("gws.error",{msg:Q.error??""})}`);else if(X.length===0)G.push(`${w("gws.agenda")}: ${w("gws.no_events_today")}`);else G.push(`${w("gws.agenda")}: ${w("gws.events",{count:X.length})}`),G.push(e2(X));if(G.push(""),!z.success)G.push(`${w("gws.drive")}: ${w("gws.error",{msg:z.error??""})}`);else if(K.length===0)G.push(`${w("gws.drive")}: ${w("gws.no_recent_files")}`);else G.push(`${w("gws.drive")}: ${w("gws.recent_files",{count:K.length})}`),G.push($1(K));return G.push(""),G.push("================================="),{success:!0,data:V,formatted:G.join(`
1326
- `)}}async function DQ($={}){let Z=$.fresh??!1,[Y,Q,z]=await Promise.all([_1({maxResults:15,fresh:Z}),N2({fresh:Z}),h1(void 0,{fresh:Z})]),J=[];if(!Y.success)J.push(w("gws.error",{msg:Y.error??""}));else{let H=Y.data??[],W=H.filter((U)=>U.isUnread);J.push(w("gws.unread_total",{unread:W.length,total:H.length})),J.push("");for(let U of H.slice(0,10)){let q=U.isUnread?"*":" ",N=U.date?new Date(U.date).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";J.push(`${q} ${N} ${U.from.slice(0,20)}`),J.push(` ${U.subject.slice(0,40)}`)}}let X=[];if(!Q.success)X.push(w("gws.error",{msg:Q.error??""}));else{let H=Q.data??[];X.push(w("gws.events_today",{count:H.length})),X.push("");for(let W of H){let U=W.start?new Date(W.start).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",q=W.end?new Date(W.end).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??";if(X.push(`${U}-${q} ${W.summary.slice(0,35)}`),W.location)X.push(` @ ${W.location.slice(0,30)}`)}if(H.length===0)X.push(w("gws.no_events"))}let K=[];if(!z.success)K.push(w("gws.error",{msg:z.error??""}));else{let H=z.data??[];K.push(w("gws.items",{count:H.length})),K.push("");for(let W of H.slice(0,10)){let q=W.mimeType==="application/vnd.google-apps.folder"?"[P]":"[A]",N=W.modifiedTime?new Date(W.modifiedTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}):"";K.push(`${q} ${W.name.slice(0,35)} ${N}`)}if(H.length===0)K.push(w("gws.no_files"))}let V=[{id:"gws-gmail",title:w("gws.gmail"),content:J},{id:"gws-calendar",title:w("gws.agenda"),content:X},{id:"gws-drive",title:w("gws.drive"),content:K}],G=[`=== ${w("gws.panel_title")} ===`,` ${w("gws.press_any_key")}`,"",`[ ${w("gws.gmail")} ]`,...J.map((H)=>` ${H}`),"",`[ ${w("gws.agenda")} ]`,...X.map((H)=>` ${H}`),"",`[ ${w("gws.drive")} ]`,...K.map((H)=>` ${H}`),"","================================"].join(`
1327
- `);return{success:!0,panels:V,formatted:G}}async function TQ($){if(!$.trim())return{success:!1,formatted:"Error: search query is required."};let[Z,Y]=await Promise.all([_1({maxResults:30,fresh:!0}),(async()=>{let{searchDriveFiles:X}=await Promise.resolve().then(() => (_5(),HG));return X($)})()]),Q=Z.success&&Z.data?Z.data.filter((X)=>{let K=$.toLowerCase();return X.subject.toLowerCase().includes(K)||X.snippet.toLowerCase().includes(K)||X.from.toLowerCase().includes(K)}):[],z=Y.success&&Y.data?Y.data:[],J=[`=== GWS Search: "${$}" ===`,""];if(Q.length>0)J.push(`Gmail: ${Q.length} matches`),J.push(B2(Q));else J.push("Gmail: no matches");if(J.push(""),z.length>0)J.push(`Drive: ${z.length} matches`),J.push($1(z));else J.push("Drive: no matches");return J.push(""),J.push("=============================="),{success:!0,formatted:J.join(`
1328
- `)}}_5();var JZ=[{name:"gws_list_emails",description:"List recent inbox emails from Gmail via Google Workspace CLI. Returns subject, sender, date, and snippet. Requires GWS CLI login via /gws login.",input_schema:{type:"object",properties:{maxResults:{type:"number",description:"Number of emails to fetch (default: 20, max: 50)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"gws_read_email",description:"Read a specific Gmail email by ID. Returns full body and metadata.",input_schema:{type:"object",properties:{id:{type:"string",description:"Email ID (from gws_list_emails)"}},required:["id"]}},{name:"gws_send_email",description:"Send an email via Gmail.",input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC email address (optional)"}},required:["to","subject","body"]}},{name:"gws_list_events",description:"List today's calendar events from Google Calendar.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"gws_create_event",description:"Create a calendar event in Google Calendar.",input_schema:{type:"object",properties:{summary:{type:"string",description:"Event title"},start:{type:"string",description:"Start datetime (ISO 8601)"},end:{type:"string",description:"End datetime (ISO 8601)"},location:{type:"string",description:"Event location (optional)"},description:{type:"string",description:"Event description (optional)"}},required:["summary","start","end"]}},{name:"gws_list_files",description:"List files in Google Drive.",input_schema:{type:"object",properties:{folderId:{type:"string",description:"Folder ID (optional, defaults to root)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"gws_search_files",description:"Search files in Google Drive by name.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query (file name)"}},required:["query"]}},{name:"gws_briefing",description:"Get a combined Google Workspace briefing: unread Gmail messages, today's Calendar events, and recent Drive files. Fetches all data in parallel.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}}];async function IQ($,Z){if(!$.startsWith("gws_"))return null;if(!await CQ())return"Not connected to Google Workspace. Run /gws login to authenticate.";switch($){case"gws_list_emails":{let Q=typeof Z.maxResults==="number"?Z.maxResults:void 0,z=Z.fresh===!0,J=await _1({maxResults:Q,fresh:z});if(!J.success)return`Error: ${J.error}`;return B2(J.data??[])}case"gws_read_email":{let Q=String(Z.id??"");if(!Q)return"Error: email ID is required.";let z=await m3(Q);if(!z.success)return`Error: ${z.error}`;let J=z.data;if(!J)return"Error: email not found.";return[`From: ${J.from}`,`To: ${J.to.join(", ")}`,J.cc.length?`CC: ${J.cc.join(", ")}`:"",`Subject: ${J.subject}`,`Date: ${J.date}`,`Attachments: ${J.hasAttachments?"Yes":"No"}`,"",J.body].filter(Boolean).join(`
1329
- `)}case"gws_send_email":{let Q=String(Z.to??""),z=String(Z.subject??""),J=String(Z.body??"");if(!Q||!z||!J)return"Error: to, subject, and body are required.";let X=await p3({to:Q,subject:z,body:J,cc:Z.cc?String(Z.cc):void 0});if(!X.success)return`Error: ${X.error}`;return"Email sent successfully."}case"gws_list_events":{let Q=Z.fresh===!0,z=await N2({fresh:Q});if(!z.success)return`Error: ${z.error}`;return e2(z.data??[])}case"gws_create_event":{let Q=String(Z.summary??""),z=String(Z.start??""),J=String(Z.end??"");if(!Q||!z||!J)return"Error: summary, start, and end are required.";let X=await u3({summary:Q,start:z,end:J,location:Z.location?String(Z.location):void 0,description:Z.description?String(Z.description):void 0});if(!X.success)return`Error: ${X.error}`;return"Event created successfully."}case"gws_list_files":{let Q=Z.folderId?String(Z.folderId):void 0,z=Z.fresh===!0,J=await h1(Q,{fresh:z});if(!J.success)return`Error: ${J.error}`;return $1(J.data??[])}case"gws_search_files":{let Q=String(Z.query??"");if(!Q)return"Error: search query is required.";let z=await x5(Q);if(!z.success)return`Error: ${z.error}`;return $1(z.data??[])}case"gws_briefing":{let Q=Z.fresh===!0;return(await c3({fresh:Q})).formatted}default:return null}}a2();t2();_5();async function wQ($,Z){let Y=$[0]?.toLowerCase()??"help",Q=$.slice(1);if(Y!=="help"){if(!await v3())return Z.showError(`Google Workspace CLI not found.
1326
+ `)}t2();$5();t2();$5();function N1($,Z=""){if($===void 0||$===null)return Z;return String($)}function N2($,Z){if(!Array.isArray($))return"";let Y=$.find((Q)=>{if(typeof Q==="object"&&Q)return Q.name===Z;return!1});if(Y&&typeof Y==="object")return N1(Y.value);return""}async function g1($={}){if(!$.fresh){let V=x5("gmail:messages:list");if(V)return{success:!0,data:V,error:null,raw:"",duration:0}}let Y=$.maxResults??20,Q=await S0(["gmail","users","messages","list","--params",JSON.stringify({userId:"me",maxResults:Y,labelIds:["INBOX"]})]);if(!Q.success)return Q;let z=Q.data&&typeof Q.data==="object"&&"messages"in Q.data?Q.data.messages:Array.isArray(Q.data)?Q.data:[];if(!z||z.length===0){let V=[];return e2("gmail:messages:list",V,"gmail"),{success:!0,data:V,error:null,raw:Q.raw,duration:Q.duration}}let J=[],X=z.slice(0,Y).map((V)=>{if(typeof V==="object"&&V)return N1(V.id);return""}).filter(Boolean),K=await Promise.all(X.map((V)=>S0(["gmail","users","messages","get","--params",JSON.stringify({userId:"me",id:V,format:"metadata",metadataHeaders:["From","Subject","Date"]})])));for(let V of K){if(!V.success||!V.data)continue;let G=V.data,H=G.payload?.headers??[],U=Array.isArray(G.labelIds)?G.labelIds:[];J.push({id:N1(G.id),threadId:N1(G.threadId),subject:N2(H,"Subject")||"(no subject)",from:N2(H,"From"),date:N2(H,"Date"),snippet:N1(G.snippet),isUnread:U.includes("UNREAD"),labelIds:U})}return e2("gmail:messages:list",J,"gmail"),{success:!0,data:J,error:null,raw:Q.raw,duration:Q.duration}}async function u3($){let Z=await S0(["gmail","users","messages","get","--params",JSON.stringify({userId:"me",id:$,format:"full"})]);if(!Z.success||!Z.data)return Z;let Y=Z.data,Q=Y.payload,z=Q?.headers??[],J=Array.isArray(Y.labelIds)?Y.labelIds:[],X=YE(Q),K=N2(z,"To"),V=N2(z,"Cc");return{success:!0,data:{id:N1(Y.id),threadId:N1(Y.threadId),subject:N2(z,"Subject")||"(no subject)",from:N2(z,"From"),to:K?K.split(",").map((W)=>W.trim()):[],cc:V?V.split(",").map((W)=>W.trim()):[],date:N2(z,"Date"),body:X,isUnread:J.includes("UNREAD"),hasAttachments:QE(Q)},error:null,raw:Z.raw,duration:Z.duration}}async function d3($){let Z=["gmail","+send","--params",JSON.stringify({userId:"me",to:$.to,subject:$.subject,body:$.body,...$.cc?{cc:$.cc}:{}})];return S0(Z)}function O2($){if($.length===0)return"Nenhum email encontrado.";let Z=["--- Gmail ---"];for(let Y of $){let Q=Y.isUnread?"*":" ",z=Y.id?Y.id.slice(-6):"------",J=Y.date?new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"",X=Y.snippet?.slice(0,60)??"";if(Z.push(`${Q} [${z}] ${J} | ${Y.from}`),Z.push(` ${Y.subject}`),X)Z.push(` ${X}...`)}return Z.push(`--- ${$.filter((Y)=>Y.isUnread).length} nao lidos ---`),Z.join(`
1327
+ `)}function YE($){if(!$)return"";let Z=$.body;if(Z?.data)return IQ(N1(Z.data));let Y=$.parts;if(!Y)return"";for(let Q of Y){if(typeof Q!=="object"||!Q)continue;let z=Q;if(z.mimeType==="text/plain"){let J=z.body;if(J?.data)return IQ(N1(J.data))}}for(let Q of Y){if(typeof Q!=="object"||!Q)continue;let z=Q;if(z.mimeType==="text/html"){let J=z.body;if(J?.data)return IQ(N1(J.data))}}return""}function QE($){if(!$)return!1;let Z=$.parts;if(!Z)return!1;return Z.some((Y)=>{if(typeof Y!=="object"||!Y)return!1;return Y.filename!==""})}function IQ($){try{let Z=$.replace(/-/g,"+").replace(/_/g,"/");return atob(Z)}catch{return $}}t2();$5();function Y1($,Z=""){if($===void 0||$===null)return Z;return String($)}async function C2($={}){if(!$.fresh){let V=x5("calendar:events:list");if(V)return{success:!0,data:V,error:null,raw:"",duration:0}}let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),z=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()+1),J=await S0(["calendar","events","list","--params",JSON.stringify({calendarId:"primary",timeMin:Q.toISOString(),timeMax:z.toISOString(),singleEvents:!0,orderBy:"startTime"})]);if(!J.success)return J;let K=((J.data&&typeof J.data==="object"&&"items"in J.data?J.data.items:Array.isArray(J.data)?J.data:[])??[]).map((V)=>{let G=V,W=typeof G.start==="object"&&G.start?Y1(G.start.dateTime??G.start.date):Y1(G.start),H=typeof G.end==="object"&&G.end?Y1(G.end.dateTime??G.end.date):Y1(G.end),U=typeof G.organizer==="object"&&G.organizer?Y1(G.organizer.email):Y1(G.organizer);return{id:Y1(G.id),summary:Y1(G.summary,"(no title)"),start:W,end:H,location:Y1(G.location),organizer:U,status:Y1(G.status),htmlLink:Y1(G.htmlLink)}});return e2("calendar:events:list",K,"calendar"),{success:!0,data:K,error:null,raw:J.raw,duration:J.duration}}async function c3($){let Z={summary:$.summary,start:{dateTime:$.start},end:{dateTime:$.end}};if($.location)Z.location=$.location;if($.description)Z.description=$.description;return S0(["calendar","events","insert","--params",JSON.stringify({calendarId:"primary"}),"--json",JSON.stringify(Z)])}function Z5($){if($.length===0)return"Nenhum evento encontrado.";let Z=["--- Agenda ---"];for(let Y of $){let Q=Y.start?new Date(Y.start).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",z=Y.end?new Date(Y.end).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",J=Y.location?` @ ${Y.location}`:"";Z.push(` ${Q}-${z} ${Y.summary}${J}`)}return Z.push("-----------------------"),Z.join(`
1328
+ `)}g5();g5();var l3={"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:","gws.gmail":"Gmail","gws.agenda":"Calendar","gws.drive":"Drive","gws.panel_title":"Google Workspace Dashboard","gws.press_any_key":"Press any key to return","gws.unread_total":"{{unread}} unread / {{total}} total","gws.events_today":"{{count}} events today","gws.no_events":"No events scheduled","gws.items":"{{count}} items","gws.no_files":"No files found","gws.no_emails":"No emails found.","gws.inbox_clear":"Inbox clear","gws.no_events_today":"No events today","gws.no_recent_files":"No recent files","gws.unread":"{{count}} unread","gws.events":"{{count}} events","gws.recent_files":"{{count}} recent files","gws.briefing_title":"Google Workspace Briefing","gws.error":"Error: {{msg}}"};var jG={"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:","gws.gmail":"Gmail","gws.agenda":"Agenda","gws.drive":"Drive","gws.panel_title":"Painel Google Workspace","gws.press_any_key":"Pressione qualquer tecla para voltar","gws.unread_total":"{{unread}} nao lidos / {{total}} total","gws.events_today":"{{count}} eventos hoje","gws.no_events":"Nenhum evento agendado","gws.items":"{{count}} itens","gws.no_files":"Nenhum arquivo encontrado","gws.no_emails":"Nenhum email encontrado.","gws.inbox_clear":"Caixa limpa","gws.no_events_today":"Nenhum evento hoje","gws.no_recent_files":"Nenhum arquivo recente","gws.unread":"{{count}} nao lidos","gws.events":"{{count}} eventos","gws.recent_files":"{{count}} arquivos recentes","gws.briefing_title":"Resumo Google Workspace","gws.error":"Erro: {{msg}}"};function PG($){if($!=="auto")return SQ($);try{let Y=Intl.DateTimeFormat().resolvedOptions().locale;if(Y){let Q=SQ(Y);if(Q!=="en")return Q}}catch{}let Z=process.env.LANG||process.env.LC_ALL||process.env.LANGUAGE||"";if(Z)return SQ(Z);return"en"}function SQ($){if($.toLowerCase().replace(/_/g,"-").startsWith("pt"))return"pt";return"en"}var JE={en:l3,pt:jG},AG="en",wQ=l3;function DG($){AG=PG($),wQ=JE[AG]||l3}function S($,Z){let Y=wQ[$]||l3[$]||$;if(Z)for(let[Q,z]of Object.entries(Z))Y=Y.replace(new RegExp(`\\{\\{${Q}\\}\\}`,"g"),String(z));return Y}function TG(){return{...wQ}}async function o3($={}){let Z=$.fresh??!1,[Y,Q,z]=await Promise.all([g1({maxResults:10,fresh:Z}),C2({fresh:Z}),m1(void 0,{fresh:Z})]),J=Y.success&&Y.data?Y.data.filter((W)=>W.isUnread):[],X=Q.success&&Q.data?Q.data:[],K=z.success&&z.data?z.data.slice(0,10):[],V={unreadEmails:J,todayEvents:X,recentFiles:K,timestamp:Date.now()},G=[`=== ${S("gws.briefing_title")} ===`,""];if(!Y.success)G.push(`${S("gws.gmail")}: ${S("gws.error",{msg:Y.error??""})}`);else if(J.length===0)G.push(`${S("gws.gmail")}: ${S("gws.inbox_clear")}`);else G.push(`${S("gws.gmail")}: ${S("gws.unread",{count:J.length})}`),G.push(O2(J));if(G.push(""),!Q.success)G.push(`${S("gws.agenda")}: ${S("gws.error",{msg:Q.error??""})}`);else if(X.length===0)G.push(`${S("gws.agenda")}: ${S("gws.no_events_today")}`);else G.push(`${S("gws.agenda")}: ${S("gws.events",{count:X.length})}`),G.push(Z5(X));if(G.push(""),!z.success)G.push(`${S("gws.drive")}: ${S("gws.error",{msg:z.error??""})}`);else if(K.length===0)G.push(`${S("gws.drive")}: ${S("gws.no_recent_files")}`);else G.push(`${S("gws.drive")}: ${S("gws.recent_files",{count:K.length})}`),G.push(Q1(K));return G.push(""),G.push("================================="),{success:!0,data:V,formatted:G.join(`
1329
+ `)}}async function kQ($={}){let Z=$.fresh??!1,[Y,Q,z]=await Promise.all([g1({maxResults:15,fresh:Z}),C2({fresh:Z}),m1(void 0,{fresh:Z})]),J=[];if(!Y.success)J.push(S("gws.error",{msg:Y.error??""}));else{let W=Y.data??[],H=W.filter((U)=>U.isUnread);J.push(S("gws.unread_total",{unread:H.length,total:W.length})),J.push("");for(let U of W.slice(0,10)){let q=U.isUnread?"*":" ",N=U.date?new Date(U.date).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";J.push(`${q} ${N} ${U.from.slice(0,20)}`),J.push(` ${U.subject.slice(0,40)}`)}}let X=[];if(!Q.success)X.push(S("gws.error",{msg:Q.error??""}));else{let W=Q.data??[];X.push(S("gws.events_today",{count:W.length})),X.push("");for(let H of W){let U=H.start?new Date(H.start).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??",q=H.end?new Date(H.end).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"??:??";if(X.push(`${U}-${q} ${H.summary.slice(0,35)}`),H.location)X.push(` @ ${H.location.slice(0,30)}`)}if(W.length===0)X.push(S("gws.no_events"))}let K=[];if(!z.success)K.push(S("gws.error",{msg:z.error??""}));else{let W=z.data??[];K.push(S("gws.items",{count:W.length})),K.push("");for(let H of W.slice(0,10)){let q=H.mimeType==="application/vnd.google-apps.folder"?"[P]":"[A]",N=H.modifiedTime?new Date(H.modifiedTime).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}):"";K.push(`${q} ${H.name.slice(0,35)} ${N}`)}if(W.length===0)K.push(S("gws.no_files"))}let V=[{id:"gws-gmail",title:S("gws.gmail"),content:J},{id:"gws-calendar",title:S("gws.agenda"),content:X},{id:"gws-drive",title:S("gws.drive"),content:K}],G=[`=== ${S("gws.panel_title")} ===`,` ${S("gws.press_any_key")}`,"",`[ ${S("gws.gmail")} ]`,...J.map((W)=>` ${W}`),"",`[ ${S("gws.agenda")} ]`,...X.map((W)=>` ${W}`),"",`[ ${S("gws.drive")} ]`,...K.map((W)=>` ${W}`),"","================================"].join(`
1330
+ `);return{success:!0,panels:V,formatted:G}}async function fQ($){if(!$.trim())return{success:!1,formatted:"Error: search query is required."};let[Z,Y]=await Promise.all([g1({maxResults:30,fresh:!0}),(async()=>{let{searchDriveFiles:X}=await Promise.resolve().then(() => (g5(),RG));return X($)})()]),Q=Z.success&&Z.data?Z.data.filter((X)=>{let K=$.toLowerCase();return X.subject.toLowerCase().includes(K)||X.snippet.toLowerCase().includes(K)||X.from.toLowerCase().includes(K)}):[],z=Y.success&&Y.data?Y.data:[],J=[`=== GWS Search: "${$}" ===`,""];if(Q.length>0)J.push(`Gmail: ${Q.length} matches`),J.push(O2(Q));else J.push("Gmail: no matches");if(J.push(""),z.length>0)J.push(`Drive: ${z.length} matches`),J.push(Q1(z));else J.push("Drive: no matches");return J.push(""),J.push("=============================="),{success:!0,formatted:J.join(`
1331
+ `)}}g5();var GZ=[{name:"gws_list_emails",description:"List recent inbox emails from Gmail via Google Workspace CLI. Returns subject, sender, date, and snippet. Requires GWS CLI login via /gws login.",input_schema:{type:"object",properties:{maxResults:{type:"number",description:"Number of emails to fetch (default: 20, max: 50)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"gws_read_email",description:"Read a specific Gmail email by ID. Returns full body and metadata.",input_schema:{type:"object",properties:{id:{type:"string",description:"Email ID (from gws_list_emails)"}},required:["id"]}},{name:"gws_send_email",description:"Send an email via Gmail.",input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC email address (optional)"}},required:["to","subject","body"]}},{name:"gws_list_events",description:"List today's calendar events from Google Calendar.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"gws_create_event",description:"Create a calendar event in Google Calendar.",input_schema:{type:"object",properties:{summary:{type:"string",description:"Event title"},start:{type:"string",description:"Start datetime (ISO 8601)"},end:{type:"string",description:"End datetime (ISO 8601)"},location:{type:"string",description:"Event location (optional)"},description:{type:"string",description:"Event description (optional)"}},required:["summary","start","end"]}},{name:"gws_list_files",description:"List files in Google Drive.",input_schema:{type:"object",properties:{folderId:{type:"string",description:"Folder ID (optional, defaults to root)"},fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}},{name:"gws_search_files",description:"Search files in Google Drive by name.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query (file name)"}},required:["query"]}},{name:"gws_briefing",description:"Get a combined Google Workspace briefing: unread Gmail messages, today's Calendar events, and recent Drive files. Fetches all data in parallel.",input_schema:{type:"object",properties:{fresh:{type:"boolean",description:"Skip cache and fetch fresh data"}},required:[]}}];async function bQ($,Z){if(!$.startsWith("gws_"))return null;if(!await RQ())return"Not connected to Google Workspace. Run /gws login to authenticate.";switch($){case"gws_list_emails":{let Q=typeof Z.maxResults==="number"?Z.maxResults:void 0,z=Z.fresh===!0,J=await g1({maxResults:Q,fresh:z});if(!J.success)return`Error: ${J.error}`;return O2(J.data??[])}case"gws_read_email":{let Q=String(Z.id??"");if(!Q)return"Error: email ID is required.";let z=await u3(Q);if(!z.success)return`Error: ${z.error}`;let J=z.data;if(!J)return"Error: email not found.";return[`From: ${J.from}`,`To: ${J.to.join(", ")}`,J.cc.length?`CC: ${J.cc.join(", ")}`:"",`Subject: ${J.subject}`,`Date: ${J.date}`,`Attachments: ${J.hasAttachments?"Yes":"No"}`,"",J.body].filter(Boolean).join(`
1332
+ `)}case"gws_send_email":{let Q=String(Z.to??""),z=String(Z.subject??""),J=String(Z.body??"");if(!Q||!z||!J)return"Error: to, subject, and body are required.";let X=await d3({to:Q,subject:z,body:J,cc:Z.cc?String(Z.cc):void 0});if(!X.success)return`Error: ${X.error}`;return"Email sent successfully."}case"gws_list_events":{let Q=Z.fresh===!0,z=await C2({fresh:Q});if(!z.success)return`Error: ${z.error}`;return Z5(z.data??[])}case"gws_create_event":{let Q=String(Z.summary??""),z=String(Z.start??""),J=String(Z.end??"");if(!Q||!z||!J)return"Error: summary, start, and end are required.";let X=await c3({summary:Q,start:z,end:J,location:Z.location?String(Z.location):void 0,description:Z.description?String(Z.description):void 0});if(!X.success)return`Error: ${X.error}`;return"Event created successfully."}case"gws_list_files":{let Q=Z.folderId?String(Z.folderId):void 0,z=Z.fresh===!0,J=await m1(Q,{fresh:z});if(!J.success)return`Error: ${J.error}`;return Q1(J.data??[])}case"gws_search_files":{let Q=String(Z.query??"");if(!Q)return"Error: search query is required.";let z=await h5(Q);if(!z.success)return`Error: ${z.error}`;return Q1(z.data??[])}case"gws_briefing":{let Q=Z.fresh===!0;return(await o3({fresh:Q})).formatted}default:return null}}t2();$5();g5();async function yQ($,Z){let Y=$[0]?.toLowerCase()??"help",Q=$.slice(1);if(Y!=="help"){if(!await _3())return Z.showError(`Google Workspace CLI not found.
1330
1333
  Run: npm install -g @googleworkspace/cli
1331
- Docs: https://github.com/googleworkspace/cli`),!0}switch(Y){case"setup":{Z.showSystem("Starting Google Workspace setup...");let z=await MQ((J)=>Z.showSystem(J));return Z.showSystem(z),!0}case"setup-guide":{Z.showSystem("Starting guided Google Workspace setup...");let z=await QZ((J)=>Z.showSystem(J));return Z.showSystem(z),!0}case"check":{x3();let z=EQ(),J=g3();if(z)Z.showSystem(`\u2713 client_secret.json found at ${J}
1334
+ Docs: https://github.com/googleworkspace/cli`),!0}switch(Y){case"setup":{Z.showSystem("Starting Google Workspace setup...");let z=await jQ((J)=>Z.showSystem(J));return Z.showSystem(z),!0}case"setup-guide":{Z.showSystem("Starting guided Google Workspace setup...");let z=await KZ((J)=>Z.showSystem(J));return Z.showSystem(z),!0}case"check":{h3();let z=PQ(),J=p3();if(z)Z.showSystem(`\u2713 client_secret.json found at ${J}
1332
1335
  Credentials will be injected automatically.
1333
1336
  Run /gws login to authenticate.`);else Z.showError(`\u2717 client_secret.json not found.
1334
1337
  Expected at: ${J}
1335
- Run /gws setup-guide for instructions.`);return!0}case"login":{let z=Q[0]||void 0;Z.showSystem("Starting Google Workspace login...");let J=await FQ((X)=>Z.showSystem(X),z);return Z.showSystem(J),!0}case"logout":{let z=await LQ();return Z.showSystem(z),!0}case"status":{Z.showSystem("Checking Google Workspace status...");let z=await YZ();return Z.showSystem(RQ(z)),!0}case"refresh":return _3(),Z.showSystem("GWS cache cleared."),!0;case"cache":{let z=NQ();return Z.showSystem(`Cache: ${z.size} entries
1338
+ Run /gws setup-guide for instructions.`);return!0}case"login":{let z=Q[0]||void 0;Z.showSystem("Starting Google Workspace login...");let J=await AQ((X)=>Z.showSystem(X),z);return Z.showSystem(J),!0}case"logout":{let z=await DQ();return Z.showSystem(z),!0}case"status":{Z.showSystem("Checking Google Workspace status...");let z=await XZ();return Z.showSystem(TQ(z)),!0}case"refresh":return g3(),Z.showSystem("GWS cache cleared."),!0;case"cache":{let z=FQ();return Z.showSystem(`Cache: ${z.size} entries
1336
1339
  ${z.keys.map((J)=>` ${J}`).join(`
1337
- `)||" (empty)"}`),!0}case"emails":case"gmail":{let z=Q[0]?.toLowerCase();if(z==="read"&&Q[1]){Z.showSystem("Fetching email...");let V=await m3(Q[1]);if(!V.success)return Z.showError(V.error??"Failed to fetch email."),!0;let G=V.data;if(!G)return Z.showError("Email not found."),!0;return Z.showSystem([`From: ${G.from}`,`To: ${G.to.join(", ")}`,G.cc.length?`CC: ${G.cc.join(", ")}`:"",`Subject: ${G.subject}`,`Date: ${G.date}`,"",G.body].filter(Boolean).join(`
1338
- `)),!0}if(z==="send"){let V=O2(Q,"--to"),G=O2(Q,"--subject"),H=O2(Q,"--body");if(!V||!G||!H)return Z.showError("Usage: /gws gmail send --to <email> --subject <text> --body <text>"),!0;Z.showSystem("Sending email...");let W=await p3({to:V,subject:G,body:H});return Z.showSystem(W.success?"Email sent.":`Error: ${W.error}`),!0}let J=Q.includes("--fresh"),X=cM(Q,"--top")??20;Z.showSystem("Fetching emails...");let K=await _1({maxResults:X,fresh:J});if(!K.success)return Z.showError(K.error??"Failed to fetch emails."),!0;return Z.showSystem(B2(K.data??[])),!0}case"calendar":{if(Q[0]?.toLowerCase()==="add"){let K=O2(Q,"--summary"),V=O2(Q,"--start"),G=O2(Q,"--end"),H=O2(Q,"--location");if(!K||!V||!G)return Z.showError("Usage: /gws calendar add --summary <text> --start <datetime> --end <datetime>"),!0;Z.showSystem("Creating event...");let W=await u3({summary:K,start:V,end:G,location:H??void 0});return Z.showSystem(W.success?"Event created.":`Error: ${W.error}`),!0}let J=Q.includes("--fresh");Z.showSystem("Fetching calendar...");let X=await N2({fresh:J});if(!X.success)return Z.showError(X.error??"Failed to fetch calendar."),!0;return Z.showSystem(e2(X.data??[])),!0}case"drive":{let z=Q[0]?.toLowerCase();if(z==="search"&&Q[1]){let V=Q.slice(1).join(" ");Z.showSystem(`Searching Drive for "${V}"...`);let G=await x5(V);if(!G.success)return Z.showError(G.error??"Failed to search Drive."),!0;return Z.showSystem($1(G.data??[])),!0}let J=Q.includes("--fresh"),X=z&&z!=="--fresh"?z:void 0;Z.showSystem("Fetching Drive files...");let K=await h1(X,{fresh:J});if(!K.success)return Z.showError(K.error??"Failed to fetch Drive files."),!0;return Z.showSystem($1(K.data??[])),!0}case"briefing":{let z=Q.includes("--fresh");Z.showSystem("Building Google Workspace briefing...");let J=await c3({fresh:z});return Z.showSystem(J.formatted),!0}case"dashboard":case"panel":{let z=Q.includes("--fresh");Z.showSystem("Building Google Workspace dashboard...");let J=await DQ({fresh:z});if(Z.enterDashboard)Z.enterDashboard(J.panels);else Z.showSystem(J.formatted);return!0}case"search":{let z=Q.join(" ");if(!z)return Z.showError("Usage: /gws search <query>"),!0;Z.showSystem(`Searching Google Workspace for "${z}"...`);let J=await TQ(z);return Z.showSystem(J.formatted),!0}case"help":default:return Z.showSystem(dM),!0}}var dM=`
1340
+ `)||" (empty)"}`),!0}case"emails":case"gmail":{let z=Q[0]?.toLowerCase();if(z==="read"&&Q[1]){Z.showSystem("Fetching email...");let V=await u3(Q[1]);if(!V.success)return Z.showError(V.error??"Failed to fetch email."),!0;let G=V.data;if(!G)return Z.showError("Email not found."),!0;return Z.showSystem([`From: ${G.from}`,`To: ${G.to.join(", ")}`,G.cc.length?`CC: ${G.cc.join(", ")}`:"",`Subject: ${G.subject}`,`Date: ${G.date}`,"",G.body].filter(Boolean).join(`
1341
+ `)),!0}if(z==="send"){let V=M2(Q,"--to"),G=M2(Q,"--subject"),W=M2(Q,"--body");if(!V||!G||!W)return Z.showError("Usage: /gws gmail send --to <email> --subject <text> --body <text>"),!0;Z.showSystem("Sending email...");let H=await d3({to:V,subject:G,body:W});return Z.showSystem(H.success?"Email sent.":`Error: ${H.error}`),!0}let J=Q.includes("--fresh"),X=KE(Q,"--top")??20;Z.showSystem("Fetching emails...");let K=await g1({maxResults:X,fresh:J});if(!K.success)return Z.showError(K.error??"Failed to fetch emails."),!0;return Z.showSystem(O2(K.data??[])),!0}case"calendar":{if(Q[0]?.toLowerCase()==="add"){let K=M2(Q,"--summary"),V=M2(Q,"--start"),G=M2(Q,"--end"),W=M2(Q,"--location");if(!K||!V||!G)return Z.showError("Usage: /gws calendar add --summary <text> --start <datetime> --end <datetime>"),!0;Z.showSystem("Creating event...");let H=await c3({summary:K,start:V,end:G,location:W??void 0});return Z.showSystem(H.success?"Event created.":`Error: ${H.error}`),!0}let J=Q.includes("--fresh");Z.showSystem("Fetching calendar...");let X=await C2({fresh:J});if(!X.success)return Z.showError(X.error??"Failed to fetch calendar."),!0;return Z.showSystem(Z5(X.data??[])),!0}case"drive":{let z=Q[0]?.toLowerCase();if(z==="search"&&Q[1]){let V=Q.slice(1).join(" ");Z.showSystem(`Searching Drive for "${V}"...`);let G=await h5(V);if(!G.success)return Z.showError(G.error??"Failed to search Drive."),!0;return Z.showSystem(Q1(G.data??[])),!0}let J=Q.includes("--fresh"),X=z&&z!=="--fresh"?z:void 0;Z.showSystem("Fetching Drive files...");let K=await m1(X,{fresh:J});if(!K.success)return Z.showError(K.error??"Failed to fetch Drive files."),!0;return Z.showSystem(Q1(K.data??[])),!0}case"briefing":{let z=Q.includes("--fresh");Z.showSystem("Building Google Workspace briefing...");let J=await o3({fresh:z});return Z.showSystem(J.formatted),!0}case"dashboard":case"panel":{let z=Q.includes("--fresh");Z.showSystem("Building Google Workspace dashboard...");let J=await kQ({fresh:z});if(Z.enterDashboard)Z.enterDashboard(J.panels);else Z.showSystem(J.formatted);return!0}case"search":{let z=Q.join(" ");if(!z)return Z.showError("Usage: /gws search <query>"),!0;Z.showSystem(`Searching Google Workspace for "${z}"...`);let J=await fQ(z);return Z.showSystem(J.formatted),!0}case"help":default:return Z.showSystem(XE),!0}}var XE=`
1339
1342
  === Google Workspace Commands ===
1340
1343
 
1341
1344
  Auth:
@@ -1367,44 +1370,44 @@ Composite:
1367
1370
 
1368
1371
  Flags: --fresh (skip cache), --top N (limit)
1369
1372
  =================================
1370
- `.trim();function O2($,Z){let Y=$.indexOf(Z);if(Y===-1||Y>=$.length-1)return null;return $[Y+1]}function cM($,Z){let Y=O2($,Z);if(Y===null)return null;let Q=parseInt(Y,10);return Number.isNaN(Q)?null:Q}Z0();import{existsSync as OG,readdirSync as lM,readFileSync as oM,mkdirSync as iM}from"fs";import{join as SQ}from"path";function h5($){if(!OG($))return[];let Z=[],Y=lM($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let z=JSON.parse(oM(SQ($,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:SQ($,Q)})}catch{}return Z}function g5($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function XZ($,Z){let Y=$.command;for(let[H,W]of Object.entries(Z)){let U=String(W).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${H}\\}\\}`,"g"),U)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let Q=Y5(),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()]),V=await z.exited;clearTimeout(J);let G=X.trim();if(K.trim())G+=(G?`
1373
+ `.trim();function M2($,Z){let Y=$.indexOf(Z);if(Y===-1||Y>=$.length-1)return null;return $[Y+1]}function KE($,Z){let Y=M2($,Z);if(Y===null)return null;let Q=parseInt(Y,10);return Number.isNaN(Q)?null:Q}Y0();import{existsSync as IG,readdirSync as VE,readFileSync as GE,mkdirSync as WE}from"fs";import{join as vQ}from"path";function m5($){if(!IG($))return[];let Z=[],Y=VE($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let z=JSON.parse(GE(vQ($,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:vQ($,Q)})}catch{}return Z}function p5($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function WZ($,Z){let Y=$.command;for(let[W,H]of Object.entries(Z)){let U=String(H).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${W}\\}\\}`,"g"),U)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let Q=z5(),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()]),V=await z.exited;clearTimeout(J);let G=X.trim();if(K.trim())G+=(G?`
1371
1374
  `:"")+K.trim();if(V!==0)G+=(G?`
1372
- `:"")+`Exit code: ${V}`;return G||"(no output)"}function CG($){let Z=SQ($,"plugins");if(!OG(Z))iM(Z,{recursive:!0});return Z}import{existsSync as R0,readdirSync as GZ,readFileSync as o3,mkdirSync as fQ,renameSync as kQ,rmSync as l3}from"fs";import{join as n,basename as KZ,extname as VZ}from"path";z1();z1();var f=[],w0="",MG="";async function EG($,Z){if(w0=$,MG=Z,f=[],!R0($))return fQ($,{recursive:!0}),[];let Y=h5($);for(let z of Y)f=[...f,{name:z.name,description:z.description,version:"1.0.0",type:"json",source:z.source,enabled:!0,tools:g5([z]),jsonPlugin:z,eventUnsubs:[]}];let Q=GZ($).filter((z)=>{let J=VZ(z);return J===".ts"||J===".js"});for(let z of Q){let J=n($,z);try{let X=await import(J),K=X.default||X;if(!K.name||!K.description){l.debug(`Skipping invalid script plugin: ${z}`);continue}let V=await bQ(K,J);if(V)f=[...f,V]}catch(X){l.debug(`Failed to load script plugin: ${z}`,{error:X instanceof Error?X.message:String(X)})}}return G0("status:update",{source:"plugin-system",message:`${f.length} plugin(s) carregado(s)`,level:"info",timestamp:Date.now()}),f}async function bQ($,Z){let Y=n(MG,"plugins",$.name);if(!R0(Y))fQ(Y,{recursive:!0});let Q={notify:(J,X="info")=>{G0("status:update",{source:`plugin:${$.name}`,message:J,level:X,timestamp:Date.now()})},dataDir:Y};try{await $.onLoad?.(Q)}catch(J){return l.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=z0.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 FG(){return f.filter(($)=>$.enabled).flatMap(($)=>[...$.tools])}async function LG($,Z){for(let Y of f){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 XZ(Y.jsonPlugin,Z)}return null}function RG($){let Z=f.findIndex((J)=>J.name===$);if(Z===-1)return!1;let Y=f[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=n(w0,"disabled");if(!R0(Q))fQ(Q,{recursive:!0});let z=n(Q,KZ(Y.source));try{kQ(Y.source,z)}catch{}return f=f.map((J,X)=>X===Z?{...J,enabled:!1,eventUnsubs:[]}:J),G0("status:update",{source:"plugin-system",message:`Plugin "${$}" desabilitado`,level:"info",timestamp:Date.now()}),!0}async function jG($){let Z=f.findIndex((V)=>V.name===$&&!V.enabled);if(Z!==-1){let V=f[Z],G=n(w0,"disabled"),H=n(G,KZ(V.source)),W=n(w0,KZ(V.source));if(R0(H))try{kQ(H,W)}catch{}return f=f.map((U,q)=>q===Z?{...U,enabled:!0,source:W}:U),G0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}let Y=n(w0,"disabled");if(!R0(Y))return!1;let z=GZ(Y).find((V)=>{return KZ(V,VZ(V))===$});if(!z)return!1;let J=n(Y,z),X=n(w0,z);try{kQ(J,X)}catch{return!1}let K=VZ(z);if(K===".json"){let V=h5(w0).filter((G)=>G.source===X);for(let G of V)f=[...f,{name:G.name,description:G.description,version:"1.0.0",type:"json",source:G.source,enabled:!0,tools:g5([G]),jsonPlugin:G,eventUnsubs:[]}]}else if(K===".ts"||K===".js")try{let V=await import(X),G=V.default||V;if(G.name&&G.description){let H=await bQ(G,X);if(H)f=[...f,H]}}catch{}return G0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}async function PG($){if(!w0)return{success:!1,name:"",message:"Plugin system nao inicializado."};let Z=nM($);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=n(w0,"installed",`${Y}--${Q}`);if(R0(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()]),T=await C.exited;if(clearTimeout(M),T!==0){try{l3(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`git clone falhou: ${F.trim().split(`
1373
- `)[0]||`exit code ${T}`}`}}}catch(C){try{l3(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`Erro ao clonar: ${C instanceof Error?C.message:String(C)}`}}let V=rM(J);if(!V){try{l3(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 G=VZ(V.path),H=`${Y}--${Q}${G}`,W=n(w0,H);if(G===".ts"||G===".js"){let C=V.path.replace(/\\/g,"/"),M=`// Auto-installed from github.com/${Y}/${Q}
1375
+ `:"")+`Exit code: ${V}`;return G||"(no output)"}function SG($){let Z=vQ($,"plugins");if(!IG(Z))WE(Z,{recursive:!0});return Z}import{existsSync as j0,readdirSync as qZ,readFileSync as n3,mkdirSync as _Q,renameSync as xQ,rmSync as i3}from"fs";import{join as r,basename as HZ,extname as UZ}from"path";X1();X1();var f=[],w0="",wG="";async function kG($,Z){if(w0=$,wG=Z,f=[],!j0($))return _Q($,{recursive:!0}),[];let Y=m5($);for(let z of Y)f=[...f,{name:z.name,description:z.description,version:"1.0.0",type:"json",source:z.source,enabled:!0,tools:p5([z]),jsonPlugin:z,eventUnsubs:[]}];let Q=qZ($).filter((z)=>{let J=UZ(z);return J===".ts"||J===".js"});for(let z of Q){let J=r($,z);try{let X=await import(J),K=X.default||X;if(!K.name||!K.description){o.debug(`Skipping invalid script plugin: ${z}`);continue}let V=await hQ(K,J);if(V)f=[...f,V]}catch(X){o.debug(`Failed to load script plugin: ${z}`,{error:X instanceof Error?X.message:String(X)})}}return W0("status:update",{source:"plugin-system",message:`${f.length} plugin(s) carregado(s)`,level:"info",timestamp:Date.now()}),f}async function hQ($,Z){let Y=r(wG,"plugins",$.name);if(!j0(Y))_Q(Y,{recursive:!0});let Q={notify:(J,X="info")=>{W0("status:update",{source:`plugin:${$.name}`,message:J,level:X,timestamp:Date.now()})},dataDir:Y};try{await $.onLoad?.(Q)}catch(J){return o.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=J0.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 fG(){return f.filter(($)=>$.enabled).flatMap(($)=>[...$.tools])}async function bG($,Z){for(let Y of f){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 WZ(Y.jsonPlugin,Z)}return null}function yG($){let Z=f.findIndex((J)=>J.name===$);if(Z===-1)return!1;let Y=f[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=r(w0,"disabled");if(!j0(Q))_Q(Q,{recursive:!0});let z=r(Q,HZ(Y.source));try{xQ(Y.source,z)}catch{}return f=f.map((J,X)=>X===Z?{...J,enabled:!1,eventUnsubs:[]}:J),W0("status:update",{source:"plugin-system",message:`Plugin "${$}" desabilitado`,level:"info",timestamp:Date.now()}),!0}async function vG($){let Z=f.findIndex((V)=>V.name===$&&!V.enabled);if(Z!==-1){let V=f[Z],G=r(w0,"disabled"),W=r(G,HZ(V.source)),H=r(w0,HZ(V.source));if(j0(W))try{xQ(W,H)}catch{}return f=f.map((U,q)=>q===Z?{...U,enabled:!0,source:H}:U),W0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}let Y=r(w0,"disabled");if(!j0(Y))return!1;let z=qZ(Y).find((V)=>{return HZ(V,UZ(V))===$});if(!z)return!1;let J=r(Y,z),X=r(w0,z);try{xQ(J,X)}catch{return!1}let K=UZ(z);if(K===".json"){let V=m5(w0).filter((G)=>G.source===X);for(let G of V)f=[...f,{name:G.name,description:G.description,version:"1.0.0",type:"json",source:G.source,enabled:!0,tools:p5([G]),jsonPlugin:G,eventUnsubs:[]}]}else if(K===".ts"||K===".js")try{let V=await import(X),G=V.default||V;if(G.name&&G.description){let W=await hQ(G,X);if(W)f=[...f,W]}}catch{}return W0("status:update",{source:"plugin-system",message:`Plugin "${$}" habilitado`,level:"success",timestamp:Date.now()}),!0}async function xG($){if(!w0)return{success:!1,name:"",message:"Plugin system nao inicializado."};let Z=HE($);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=r(w0,"installed",`${Y}--${Q}`);if(j0(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()]),T=await C.exited;if(clearTimeout(M),T!==0){try{i3(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`git clone falhou: ${F.trim().split(`
1376
+ `)[0]||`exit code ${T}`}`}}}catch(C){try{i3(J,{recursive:!0,force:!0})}catch{}return{success:!1,name:`${Y}/${Q}`,message:`Erro ao clonar: ${C instanceof Error?C.message:String(C)}`}}let V=UE(J);if(!V){try{i3(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 G=UZ(V.path),W=`${Y}--${Q}${G}`,H=r(w0,W);if(G===".ts"||G===".js"){let C=V.path.replace(/\\/g,"/"),M=`// Auto-installed from github.com/${Y}/${Q}
1374
1377
  export { default } from '${C}'
1375
- `;Bun.write(W,M)}else{let C=o3(V.path,"utf-8");Bun.write(W,C)}if(G===".json"){let C=h5(w0).filter((M)=>M.source===W);for(let M of C)f=[...f,{name:M.name,description:M.description,version:"1.0.0",type:"json",source:W,enabled:!0,tools:g5([M]),jsonPlugin:M,eventUnsubs:[]}]}else try{let C=await import(V.path),M=C.default||C;if(M.name&&M.description){let F=await bQ(M,W);if(F)f=[...f,F]}}catch{}let q=f.find((C)=>C.source===W)?.name||`${Y}/${Q}`;G0("status:update",{source:"plugin-system",message:`Plugin "${q}" instalado de github.com/${Y}/${Q}`,level:"success",timestamp:Date.now()});let N=n(J,".smolerclaw-install.json");return Bun.write(N,JSON.stringify({source:`${Y}/${Q}`,branch:z||"default",installedAt:new Date().toISOString(),entryPoint:W,pluginName:q},null,2)),{success:!0,name:q,message:`Plugin "${q}" instalado com sucesso de github.com/${Y}/${Q}.`}}function AG($){if(!w0)return{success:!1,message:"Plugin system nao inicializado."};let Z=n(w0,"installed");if(!R0(Z))return{success:!1,message:`Plugin "${$}" nao encontrado.`};let Y=f.find((J)=>J.name===$),Q=null,z=null;if(Y){z=Y.source;let J=GZ(Z).filter((X)=>R0(n(Z,X,".smolerclaw-install.json")));for(let X of J)try{let K=JSON.parse(o3(n(Z,X,".smolerclaw-install.json"),"utf-8"));if(K.pluginName===$||K.entryPoint===z){Q=n(Z,X);break}}catch{}}else{let J=$.replace("/","--"),X=n(Z,J);if(R0(X)){Q=X;try{z=JSON.parse(o3(n(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{}f=f.filter((J)=>J.name!==$)}if(z&&R0(z))try{l3(z,{force:!0})}catch{}if(Q)try{l3(Q,{recursive:!0,force:!0})}catch{}return G0("status:update",{source:"plugin-system",message:`Plugin "${$}" desinstalado`,level:"info",timestamp:Date.now()}),{success:!0,message:`Plugin "${$}" desinstalado com sucesso.`}}function DG(){let $=n(w0,"installed");if(!R0($))return[];let Z=[],Y=GZ($);for(let Q of Y){let z=n($,Q,".smolerclaw-install.json");if(!R0(z))continue;try{let J=JSON.parse(o3(z,"utf-8"));Z.push({name:J.pluginName||Q,source:J.source||Q.replace("--","/"),installedAt:J.installedAt||"desconhecido"})}catch{}}return Z}function nM($){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 rM($){let Z=n($,"package.json");if(R0(Z))try{let z=JSON.parse(o3(Z,"utf-8"));if(z.smolerclaw){let J=n($,z.smolerclaw);if(R0(J))return{path:J}}}catch{}let Y=["plugin.json","plugin.ts","plugin.js","index.ts","index.js"];for(let z of Y){let J=n($,z);if(R0(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=n($,z);if(R0(J))return{path:J}}return null}function TG($){return f.find((Z)=>Z.name===$)}function IG(){if(f.length===0)return"Nenhum plugin carregado. Adicione arquivos em ~/.config/smolerclaw/plugins/";let $=["Plugins:"];for(let Z of f){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(`
1376
- `)}async function wG(){for(let $ of f){for(let Z of $.eventUnsubs)Z();if($.type==="script"&&$.scriptDef?.onUnload)try{await $.scriptDef.onUnload()}catch{}}f=[]}h();import{existsSync as xQ,readFileSync as fG,statSync as eM}from"fs";import{resolve as _Q}from"path";import{existsSync as aM,realpathSync as sM}from"fs";import{resolve as tM,sep as SG}from"path";var yQ=10485760;function C2($){let Z=tM($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+SG))return`Error: path outside working directory is not permitted: ${Z}`;try{if(aM(Z)){let Q=sM(Z);if(Q!==Y&&!Q.startsWith(Y+SG))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function g1($,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 vQ($){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 kG($){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,`
1378
+ `;Bun.write(H,M)}else{let C=n3(V.path,"utf-8");Bun.write(H,C)}if(G===".json"){let C=m5(w0).filter((M)=>M.source===H);for(let M of C)f=[...f,{name:M.name,description:M.description,version:"1.0.0",type:"json",source:H,enabled:!0,tools:p5([M]),jsonPlugin:M,eventUnsubs:[]}]}else try{let C=await import(V.path),M=C.default||C;if(M.name&&M.description){let F=await hQ(M,H);if(F)f=[...f,F]}}catch{}let q=f.find((C)=>C.source===H)?.name||`${Y}/${Q}`;W0("status:update",{source:"plugin-system",message:`Plugin "${q}" instalado de github.com/${Y}/${Q}`,level:"success",timestamp:Date.now()});let N=r(J,".smolerclaw-install.json");return Bun.write(N,JSON.stringify({source:`${Y}/${Q}`,branch:z||"default",installedAt:new Date().toISOString(),entryPoint:H,pluginName:q},null,2)),{success:!0,name:q,message:`Plugin "${q}" instalado com sucesso de github.com/${Y}/${Q}.`}}function _G($){if(!w0)return{success:!1,message:"Plugin system nao inicializado."};let Z=r(w0,"installed");if(!j0(Z))return{success:!1,message:`Plugin "${$}" nao encontrado.`};let Y=f.find((J)=>J.name===$),Q=null,z=null;if(Y){z=Y.source;let J=qZ(Z).filter((X)=>j0(r(Z,X,".smolerclaw-install.json")));for(let X of J)try{let K=JSON.parse(n3(r(Z,X,".smolerclaw-install.json"),"utf-8"));if(K.pluginName===$||K.entryPoint===z){Q=r(Z,X);break}}catch{}}else{let J=$.replace("/","--"),X=r(Z,J);if(j0(X)){Q=X;try{z=JSON.parse(n3(r(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{}f=f.filter((J)=>J.name!==$)}if(z&&j0(z))try{i3(z,{force:!0})}catch{}if(Q)try{i3(Q,{recursive:!0,force:!0})}catch{}return W0("status:update",{source:"plugin-system",message:`Plugin "${$}" desinstalado`,level:"info",timestamp:Date.now()}),{success:!0,message:`Plugin "${$}" desinstalado com sucesso.`}}function hG(){let $=r(w0,"installed");if(!j0($))return[];let Z=[],Y=qZ($);for(let Q of Y){let z=r($,Q,".smolerclaw-install.json");if(!j0(z))continue;try{let J=JSON.parse(n3(z,"utf-8"));Z.push({name:J.pluginName||Q,source:J.source||Q.replace("--","/"),installedAt:J.installedAt||"desconhecido"})}catch{}}return Z}function HE($){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 UE($){let Z=r($,"package.json");if(j0(Z))try{let z=JSON.parse(n3(Z,"utf-8"));if(z.smolerclaw){let J=r($,z.smolerclaw);if(j0(J))return{path:J}}}catch{}let Y=["plugin.json","plugin.ts","plugin.js","index.ts","index.js"];for(let z of Y){let J=r($,z);if(j0(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=r($,z);if(j0(J))return{path:J}}return null}function gG($){return f.find((Z)=>Z.name===$)}function mG(){if(f.length===0)return"Nenhum plugin carregado. Adicione arquivos em ~/.config/smolerclaw/plugins/";let $=["Plugins:"];for(let Z of f){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(`
1379
+ `)}async function pG(){for(let $ of f){for(let Z of $.eventUnsubs)Z();if($.type==="script"&&$.scriptDef?.onUnload)try{await $.scriptDef.onUnload()}catch{}}f=[]}g();import{existsSync as pQ,readFileSync as cG,statSync as OE}from"fs";import{resolve as uQ}from"path";import{existsSync as qE,realpathSync as BE}from"fs";import{resolve as NE,sep as uG}from"path";var gQ=10485760;function E2($){let Z=NE($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+uG))return`Error: path outside working directory is not permitted: ${Z}`;try{if(qE(Z)){let Q=BE(Z);if(Q!==Y&&!Q.startsWith(Y+uG))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function p1($,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 mQ($){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 dG($){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,`
1377
1380
  `).replace(/<(br|hr)[^>]*\/?>/gi,`
1378
1381
  `).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,`
1379
1382
 
1380
- `).trim()}function bG($){let Z=g1($,"path");if(Z)return Z;let Y=_Q($.path),Q=C2(Y);if(Q)return Q;if(!xQ(Y))return`Error: file not found: ${Y}`;let z=eM(Y).size;if(z>yQ)return`Error: file too large (${O3(z)}). Max is ${O3(yQ)}.`;let X=fG(Y,"utf-8").split(`
1381
- `),K=Math.max(1,$.offset||1),V=Math.min(2000,$.limit||500),W=X.slice(K-1,K-1+V).map((q,N)=>`${String(K+N).padStart(4)} ${q}`).join(`
1382
- `),U=X.length-(K-1+V);if(U>0)W+=`
1383
- ... (${U} more lines, total ${X.length})`;return H1(W)}function yG($,Z){let Y=g1($,"path");if(Y)return Y;let Q=_Q($.path),z=C2(Q);if(z)return z;let J=$.content,X=xQ(Q);Z.saveState(Q),P(Q,J);let K=J.split(`
1384
- `).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function vG($,Z){let Y=g1($,"path");if(Y)return Y;let Q=_Q($.path),z=C2(Q);if(z)return z;if(!xQ(Q))return`Error: file not found: ${Q}`;let J=fG(Q,"utf-8"),X=$.old_text,K=$.new_text,V=J.split(X).length-1;if(V===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(V>1)return`Error: old_text found ${V} times. It must be unique. Include more surrounding context.`;Z.saveState(Q);let G=J.split(X).join(K);P(Q,G);let H=X.split(`
1385
- `).length,W=K.split(`
1386
- `).length;return`Edited: ${Q} (replaced ${H} lines with ${W} lines)`}Z0();import{existsSync as $E,readdirSync as ZE,readFileSync as YE,statSync as QE}from"fs";import{resolve as hQ,join as _G,sep as xG}from"path";async function hG($){let Z=g1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=hQ($.path||"."),z=C2(Q);if(z)return z;let J=$.include;if(await dz())return zE(Y,Q,J);return JE(Y,Q,J)}async function zE($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let K of l5)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 XE(J,Z)}async function JE($,Z,Y){let Q;try{Q=new RegExp($)}catch(H){return`Error: invalid regex pattern: ${H instanceof Error?H.message:$}`}let z=Y||"**/*",J=new Bun.Glob(z),X=[],K=0,V=5000;for await(let H of J.scan({cwd:Z,onlyFiles:!0})){if(kZ(H))continue;if(++K>V){X.push(`... (stopped after scanning ${V} files)`);break}let W=_G(Z,H);try{let q=YE(W,"utf-8").split(`
1387
- `);for(let N=0;N<q.length;N++)if(Q.test(q[N])){if(X.push(`${H}:${N+1}:${q[N]}`),X.length>=100)break}}catch{}if(X.length>=100)break}if(X.length===0)return"No matches found.";let G=X.slice(0,100).join(`
1383
+ `).trim()}function lG($){let Z=p1($,"path");if(Z)return Z;let Y=uQ($.path),Q=E2(Y);if(Q)return Q;if(!pQ(Y))return`Error: file not found: ${Y}`;let z=OE(Y).size;if(z>gQ)return`Error: file too large (${M3(z)}). Max is ${M3(gQ)}.`;let X=cG(Y,"utf-8").split(`
1384
+ `),K=Math.max(1,$.offset||1),V=Math.min(2000,$.limit||500),H=X.slice(K-1,K-1+V).map((q,N)=>`${String(K+N).padStart(4)} ${q}`).join(`
1385
+ `),U=X.length-(K-1+V);if(U>0)H+=`
1386
+ ... (${U} more lines, total ${X.length})`;return U1(H)}function oG($,Z){let Y=p1($,"path");if(Y)return Y;let Q=uQ($.path),z=E2(Q);if(z)return z;let J=$.content,X=pQ(Q);Z.saveState(Q),j(Q,J);let K=J.split(`
1387
+ `).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function iG($,Z){let Y=p1($,"path");if(Y)return Y;let Q=uQ($.path),z=E2(Q);if(z)return z;if(!pQ(Q))return`Error: file not found: ${Q}`;let J=cG(Q,"utf-8"),X=$.old_text,K=$.new_text,V=J.split(X).length-1;if(V===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(V>1)return`Error: old_text found ${V} times. It must be unique. Include more surrounding context.`;Z.saveState(Q);let G=J.split(X).join(K);j(Q,G);let W=X.split(`
1388
+ `).length,H=K.split(`
1389
+ `).length;return`Edited: ${Q} (replaced ${W} lines with ${H} lines)`}Y0();import{existsSync as CE,readdirSync as ME,readFileSync as EE,statSync as FE}from"fs";import{resolve as dQ,join as rG,sep as nG}from"path";async function aG($){let Z=p1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=dQ($.path||"."),z=E2(Q);if(z)return z;let J=$.include;if(await ZJ())return LE(Y,Q,J);return RE(Y,Q,J)}async function LE($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let K of i5)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 jE(J,Z)}async function RE($,Z,Y){let Q;try{Q=new RegExp($)}catch(W){return`Error: invalid regex pattern: ${W instanceof Error?W.message:$}`}let z=Y||"**/*",J=new Bun.Glob(z),X=[],K=0,V=5000;for await(let W of J.scan({cwd:Z,onlyFiles:!0})){if(xZ(W))continue;if(++K>V){X.push(`... (stopped after scanning ${V} files)`);break}let H=rG(Z,W);try{let q=EE(H,"utf-8").split(`
1390
+ `);for(let N=0;N<q.length;N++)if(Q.test(q[N])){if(X.push(`${W}:${N+1}:${q[N]}`),X.length>=100)break}}catch{}if(X.length>=100)break}if(X.length===0)return"No matches found.";let G=X.slice(0,100).join(`
1388
1391
  `);if(X.length>100)G+=`
1389
- ... (showing first 100 matches)`;return H1(G)}async function gG($){let Z=g1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=hQ($.path||"."),z=C2(Q);if(z)return z;let J=new Bun.Glob(Y),X=[];for await(let V of J.scan({cwd:Q,onlyFiles:!0})){if(kZ(V))continue;if(X.push(V),X.length>=200)break}if(X.length===0)return"No files found.";let K=X.join(`
1392
+ ... (showing first 100 matches)`;return U1(G)}async function sG($){let Z=p1($,"pattern");if(Z)return Z;let Y=$.pattern,Q=dQ($.path||"."),z=E2(Q);if(z)return z;let J=new Bun.Glob(Y),X=[];for await(let V of J.scan({cwd:Q,onlyFiles:!0})){if(xZ(V))continue;if(X.push(V),X.length>=200)break}if(X.length===0)return"No files found.";let K=X.join(`
1390
1393
  `);if(X.length>=200)K+=`
1391
- ... (showing first 200 files)`;return K}function mG($){let Z=hQ($.path||"."),Y=C2(Z);if(Y)return Y;if(!$E(Z))return`Error: not found: ${Z}`;return ZE(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=QE(_G(Z,J.name)),K=O3(X.size);return`f ${J.name} ${K}`}catch{return`f ${J.name}`}}).join(`
1392
- `)}function XE($,Z){let Y=process.cwd(),Q=Y+xG,z=Z+xG,X=$.trim().split(`
1394
+ ... (showing first 200 files)`;return K}function tG($){let Z=dQ($.path||"."),Y=E2(Z);if(Y)return Y;if(!CE(Z))return`Error: not found: ${Z}`;return ME(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=FE(rG(Z,J.name)),K=M3(X.size);return`f ${J.name} ${K}`}catch{return`f ${J.name}`}}).join(`
1395
+ `)}function jE($,Z){let Y=process.cwd(),Q=Y+nG,z=Z+nG,X=$.trim().split(`
1393
1396
  `).map((G)=>{if(G.startsWith(Q))return"."+G.slice(Y.length).replace(/\\/g,"/");if(G.startsWith(z))return"."+G.slice(Z.length).replace(/\\/g,"/");return G}),K=X.length,V=X.slice(0,100).join(`
1394
1397
  `);if(K>100)V+=`
1395
- ... (${K-100} more matches)`;return H1(V)}Z0();async function pG($){let Z=g1($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),z=Y5(),J=Bun.spawn([...z,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>J.kill(),Q*1000),[K,V]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),G=await J.exited;clearTimeout(X);let H="";if(K.trim())H+=K.trim();if(V.trim())H+=(H?`
1398
+ ... (${K-100} more matches)`;return U1(V)}Y0();async function eG($){let Z=p1($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),z=z5(),J=Bun.spawn([...z,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>J.kill(),Q*1000),[K,V]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),G=await J.exited;clearTimeout(X);let W="";if(K.trim())W+=K.trim();if(V.trim())W+=(W?`
1396
1399
  `:"")+`STDERR:
1397
- `+V.trim();if(G!==0)H+=(H?`
1398
- `:"")+`Exit code: ${G}`;return H1(H||"(no output)")}async function uG($){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=vQ(Z);if(J)return J;try{let X=new AbortController,K=setTimeout(()=>X.abort(),30000),V=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Q},body:z&&Y!=="GET"&&Y!=="HEAD"?z:void 0,signal:X.signal});if(clearTimeout(K),V.status>=300&&V.status<400){let q=V.headers.get("location");if(!q)return`Status: ${V.status} (redirect with no location header)`;let N=vQ(q);if(N)return`Redirect blocked: ${N}`;return`Status: ${V.status} -> Redirect to: ${q}
1399
- (Use fetch_url on the redirect target if needed)`}let G=`${V.status} ${V.statusText}`,H=V.headers.get("content-type")||"";if(Y==="HEAD"){let q=[...V.headers.entries()].map(([N,C])=>`${N}: ${C}`).join(`
1400
+ `+V.trim();if(G!==0)W+=(W?`
1401
+ `:"")+`Exit code: ${G}`;return U1(W||"(no output)")}async function $W($){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=mQ(Z);if(J)return J;try{let X=new AbortController,K=setTimeout(()=>X.abort(),30000),V=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Q},body:z&&Y!=="GET"&&Y!=="HEAD"?z:void 0,signal:X.signal});if(clearTimeout(K),V.status>=300&&V.status<400){let q=V.headers.get("location");if(!q)return`Status: ${V.status} (redirect with no location header)`;let N=mQ(q);if(N)return`Redirect blocked: ${N}`;return`Status: ${V.status} -> Redirect to: ${q}
1402
+ (Use fetch_url on the redirect target if needed)`}let G=`${V.status} ${V.statusText}`,W=V.headers.get("content-type")||"";if(Y==="HEAD"){let q=[...V.headers.entries()].map(([N,C])=>`${N}: ${C}`).join(`
1400
1403
  `);return`Status: ${G}
1401
- ${q}`}let W=V.headers.get("content-length");if(W&&Number(W)>N3*2)return`Status: ${G}
1404
+ ${q}`}let H=V.headers.get("content-length");if(H&&Number(H)>C3*2)return`Status: ${G}
1402
1405
 
1403
- Error: response body too large (${W} bytes). Max is ${N3*2} bytes.`;let U=await V.text();if(H.includes("text/html")){let q=kG(U);return H1(`Status: ${G}
1406
+ Error: response body too large (${H} bytes). Max is ${C3*2} bytes.`;let U=await V.text();if(W.includes("text/html")){let q=dG(U);return U1(`Status: ${G}
1404
1407
 
1405
- ${q}`)}return H1(`Status: ${G}
1408
+ ${q}`)}return U1(`Status: ${G}
1406
1409
 
1407
- ${U}`)}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 dG($,Z,Y,Q,z){let J=performance.now();try{let X=await KE($,Z,Y,Q,z);return setImmediate(()=>{HY({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!X.startsWith("Error:")})}),X}catch(X){return setImmediate(()=>{HY({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${X instanceof Error?X.message:String(X)}`}}async function KE($,Z,Y,Q,z){switch($){case"read_file":return bG(Z);case"write_file":return yG(Z,Y);case"edit_file":return vG(Z,Y);case"search_files":return await hG(Z);case"find_files":return await gG(Z);case"list_directory":return mG(Z);case"run_command":return await pG(Z);case"fetch_url":return await uG(Z)}let J=await _V($,Z);if(J!==null)return J;let X=uV($,Z);if(X!==null)return X;let K=await YG($,Z);if(K!==null)return K;let V=await HQ($,Z);if(V!==null)return V;let G=await IQ($,Z);if(G!==null)return G;let H=await xV($,Z,z);if(H!==null)return H;let W=await LG($,Z);if(W!==null)return W;let U=Q.find((q)=>q.name===$);if(U)return await XZ(U,Z);return`Error: unknown tool "${$}"`}var m5=new C4,lG=[];function gQ($){lG=$}var oG=null;function mQ($){oG=$}var cG=!1;function pQ(){if(cG)return;if(cG=!0,R)k.push(..._$),k.push(...r8),k.push(...a8);else k.push(s8);k.push(...R9),k.push(...j9),k.push(...P9),k.push(...A9),k.push(D9),k.push(...T9),k.push(...I9),k.push(...w9),k.push(...i9),k.push(...y9),k.push(...g9),k.push(...S9),k.push(...k9),k.push(...f9),k.push(...v9),k.push(...b9),k.push(...x9),k.push(...n9),k.push(...gY),k.push(..._9),k.push(...h9),k.push(...t9),k.push(...JZ)}async function HZ($,Z){return dG($,Z,m5,lG,oG)}var VE=new Set([429,500,502,503,529]);async function nG($,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(GE(X)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(J+1,500,"Auth refreshed, retrying..."),await iG(500,Z.signal);continue}}if(!HE(X))throw X;let V=WE(X)??Q*Math.pow(2,J),G=X instanceof Error?X.message:String(X);Z.onRetry?.(J+1,V,G),await iG(V,Z.signal)}throw z}function GE($){if(!($ instanceof Error))return!1;return $.status===401}function HE($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&VE.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 WE($){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 iG($,Z){return new Promise((Y,Q)=>{let z=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(z),Q(Error("Aborted"))},{once:!0})})}var UE={haiku:200000,sonnet:200000,opus:200000};function M2($){return Math.ceil($.length/3.5)}function uQ($){let Z=0;for(let Y of $){if(Z+=M2(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=M2(JSON.stringify(Q.input)),Z+=M2(Q.result);Z+=10}return Z}function dQ($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(UE))if(Z.includes(Y))return Q;return 200000}function rG($,Z,Y){let Q=dQ(Z)-20000-Y;if(uQ($)<=Q)return $;let J=[],X=Q,K=[...$].reverse(),V=[];for(let H of K){let W=M2(H.content)+(H.toolCalls?.reduce((U,q)=>U+M2(JSON.stringify(q.input))+M2(q.result),0)??0)+10;if(X-W<0)break;X-=W,V.unshift(H)}let G=$.length-V.length;if(G>0)J.push({role:"user",content:`[Note: ${G} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return J.push(...V),J}function aG($,Z,Y){let Q=dQ(Z)-20000-Y;return uQ($)>Q*0.7}function sG($,Z,Y){let Q=dQ(Z)-20000-Y;if(uQ($)<=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 tG($){return`Summarize this conversation concisely. Focus on:
1410
+ ${U}`)}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 ZW($,Z,Y,Q,z){let J=performance.now();try{let X=await PE($,Z,Y,Q,z);return setImmediate(()=>{NY({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!X.startsWith("Error:")})}),X}catch(X){return setImmediate(()=>{NY({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${X instanceof Error?X.message:String(X)}`}}async function PE($,Z,Y,Q,z){switch($){case"read_file":return lG(Z);case"write_file":return oG(Z,Y);case"edit_file":return iG(Z,Y);case"search_files":return await aG(Z);case"find_files":return await sG(Z);case"list_directory":return tG(Z);case"run_command":return await eG(Z);case"fetch_url":return await $W(Z)}let J=await rV($,Z);if(J!==null)return J;let X=$G($,Z);if(X!==null)return X;let K=await BG($,Z);if(K!==null)return K;let V=await NQ($,Z);if(V!==null)return V;let G=await bQ($,Z);if(G!==null)return G;let W=await nV($,Z,z);if(W!==null)return W;let H=await bG($,Z);if(H!==null)return H;let U=Q.find((q)=>q.name===$);if(U)return await WZ(U,Z);return`Error: unknown tool "${$}"`}var u5=new R4,QW=[];function cQ($){QW=$}var zW=null;function lQ($){zW=$}var YW=!1;function oQ(){if(YW)return;if(YW=!0,R)k.push(...g$),k.push(...e8),k.push(...$6);else k.push(Z6);k.push(...D9),k.push(...T9),k.push(...I9),k.push(...S9),k.push(w9),k.push(...k9),k.push(...f9),k.push(...b9),k.push(...s9),k.push(...h9),k.push(...d9),k.push(...y9),k.push(...v9),k.push(...x9),k.push(...g9),k.push(..._9),k.push(...m9),k.push(...t9),k.push(...cY),k.push(...p9),k.push(...u9),k.push(...YZ),k.push(...GZ)}async function BZ($,Z){return ZW($,Z,u5,QW,zW)}var AE=new Set([429,500,502,503,529]);async function XW($,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(DE(X)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(J+1,500,"Auth refreshed, retrying..."),await JW(500,Z.signal);continue}}if(!TE(X))throw X;let V=IE(X)??Q*Math.pow(2,J),G=X instanceof Error?X.message:String(X);Z.onRetry?.(J+1,V,G),await JW(V,Z.signal)}throw z}function DE($){if(!($ instanceof Error))return!1;return $.status===401}function TE($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&AE.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 IE($){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 JW($,Z){return new Promise((Y,Q)=>{let z=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(z),Q(Error("Aborted"))},{once:!0})})}var SE={haiku:200000,sonnet:200000,opus:200000};function F2($){return Math.ceil($.length/3.5)}function iQ($){let Z=0;for(let Y of $){if(Z+=F2(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=F2(JSON.stringify(Q.input)),Z+=F2(Q.result);Z+=10}return Z}function nQ($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(SE))if(Z.includes(Y))return Q;return 200000}function KW($,Z,Y){let Q=nQ(Z)-20000-Y;if(iQ($)<=Q)return $;let J=[],X=Q,K=[...$].reverse(),V=[];for(let W of K){let H=F2(W.content)+(W.toolCalls?.reduce((U,q)=>U+F2(JSON.stringify(q.input))+F2(q.result),0)??0)+10;if(X-H<0)break;X-=H,V.unshift(W)}let G=$.length-V.length;if(G>0)J.push({role:"user",content:`[Note: ${G} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return J.push(...V),J}function VW($,Z,Y){let Q=nQ(Z)-20000-Y;return iQ($)>Q*0.7}function GW($,Z,Y){let Q=nQ(Z)-20000-Y;if(iQ($)<=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 WW($){return`Summarize this conversation concisely. Focus on:
1408
1411
  1. Key decisions made
1409
1412
  2. Files created or modified
1410
1413
  3. Important context the user shared
@@ -1416,32 +1419,32 @@ Be brief but preserve actionable information. Output ONLY the summary.
1416
1419
  ${$.map((Y)=>{let Q=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)Q+=`
1417
1420
  Tools used: ${Y.toolCalls.map((z)=>z.name).join(", ")}`;return Q}).join(`
1418
1421
 
1419
- `)}`}function eG($,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(`
1420
- `),X=Math.min(10,J.length),K=Math.min(5,Math.max(0,J.length-X)),V=J.length-X-K,G=[...J.slice(0,X)];if(V>0)G.push(`... (${V} lines omitted)`);if(K>0)G.push(...J.slice(-K));let H=G.join(`
1421
- `);return{...z,result:H}});return{...Y,toolCalls:Q}})}var qE=[/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 cQ($){for(let Z of qE)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var BE=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],NE=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function $H($){return(process.platform==="win32"?BE:NE).some((Y)=>Y.test($))}var OE=[/\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],CE=[/\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 ZH($,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($H(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),z=cQ(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($H(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),z=cQ(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=cQ(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let z of OE)if(z.test(Y))return{level:"dangerous",reason:Y};for(let z of CE)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"};case"m365_list_emails":case"m365_read_email":case"m365_list_events":case"m365_list_todos":case"m365_list_files":case"m365_briefing":return{level:"safe"};case"m365_send_email":return{level:"moderate",reason:`send email to ${Z.to??"unknown"}`};case"m365_create_event":return{level:"moderate",reason:`create calendar event: ${Z.subject??""}`};case"m365_create_todo":return{level:"moderate",reason:`create To Do task: ${Z.title??""}`};case"m365_complete_todo":return{level:"moderate",reason:`complete To Do task: ${Z.taskId??""}`};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function lQ($){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: ${ME(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.
1422
- Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${EE(Y)}" may not exist or be unavailable.
1422
+ `)}`}function HW($,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(`
1423
+ `),X=Math.min(10,J.length),K=Math.min(5,Math.max(0,J.length-X)),V=J.length-X-K,G=[...J.slice(0,X)];if(V>0)G.push(`... (${V} lines omitted)`);if(K>0)G.push(...J.slice(-K));let W=G.join(`
1424
+ `);return{...z,result:W}});return{...Y,toolCalls:Q}})}var wE=[/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 rQ($){for(let Z of wE)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var kE=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],fE=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function UW($){return(process.platform==="win32"?kE:fE).some((Y)=>Y.test($))}var bE=[/\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],yE=[/\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 qW($,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(UW(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),z=rQ(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(UW(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),z=rQ(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=rQ(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let z of bE)if(z.test(Y))return{level:"dangerous",reason:Y};for(let z of yE)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"};case"m365_list_emails":case"m365_read_email":case"m365_list_events":case"m365_list_todos":case"m365_list_files":case"m365_briefing":return{level:"safe"};case"m365_send_email":return{level:"moderate",reason:`send email to ${Z.to??"unknown"}`};case"m365_create_event":return{level:"moderate",reason:`create calendar event: ${Z.subject??""}`};case"m365_create_todo":return{level:"moderate",reason:`create To Do task: ${Z.title??""}`};case"m365_complete_todo":return{level:"moderate",reason:`complete To Do task: ${Z.taskId??""}`};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function aQ($){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: ${vE(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.
1425
+ Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${xE(Y)}" may not exist or be unavailable.
1423
1426
  Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
1424
- 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 ME($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function EE($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function YH($,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 QH($,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(`
1427
+ 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 vE($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function xE($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function BW($,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 NW($,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(`
1425
1428
  `)[0]||"",z=Y.split(`
1426
- `).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 zH($,Z,Y=20){let Q=$.split(`
1429
+ `).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 OW($,Z,Y=20){let Q=$.split(`
1427
1430
  `),z=Z.split(`
1428
- `),J=[],X=Q.slice(0,Y);for(let V of X)J.push(` \x1B[31m- ${V}\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 V of K)J.push(` \x1B[32m+ ${V}\x1B[0m`);if(z.length>Y)J.push(` \x1B[2m ... (${z.length-Y} more added)\x1B[0m`);return J}class oQ{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new X1({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new X1({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=eG($),z=M2(Z);if(aG(Q,this.model,z)){let V=sG(Q,this.model,z);if(V)try{let H={role:"assistant",content:`[Conversation summary]
1429
- ${await this.generateSummary(V.toSummarize)}`,timestamp:Date.now()};Q=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},H,...V.toKeep]}catch{}}let J=rG(Q,this.model,z),X=FE(J),K=Y?k:void 0;try{yield*this.streamLoop(X,Z,K)}catch(V){yield{type:"error",error:lQ(V)}}}async generateSummary($){let Z=tG($),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 nG(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(H){yield{type:"error",error:lQ(H)};return}for await(let H of X)if(H.type==="content_block_delta"&&H.delta.type==="text_delta")yield{type:"text",text:H.delta.text};let K=await X.finalMessage();if(K.usage)yield{type:"usage",inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens};if(K.stop_reason!=="tool_use"){yield{type:"done"};return}let V=K.content.filter((H)=>H.type==="tool_use");z.push({role:"assistant",content:K.content});let G=[];for(let H of V){let W=H.input,U=ZH(H.name,W);if(U.level==="dangerous"){yield{type:"tool_blocked",id:H.id,name:H.name,reason:`Blocked dangerous operation: ${U.reason}`},G.push({type:"tool_result",tool_use_id:H.id,content:`Error: Operation blocked for safety. Reason: ${U.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&YH(this.approvalMode,H.name,U.level)&&this.approvalCallback){if(yield{type:"tool_call",id:H.id,name:H.name,input:H.input},!await this.approvalCallback(H.name,W,U.level)){yield{type:"tool_blocked",id:H.id,name:H.name,reason:"Rejected by user"},G.push({type:"tool_result",tool_use_id:H.id,content:"Error: User rejected this operation."});continue}let C=await HZ(H.name,W);yield{type:"tool_result",id:H.id,name:H.name,result:C},G.push({type:"tool_result",tool_use_id:H.id,content:C});continue}yield{type:"tool_call",id:H.id,name:H.name,input:H.input};let q=await HZ(H.name,W);yield{type:"tool_result",id:H.id,name:H.name,result:q},G.push({type:"tool_result",tool_use_id:H.id,content:q})}z.push({role:"user",content:G})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function FE($){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 iQ{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 H=await z.text();yield{type:"error",error:`${this.name} API error ${z.status}: ${H.slice(0,200)}`};return}if(!z.body){yield{type:"error",error:"No response body"};return}let J=z.body.getReader(),X=new TextDecoder,K="",V=Z.length+$.reduce((H,W)=>H+W.content.length,0),G=0;while(!0){let{done:H,value:W}=await J.read();if(H)break;K+=X.decode(W,{stream:!0});let U=K.split(`
1430
- `);K=U.pop()||"";for(let q of U){if(!q.startsWith("data: "))continue;let N=q.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},G+=M.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(V/3.5),outputTokens:Math.ceil(G/3.5)},yield{type:"done"}}catch(z){yield{type:"error",error:z instanceof Error?z.message:String(z)}}}}function WZ($){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 LE={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 JH(){let $=["Providers:"];for(let[Z,Y]of Object.entries(LE)){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(`
1431
- `)}function XH($,Z,Y,Q){let{provider:z,model:J}=WZ(Z);if(z==="openai"||z==="ollama")return new iQ(z,J,Y);let X=new oQ($.auth.token,Z,Y,Q);return X.setAuthRefresh(()=>{let K=j2();if(K&&K.token!==$.auth.token)return $.auth=K,X.updateToken(K.token),!0;return!1}),X}h();import{existsSync as S0,mkdirSync as KH,readdirSync as VH,readFileSync as i3,unlinkSync as GH,renameSync as nQ}from"fs";import{join as J0}from"path";class rQ{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=J0($,"sessions"),this.archiveDir=J0($,"sessions","archive"),!S0(this.sessionsDir))KH(this.sessionsDir,{recursive:!0});if(!S0(this.archiveDir))KH(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(!S0(this.sessionsDir))return[];return VH(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=J0(this.sessionsDir,`${$}.json`);if(!S0(Z))return null;try{let Y=JSON.parse(i3(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=J0(this.sessionsDir,`${$}.json`);if(S0(Z))return GH(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=J0(this.sessionsDir,`${$}.json`);return P(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=J0(this.sessionsDir,`${$}.json`);if(!S0(Z))return!1;let Y=J0(this.archiveDir,`${$}.json`);return nQ(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=J0(this.archiveDir,`${$}.json`);if(!S0(Z))return!1;let Y=J0(this.sessionsDir,`${$}.json`);return nQ(Z,Y),!0}listArchived(){if(!S0(this.archiveDir))return[];return VH(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=J0(this.archiveDir,`${$}.json`);if(!S0(Z))return null;try{let Y=JSON.parse(i3(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=J0(this.archiveDir,`${$}.json`);if(S0(Z))return GH(Z),!0;return!1}loadOrCreate($){let Z=J0(this.sessionsDir,`${$}.json`);if(S0(Z))try{return JSON.parse(i3(Z,"utf-8"))}catch{let Q=J0(this.sessionsDir,`${$}.corrupt.json`);try{nQ(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 $=J0(this.sessionsDir,"..","last-session.txt");P($,this.current.name)}getLastSession(){let $=J0(this.sessionsDir,"..","last-session.txt");if(!S0($))return null;try{let Z=i3($,"utf-8").trim();if(!Z||!S0(J0(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}getSession($){let Z=J0(this.sessionsDir,`${$}.json`);if(!S0(Z))return null;try{return JSON.parse(i3(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=J0(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=J0(this.sessionsDir,`${$}.json`);return P(Q,JSON.stringify(Y,null,2)),Y}save(){let $=J0(this.sessionsDir,`${this.current.name}.json`);P($,JSON.stringify(this.current,null,2))}}import{existsSync as UH,readdirSync as AE,readFileSync as qH}from"fs";import{join as sQ}from"path";Z0();import{existsSync as aQ,readFileSync as HH}from"fs";import{basename as RE,join as UZ}from"path";function WH(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${uz()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),R)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=jE($);if(Y)Z.push(`Project: ${Y}`);let Q=PE($);if(Q)Z.push(Q);return Z.join(`
1432
- `)}function jE($){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(aQ(UZ($,z)))Y.push(J);if(Y.length===0)return null;let Q=RE($);try{let z=UZ($,"package.json");if(aQ(z)){let J=JSON.parse(HH(z,"utf-8"));if(J.name)Q=J.name}}catch(z){l.debug("Failed to parse package.json for project name",{error:z})}return`Project: ${Q} (${Y.join(", ")})`}function PE($){if(!aQ(UZ($,".git")))return null;let Z=[];try{let Y=HH(UZ($,".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(`
1433
- `)}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){l.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(`
1431
+ `),J=[],X=Q.slice(0,Y);for(let V of X)J.push(` \x1B[31m- ${V}\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 V of K)J.push(` \x1B[32m+ ${V}\x1B[0m`);if(z.length>Y)J.push(` \x1B[2m ... (${z.length-Y} more added)\x1B[0m`);return J}class sQ{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new V1({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new V1({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=HW($),z=F2(Z);if(VW(Q,this.model,z)){let V=GW(Q,this.model,z);if(V)try{let W={role:"assistant",content:`[Conversation summary]
1432
+ ${await this.generateSummary(V.toSummarize)}`,timestamp:Date.now()};Q=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},W,...V.toKeep]}catch{}}let J=KW(Q,this.model,z),X=_E(J),K=Y?k:void 0;try{yield*this.streamLoop(X,Z,K)}catch(V){yield{type:"error",error:aQ(V)}}}async generateSummary($){let Z=WW($),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 XW(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(W){yield{type:"error",error:aQ(W)};return}for await(let W of X)if(W.type==="content_block_delta"&&W.delta.type==="text_delta")yield{type:"text",text:W.delta.text};let K=await X.finalMessage();if(K.usage)yield{type:"usage",inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens};if(K.stop_reason!=="tool_use"){yield{type:"done"};return}let V=K.content.filter((W)=>W.type==="tool_use");z.push({role:"assistant",content:K.content});let G=[];for(let W of V){let H=W.input,U=qW(W.name,H);if(U.level==="dangerous"){yield{type:"tool_blocked",id:W.id,name:W.name,reason:`Blocked dangerous operation: ${U.reason}`},G.push({type:"tool_result",tool_use_id:W.id,content:`Error: Operation blocked for safety. Reason: ${U.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&BW(this.approvalMode,W.name,U.level)&&this.approvalCallback){if(yield{type:"tool_call",id:W.id,name:W.name,input:W.input},!await this.approvalCallback(W.name,H,U.level)){yield{type:"tool_blocked",id:W.id,name:W.name,reason:"Rejected by user"},G.push({type:"tool_result",tool_use_id:W.id,content:"Error: User rejected this operation."});continue}let C=await BZ(W.name,H);yield{type:"tool_result",id:W.id,name:W.name,result:C},G.push({type:"tool_result",tool_use_id:W.id,content:C});continue}yield{type:"tool_call",id:W.id,name:W.name,input:W.input};let q=await BZ(W.name,H);yield{type:"tool_result",id:W.id,name:W.name,result:q},G.push({type:"tool_result",tool_use_id:W.id,content:q})}z.push({role:"user",content:G})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function _E($){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 tQ{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 W=await z.text();yield{type:"error",error:`${this.name} API error ${z.status}: ${W.slice(0,200)}`};return}if(!z.body){yield{type:"error",error:"No response body"};return}let J=z.body.getReader(),X=new TextDecoder,K="",V=Z.length+$.reduce((W,H)=>W+H.content.length,0),G=0;while(!0){let{done:W,value:H}=await J.read();if(W)break;K+=X.decode(H,{stream:!0});let U=K.split(`
1433
+ `);K=U.pop()||"";for(let q of U){if(!q.startsWith("data: "))continue;let N=q.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},G+=M.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(V/3.5),outputTokens:Math.ceil(G/3.5)},yield{type:"done"}}catch(z){yield{type:"error",error:z instanceof Error?z.message:String(z)}}}}function NZ($){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 hE={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 CW(){let $=["Providers:"];for(let[Z,Y]of Object.entries(hE)){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(`
1434
+ `)}function MW($,Z,Y,Q){let{provider:z,model:J}=NZ(Z);if(z==="openai"||z==="ollama")return new tQ(z,J,Y);let X=new sQ($.auth.token,Z,Y,Q);return X.setAuthRefresh(()=>{let K=A2();if(K&&K.token!==$.auth.token)return $.auth=K,X.updateToken(K.token),!0;return!1}),X}g();import{existsSync as k0,mkdirSync as EW,readdirSync as FW,readFileSync as r3,unlinkSync as LW,renameSync as eQ}from"fs";import{join as X0}from"path";class $z{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=X0($,"sessions"),this.archiveDir=X0($,"sessions","archive"),!k0(this.sessionsDir))EW(this.sessionsDir,{recursive:!0});if(!k0(this.archiveDir))EW(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(!k0(this.sessionsDir))return[];return FW(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=X0(this.sessionsDir,`${$}.json`);if(!k0(Z))return null;try{let Y=JSON.parse(r3(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=X0(this.sessionsDir,`${$}.json`);if(k0(Z))return LW(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=X0(this.sessionsDir,`${$}.json`);return j(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=X0(this.sessionsDir,`${$}.json`);if(!k0(Z))return!1;let Y=X0(this.archiveDir,`${$}.json`);return eQ(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=X0(this.archiveDir,`${$}.json`);if(!k0(Z))return!1;let Y=X0(this.sessionsDir,`${$}.json`);return eQ(Z,Y),!0}listArchived(){if(!k0(this.archiveDir))return[];return FW(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=X0(this.archiveDir,`${$}.json`);if(!k0(Z))return null;try{let Y=JSON.parse(r3(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=X0(this.archiveDir,`${$}.json`);if(k0(Z))return LW(Z),!0;return!1}loadOrCreate($){let Z=X0(this.sessionsDir,`${$}.json`);if(k0(Z))try{return JSON.parse(r3(Z,"utf-8"))}catch{let Q=X0(this.sessionsDir,`${$}.corrupt.json`);try{eQ(Z,Q)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return j(Z,JSON.stringify(Y,null,2)),Y}saveLastSession(){let $=X0(this.sessionsDir,"..","last-session.txt");j($,this.current.name)}getLastSession(){let $=X0(this.sessionsDir,"..","last-session.txt");if(!k0($))return null;try{let Z=r3($,"utf-8").trim();if(!Z||!k0(X0(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}getSession($){let Z=X0(this.sessionsDir,`${$}.json`);if(!k0(Z))return null;try{return JSON.parse(r3(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=X0(this.sessionsDir,`${$}.json`);if(j(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=X0(this.sessionsDir,`${$}.json`);return j(Q,JSON.stringify(Y,null,2)),Y}save(){let $=X0(this.sessionsDir,`${this.current.name}.json`);j($,JSON.stringify(this.current,null,2))}}import{existsSync as PW,readdirSync as uE,readFileSync as AW}from"fs";import{join as Yz}from"path";Y0();import{existsSync as Zz,readFileSync as RW}from"fs";import{basename as gE,join as OZ}from"path";function jW(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${$J()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),R)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=mE($);if(Y)Z.push(`Project: ${Y}`);let Q=pE($);if(Q)Z.push(Q);return Z.join(`
1435
+ `)}function mE($){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(Zz(OZ($,z)))Y.push(J);if(Y.length===0)return null;let Q=gE($);try{let z=OZ($,"package.json");if(Zz(z)){let J=JSON.parse(RW(z,"utf-8"));if(J.name)Q=J.name}}catch(z){o.debug("Failed to parse package.json for project name",{error:z})}return`Project: ${Q} (${Y.join(", ")})`}function pE($){if(!Zz(OZ($,".git")))return null;let Z=[];try{let Y=RW(OZ($,".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(`
1436
+ `)}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){o.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(`
1434
1437
  `),J=z.slice(0,15);if(z.length>15)J.push(`... and ${z.length-15} more files`);Z.push(`Uncommitted changes:
1435
1438
  `+J.join(`
1436
- `))}}}catch(Y){l.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(`
1439
+ `))}}}catch(Y){o.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(`
1437
1440
  `).slice(0,10);Z.push(`Staged:
1438
1441
  `+z.join(`
1439
- `))}}}catch(Y){l.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
1440
- `):null}function BH($,Z){if(!UH($))return[];let Y=[],Q=AE($,{withFileTypes:!0});for(let z of Q)if(z.isFile()&&z.name.endsWith(".md")){let J=qH(sQ($,z.name),"utf-8");Y.push({name:z.name.replace(".md",""),content:J.trim(),source:Z})}else if(z.isDirectory()){let J=sQ($,z.name,"SKILL.md");if(UH(J)){let X=qH(J,"utf-8");Y.push({name:z.name,content:X.trim(),source:Z})}}return Y}function NH($){let Z=BH($,"global"),Y=sQ(process.cwd(),".smolerclaw","skills"),Q=BH(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 OH($){if($.length===0)return"No skills loaded.";return`Skills:
1442
+ `))}}}catch(Y){o.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
1443
+ `):null}function DW($,Z){if(!PW($))return[];let Y=[],Q=uE($,{withFileTypes:!0});for(let z of Q)if(z.isFile()&&z.name.endsWith(".md")){let J=AW(Yz($,z.name),"utf-8");Y.push({name:z.name.replace(".md",""),content:J.trim(),source:Z})}else if(z.isDirectory()){let J=Yz($,z.name,"SKILL.md");if(PW(J)){let X=AW(J,"utf-8");Y.push({name:z.name,content:X.trim(),source:Z})}}return Y}function TW($){let Z=DW($,"global"),Y=Yz(process.cwd(),".smolerclaw","skills"),Q=DW(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 IW($){if($.length===0)return"No skills loaded.";return`Skills:
1441
1444
  `+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
1442
- `)}function qZ($,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
1443
- ALWAYS respond in ${J}. This is a hard requirement.`)}if(v1())Q.push(`---
1444
- `+ZG());if(Q.push(`---
1445
+ `)}function CZ($,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
1446
+ ALWAYS respond in ${J}. This is a hard requirement.`)}if(_1())Q.push(`---
1447
+ `+qG());if(Q.push(`---
1445
1448
  ## Meta-Learning & Self-Awareness
1446
1449
  You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
1447
1450
 
@@ -1461,111 +1464,111 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
1461
1464
  ## Environment
1462
1465
  The user's current working directory and project info. Use this context when they ask about code or files.
1463
1466
 
1464
- `+WH()),$)Q.push(`## User Instructions
1467
+ `+jW()),$)Q.push(`## User Instructions
1465
1468
  `+$);return Q.join(`
1466
1469
 
1467
- `)}async function CH($,Z,Y){let Q=new rQ($.dataDir),z=Z||Q.getLastSession()||"default";if(z!=="default")Q.switchTo(z);let J=NH($.skillsDir),X=qZ($.systemPrompt,J,$.language),K=!Y;pQ();let V=CG(hZ()),G=h5(V);if(G.length>0)gQ(G),k.push(...g5(G));await EG(V,$.dataDir);let H=FG(),W=new Set(k.map((N)=>N.name));for(let N of H)if(!W.has(N.name))k.push(N);let U=BX(),q=U?`${X}
1470
+ `)}async function SW($,Z,Y){let Q=new $z($.dataDir),z=Z||Q.getLastSession()||"default";if(z!=="default")Q.switchTo(z);let J=TW($.skillsDir),X=CZ($.systemPrompt,J,$.language),K=!Y;oQ();let V=SG(dZ()),G=m5(V);if(G.length>0)cQ(G),k.push(...p5(G));await kG(V,$.dataDir);let W=fG(),H=new Set(k.map((N)=>N.name));for(let N of W)if(!H.has(N.name))k.push(N);let U=DX(),q=U?`${X}
1468
1471
 
1469
- ${U}`:X;return{sessions:Q,sessionName:z,skills:J,systemPrompt:X,activeSystemPrompt:q,enableTools:K,plugins:G}}async function MH($,Z,Y,Q,z,J){let X=z||"";if(J){let H=await DE();X=X?`${X}
1472
+ ${U}`:X;return{sessions:Q,sessionName:z,skills:J,systemPrompt:X,activeSystemPrompt:q,enableTools:K,plugins:G}}async function wW($,Z,Y,Q,z,J){let X=z||"";if(J){let W=await dE();X=X?`${X}
1470
1473
 
1471
- ${H}`:H}if(!X.trim())console.error("smolerclaw: no input provided"),process.exit(1);let K={role:"user",content:X.trim(),timestamp:Date.now()};Z.addMessage(K);let V="";for await(let H of $.chat(Z.messages,Y,Q))if(H.type==="text")process.stdout.write(H.text),V+=H.text;else if(H.type==="error")console.error(`
1472
- smolerclaw error: ${H.error}`);if(V&&!V.endsWith(`
1474
+ ${W}`:W}if(!X.trim())console.error("smolerclaw: no input provided"),process.exit(1);let K={role:"user",content:X.trim(),timestamp:Date.now()};Z.addMessage(K);let V="";for await(let W of $.chat(Z.messages,Y,Q))if(W.type==="text")process.stdout.write(W.text),V+=W.text;else if(W.type==="error")console.error(`
1475
+ smolerclaw error: ${W.error}`);if(V&&!V.endsWith(`
1473
1476
  `))process.stdout.write(`
1474
- `);let G={role:"assistant",content:V,timestamp:Date.now()};Z.addMessage(G)}async function DE(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var TE=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function B1($){return TE?"":$}var B={altOn:B1("\x1B[?1049h"),altOff:B1("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:B1("\x1B[1m"),dim:B1("\x1B[2m"),italic:B1("\x1B[3m"),underline:B1("\x1B[4m"),reset:B1("\x1B[0m"),inv:B1("\x1B[7m"),fg:($)=>B1(`\x1B[38;5;${$}m`),bg:($)=>B1(`\x1B[48;5;${$}m`)};var S={user:B.fg(75),ai:B.fg(114),tool:B.fg(215),err:B.fg(196),sys:B.fg(245),prompt:B.fg(220),code:B.fg(180),heading:B.fg(75),link:B.fg(39),quote:B.fg(245)},IE={primary:B.fg(75),secondary:B.fg(39),accent:B.fg(220),muted:B.fg(245),header:B.fg(81)},wE={primary:B.fg(215),secondary:B.fg(220),accent:B.fg(196),muted:B.fg(245),header:B.fg(214)},SE={primary:B.fg(183),secondary:B.fg(157),accent:B.fg(147),muted:B.fg(242),header:B.fg(183)};function tQ($){switch($){case"productivity":return IE;case"spillover_alert":return wE;case"sharpen_or_relax":return SE}}function E($){process.stdout.write($)}var kE=/\x1b\[[0-9;]*[a-zA-Z]/g;function E2($){return $.replace(kE,"")}function fE($){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=E2($),Y=0;for(let Q of Z)Y+=fE(Q);return Y}function N1($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
1475
- `)){if(O0(Q)<=Z){Y.push(Q);continue}let X=E2(Q).split(" "),K=[],V="";for(let H of X){if(H.length>Z){if(V)K.push(V),V="";let U=H;while(U.length>Z)K.push(U.slice(0,Z)),U=U.slice(Z);if(U)V=" "+U;continue}if(V.length+(V?1:0)+H.length>Z&&V)K.push(V),V=" "+H;else V+=(V?" ":"")+H}if(V)K.push(V);let G=bE(Q);for(let H=0;H<K.length;H++)if(G&&H===0)K[H]=G+K[H]+B.reset;else if(G)K[H]=G+K[H]+B.reset;Y.push(...K)}return Y}function bE($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function BZ($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
1476
- `),z=[],J=!1,X="";for(let K=0;K<Q.length;K++){let V=Q[K];if(V.trimStart().startsWith("```")){if(!J){J=!0,X=V.trimStart().slice(3).trim();let q=X?` ${X}`:"";z.push(` ${B.dim}\u250C\u2500\u2500${q}${"\u2500".repeat(Math.max(1,40-q.length))}${B.reset}`)}else J=!1,X="",z.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);continue}if(J){z.push(` ${B.dim}\u2502${B.reset} ${S.code}${V}${B.reset}`);continue}if(!V.trim()){z.push("");continue}let G=V.match(/^(#{1,3})\s+(.+)/);if(G){let q=G[1].length,N=G[2],C=q===1?"\u2501":q===2?"\u2500":"\xB7";z.push(` ${S.heading}${B.bold}${C} ${n3(N)}${B.reset}`);continue}if(V.trimStart().startsWith(">")){let q=V.replace(/^\s*>\s?/,"");eQ(z,` ${S.quote}\u2502 ${n3(q)}${B.reset}`,Y);continue}let H=V.match(/^(\s*)([-*+])\s+(.+)/);if(H){let q=Math.floor(H[1].length/2),N=H[3],C=" ".repeat(q);eQ(z,` ${C}${B.dim}\u2022${B.reset} ${n3(N)}`,Y);continue}let W=V.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(W){let q=Math.floor(W[1].length/2),N=W[2],C=W[3],M=" ".repeat(q);eQ(z,` ${M}${B.dim}${N}.${B.reset} ${n3(C)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(V.trim())){z.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`);continue}let U=` ${n3(V)}`;if(O0(U)>Y)for(let q of N1(U,Y))z.push(q);else z.push(U)}if(J)z.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);return z}function eQ($,Z,Y){if(O0(Z)>Y)for(let Q of N1(Z,Y))$.push(Q);else $.push(Z)}function n3($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${B.inv} $1 ${B.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${B.bold}${B.italic}$1${B.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${B.bold}$1${B.reset}`),Z=Z.replace(/__(.+?)__/g,`${B.bold}$1${B.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${B.italic}$1${B.reset}`),Z=Z.replace(/_(.+?)_/g,`${B.italic}$1${B.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${B.underline}$1${B.reset} ${S.link}($2)${B.reset}`),Z}import{existsSync as yE,readFileSync as vE,writeFileSync as xE}from"fs";var $z=500;class Zz{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>$z)this.entries=this.entries.slice(-$z);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=""}getEntries(){return this.entries}load(){try{if(yE(this.filePath)){let $=vE(this.filePath,"utf-8");this.entries=$.split(`
1477
- `).filter(Boolean).slice(-$z)}}catch{}}save(){try{xE(this.filePath,this.entries.join(`
1477
+ `);let G={role:"assistant",content:V,timestamp:Date.now()};Z.addMessage(G)}async function dE(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var cE=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function O1($){return cE?"":$}var B={altOn:O1("\x1B[?1049h"),altOff:O1("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:O1("\x1B[1m"),dim:O1("\x1B[2m"),italic:O1("\x1B[3m"),underline:O1("\x1B[4m"),reset:O1("\x1B[0m"),inv:O1("\x1B[7m"),fg:($)=>O1(`\x1B[38;5;${$}m`),bg:($)=>O1(`\x1B[48;5;${$}m`)};var w={user:B.fg(75),ai:B.fg(114),tool:B.fg(215),err:B.fg(196),sys:B.fg(245),prompt:B.fg(220),code:B.fg(180),heading:B.fg(75),link:B.fg(39),quote:B.fg(245)},lE={primary:B.fg(75),secondary:B.fg(39),accent:B.fg(220),muted:B.fg(245),header:B.fg(81)},oE={primary:B.fg(215),secondary:B.fg(220),accent:B.fg(196),muted:B.fg(245),header:B.fg(214)},iE={primary:B.fg(183),secondary:B.fg(157),accent:B.fg(147),muted:B.fg(242),header:B.fg(183)};function Qz($){switch($){case"productivity":return lE;case"spillover_alert":return oE;case"sharpen_or_relax":return iE}}function E($){process.stdout.write($)}var nE=/\x1b\[[0-9;]*[a-zA-Z]/g;function L2($){return $.replace(nE,"")}function rE($){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 C0($){let Z=L2($),Y=0;for(let Q of Z)Y+=rE(Q);return Y}function C1($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
1478
+ `)){if(C0(Q)<=Z){Y.push(Q);continue}let X=L2(Q).split(" "),K=[],V="";for(let W of X){if(W.length>Z){if(V)K.push(V),V="";let U=W;while(U.length>Z)K.push(U.slice(0,Z)),U=U.slice(Z);if(U)V=" "+U;continue}if(V.length+(V?1:0)+W.length>Z&&V)K.push(V),V=" "+W;else V+=(V?" ":"")+W}if(V)K.push(V);let G=aE(Q);for(let W=0;W<K.length;W++)if(G&&W===0)K[W]=G+K[W]+B.reset;else if(G)K[W]=G+K[W]+B.reset;Y.push(...K)}return Y}function aE($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function MZ($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
1479
+ `),z=[],J=!1,X="";for(let K=0;K<Q.length;K++){let V=Q[K];if(V.trimStart().startsWith("```")){if(!J){J=!0,X=V.trimStart().slice(3).trim();let q=X?` ${X}`:"";z.push(` ${B.dim}\u250C\u2500\u2500${q}${"\u2500".repeat(Math.max(1,40-q.length))}${B.reset}`)}else J=!1,X="",z.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);continue}if(J){z.push(` ${B.dim}\u2502${B.reset} ${w.code}${V}${B.reset}`);continue}if(!V.trim()){z.push("");continue}let G=V.match(/^(#{1,3})\s+(.+)/);if(G){let q=G[1].length,N=G[2],C=q===1?"\u2501":q===2?"\u2500":"\xB7";z.push(` ${w.heading}${B.bold}${C} ${a3(N)}${B.reset}`);continue}if(V.trimStart().startsWith(">")){let q=V.replace(/^\s*>\s?/,"");zz(z,` ${w.quote}\u2502 ${a3(q)}${B.reset}`,Y);continue}let W=V.match(/^(\s*)([-*+])\s+(.+)/);if(W){let q=Math.floor(W[1].length/2),N=W[3],C=" ".repeat(q);zz(z,` ${C}${B.dim}\u2022${B.reset} ${a3(N)}`,Y);continue}let H=V.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(H){let q=Math.floor(H[1].length/2),N=H[2],C=H[3],M=" ".repeat(q);zz(z,` ${M}${B.dim}${N}.${B.reset} ${a3(C)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(V.trim())){z.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`);continue}let U=` ${a3(V)}`;if(C0(U)>Y)for(let q of C1(U,Y))z.push(q);else z.push(U)}if(J)z.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);return z}function zz($,Z,Y){if(C0(Z)>Y)for(let Q of C1(Z,Y))$.push(Q);else $.push(Z)}function a3($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${B.inv} $1 ${B.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${B.bold}${B.italic}$1${B.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${B.bold}$1${B.reset}`),Z=Z.replace(/__(.+?)__/g,`${B.bold}$1${B.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${B.italic}$1${B.reset}`),Z=Z.replace(/_(.+?)_/g,`${B.italic}$1${B.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${B.underline}$1${B.reset} ${w.link}($2)${B.reset}`),Z}import{existsSync as sE,readFileSync as tE,writeFileSync as eE}from"fs";var Jz=500;class Xz{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>Jz)this.entries=this.entries.slice(-Jz);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=""}getEntries(){return this.entries}load(){try{if(sE(this.filePath)){let $=tE(this.filePath,"utf-8");this.entries=$.split(`
1480
+ `).filter(Boolean).slice(-Jz)}}catch{}}save(){try{eE(this.filePath,this.entries.join(`
1478
1481
  `)+`
1479
- `)}catch{}}}var _E={consecutiveBonus:15,wordBoundaryBonus:30,startBonus:25,caseSensitiveBonus:5,gapPenalty:1};function hE($,Z){if(Z===0)return!0;let Y=$[Z-1],Q=$[Z];if(Y==="-"||Y==="_"||Y==="."||Y===" "||Y==="/")return!0;if(Y===Y.toLowerCase()&&Q===Q.toUpperCase()&&Q!==Q.toLowerCase())return!0;return!1}function gE($,Z,Y={}){let Q={..._E,...Y};if($.length===0)return{item:Z,score:1,indices:[]};if($.length>Z.length)return null;let z=$.toLowerCase(),J=Z.toLowerCase(),X=[],K=0,V=0,G=-1;for(let W=0;W<Z.length&&V<$.length;W++)if(J[W]===z[V]){if(X.push(W),K+=10,G===W-1)K+=Q.consecutiveBonus;if(hE(Z,W))K+=Q.wordBoundaryBonus;if(W===0)K+=Q.startBonus;if(Z[W]===$[V])K+=Q.caseSensitiveBonus;if(G>=0){let U=W-G-1;K-=U*Q.gapPenalty}G=W,V++}if(V!==$.length)return null;K+=$.length*5;let H=$.length/Z.length;return K=Math.round(K*(0.5+H*0.5)),{item:Z,score:K,indices:X}}function r3($,Z,Y=(z)=>String(z),Q={}){let z=[];for(let J of Z){let X=Y(J),K=gE($,X,Q);if(K)z.push({item:J,match:{...K,item:X}})}return z.sort((J,X)=>X.match.score-J.match.score),z}import{join as ZF}from"path";var mE=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],pE=" ";function Yz($,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=tE($,Y),V=z-Q||1,H=K.map((U)=>{if(U===0&&Q===0)return pE;let q=(U-Q)/V,N=Math.min(7,Math.floor(q*8));return mE[N]}).join(""),W=J?`${J}${H}${B.reset}`:H;if(X)return`${B.dim}${Q.toFixed(0)}${B.reset}${W}${B.dim}${z.toFixed(0)}${B.reset}`;return W}var uE="\u2588",dE="\u2589",cE="\u258A",lE="\u258B",oE="\u258C",iE="\u258D",nE="\u258E",rE="\u258F",aE="\u2591",sE=[" ",rE,nE,iE,oE,lE,cE,dE];function Qz($,Z={}){let{width:Y=20,maxValue:Q=100,showValue:z=!0,color:J=B.fg(75),label:X=""}=Z,K=Math.min(1,Math.max(0,$/Q)),V=Math.floor(K*Y),G=K*Y-V,H=Math.floor(G*8),W=uE.repeat(V);if(H>0&&V<Y)W+=sE[H];let U=Y-O0(W);W+=aE.repeat(Math.max(0,U));let q=J?`${J}${W}${B.reset}`:W,N=[];if(X)N.push(`${B.dim}${X.padEnd(12)}${B.reset}`);if(N.push(q),z)N.push(` ${B.dim}${$.toFixed(1)}%${B.reset}`);return N.join("")}function a3($,Z){let Y=[];if(Y.push(`${S.ai}${$.model}${B.reset}`),$.project)Y.push(`${S.heading}${$.project}${B.reset}`);if($.tokens){let{input:X,output:K}=$.tokens;Y.push(`${B.dim}${EH(X)}/${EH(K)} tok${B.reset}`)}if($.sessionCost)Y.push(`${B.dim}${$.sessionCost}${B.reset}`);if($.vaultStatus){let X=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",K=$.vaultStatus==="ok"?B.fg(114):$.vaultStatus==="warn"?B.fg(220):B.fg(196);Y.push(`${K}${X}${B.reset}`)}if($.customItems)for(let X of $.customItems){let K=X.color||"";Y.push(`${B.dim}${X.label}:${B.reset}${K}${X.value}${B.reset}`)}let Q=Y.join(` ${B.dim}\u2502${B.reset} `),z=O0(Q),J=Math.max(0,Z-z-2);return`${B.inv} ${Q}${" ".repeat(J)} ${B.reset}`}function zz($,Z=40){let Y=[];Y.push(`${B.dim}${"\u2500".repeat(Z)}${B.reset}`),Y.push(`${S.heading}${B.bold} System${B.reset}`);let Q=Yz($.cpu,{width:15,color:B.fg(75)}),z=Qz($.currentCpu,{width:10,showValue:!1,color:B.fg(75)});Y.push(` ${B.dim}CPU:${B.reset} ${Q} ${z} ${$.currentCpu.toFixed(0)}%`);let J=Yz($.memory,{width:15,color:B.fg(114)}),X=Qz($.currentMem,{width:10,showValue:!1,color:B.fg(114)});return Y.push(` ${B.dim}MEM:${B.reset} ${J} ${X} ${$.currentMem.toFixed(0)}%`),Y.push(`${B.dim}${"\u2500".repeat(Z)}${B.reset}`),Y}function tE($,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),V=K.reduce((G,H)=>G+H,0)/K.length;Q.push(V)}return Q}function EH($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function s3($,Z,Y={}){let{title:Q="",padding:z=1,borderColor:J=B.dim,titleColor:X=S.heading}=Y,K=Z-2-z*2,V=[];if(Q){let H=O0(Q),W=2,U=Math.max(1,Z-H-2-4);V.push(`${J}\u250C${"\u2500".repeat(2)}${B.reset}${X}${B.bold} ${Q} ${B.reset}${J}${"\u2500".repeat(U)}\u2510${B.reset}`)}else V.push(`${J}\u250C${"\u2500".repeat(Z-2)}\u2510${B.reset}`);let G=" ".repeat(z);for(let H of $){let W=O0(H)>K?N1(H,K):[H];for(let U of W){let q=O0(U),N=Math.max(0,K-q);V.push(`${J}\u2502${B.reset}${G}${U}${" ".repeat(N)}${G}${J}\u2502${B.reset}`)}}return V.push(`${J}\u2514${"\u2500".repeat(Z-2)}\u2518${B.reset}`),V}function Jz($,Z,Y,Q,z={}){let J=s3($,Q,z);for(let X=0;X<J.length;X++)E(B.to(Z+X,Y)),E(J[X])}var NZ={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},eE={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function Xz($,Z={}){let{width:Y=60,showActions:Q=!0,compact:z=!1}=Z,J=[],X=eE[$.category]||"\uD83D\uDCA1",K=NZ.dimYellow+NZ.italic;if(z){let H=$.title.length>Y-10?$.title.slice(0,Y-13)+"...":$.title;return J.push(` ${K}${X} ${H}${B.reset}`),J}J.push(` ${K}${X} ${$.title}${B.reset}`);let V=Y-6,G=N1($.explanation,V);for(let H of G)J.push(` ${K} ${E2(H)}${B.reset}`);if($.suggestedAction)J.push(` ${NZ.dimCyan} \u2192 ${$.suggestedAction.label}${B.reset}`);if(Q)J.push(` ${B.dim} [Y] Aceitar [N] Ignorar${B.reset}`);return J}function FH($,Z=40){let Y=[],Q=[...$].sort((z,J)=>J.frequency-z.frequency).slice(0,3);if(Q.length===0)return Y.push(`${B.dim} Nenhuma dica disponivel ainda.${B.reset}`),Y.push(`${B.dim} Continue usando para gerar insights.${B.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",V=Z-8,G=J.title.length>V?J.title.slice(0,V-3)+"...":J.title;Y.push(`${K} ${NZ.dimYellow}${G}${B.reset}`);let H=Z-4,W=J.description.length>H?J.description.slice(0,H-3)+"...":J.description;Y.push(` ${B.dim}${W}${B.reset}`);let U=J.frequency===1?"vez":"vezes";if(Y.push(` ${B.dim}Detectado ${J.frequency}x${B.reset}`),z<Q.length-1)Y.push("")}return Y}function OZ($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:FH($,Z)}}class t3{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(B.to($,1)),E(a3(this.statusConfig,this.width))}clearScreen(){E(B.clear),E(B.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)E(B.to(Z,1)),E(B.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 V=0;V<$.length;V++){let G=$[V],H=G.row??X,W=G.col??K,U=G.width??J,q=G.height??Math.floor(z/Math.ceil($.length/Z));if(this.drawDashboardPanel(G,H,W,U,q),(V+1)%Z===0)X+=q+Y,K=1+Y;else K+=U+Y}this.renderStatusBar()}drawDashboardPanel($,Z,Y,Q,z){let J=z-2,X=$.content.slice(0,J);Jz(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:zz($,35)}],columns:1,gap:1}}}function CZ($,Z){E(`\x1B[${$};${Z}r`)}function MZ(){E("\x1B[r")}var $F=new t3;z1();class Kz{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=tQ("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"]};commandDescriptions={"/help":"Mostrar todos os comandos","/ajuda":"Mostrar todos os comandos","/clear":"Limpar tela","/limpar":"Limpar tela","/commit":"Git commit com mensagem IA","/commitar":"Git commit com mensagem IA","/persona":"Trocar modo de persona","/modo":"Trocar modo de persona","/copy":"Copiar ultima resposta","/copiar":"Copiar ultima resposta","/fork":"Bifurcar sessao atual","/new":"Nova sessao","/novo":"Nova sessao","/load":"Carregar sessao","/carregar":"Carregar sessao","/sessions":"Listar sessoes","/sessoes":"Listar sessoes","/delete":"Deletar sessao","/deletar":"Deletar sessao","/model":"Trocar modelo IA","/modelo":"Trocar modelo IA","/export":"Exportar conversa","/exportar":"Exportar conversa","/cost":"Ver custo da sessao","/custo":"Ver custo da sessao","/retry":"Repetir ultima mensagem","/repetir":"Repetir ultima mensagem","/undo":"Desfazer ultima acao","/desfazer":"Desfazer ultima acao","/search":"Buscar na conversa","/buscar":"Buscar na conversa","/lang":"Trocar idioma","/idioma":"Trocar idioma","/config":"Configuracoes","/exit":"Sair do aplicativo","/sair":"Sair do aplicativo","/briefing":"Resumo diario","/resumo":"Resumo diario","/news":"Feed de noticias","/noticias":"Feed de noticias","/open":"Abrir aplicativo","/abrir":"Abrir aplicativo","/openfile":"Abrir arquivo","/openurl":"Abrir URL","/apps":"Listar aplicativos","/programas":"Listar aplicativos","/sysinfo":"Info do sistema","/sistema":"Info do sistema","/calendar":"Ver calendario","/calendario":"Ver calendario","/agenda":"Ver calendario","/ask":"Perguntar ao modelo","/perguntar":"Perguntar ao modelo","/budget":"Ver orcamento","/orcamento":"Ver orcamento","/plugins":"Gerenciar plugins","/task":"Criar tarefa","/tarefa":"Criar tarefa","/tasks":"Listar tarefas","/tarefas":"Listar tarefas","/done":"Concluir tarefa","/feito":"Concluir tarefa","/concluido":"Concluir tarefa","/rmtask":"Remover tarefa","/rmtarefa":"Remover tarefa","/people":"Gerenciar pessoas","/pessoas":"Gerenciar pessoas","/team":"Ver equipe","/equipe":"Ver equipe","/family":"Ver familia","/familia":"Ver familia","/person":"Ver pessoa","/pessoa":"Ver pessoa","/addperson":"Adicionar pessoa","/novapessoa":"Adicionar pessoa","/addpessoa":"Adicionar pessoa","/delegate":"Delegar tarefa","/delegar":"Delegar tarefa","/delegations":"Ver delegacoes","/delegacoes":"Ver delegacoes","/delegados":"Ver delegacoes","/followups":"Ver follow-ups","/dashboard":"Painel visual","/painel":"Painel visual","/contacts":"Ver contatos","/contatos":"Ver contatos","/investigar":"Iniciar investigacao","/investigate":"Start investigation","/investigacoes":"Ver investigacoes","/monitor":"Monitorar recurso","/vigiar":"Monitorar recurso","/workflow":"Gerenciar workflows","/fluxo":"Gerenciar workflows","/macro":"Gerenciar macros","/macros":"Listar macros","/atalho":"Gerenciar atalhos","/atalhos":"Listar atalhos","/pomodoro":"Timer Pomodoro","/foco":"Timer Pomodoro","/entrada":"Registrar receita","/income":"Registrar receita","/saida":"Registrar despesa","/expense":"Registrar despesa","/finance":"Ver financas","/financas":"Ver financas","/balanco":"Ver balanco","/decisions":"Registro de decisoes","/decisoes":"Registro de decisoes","/email":"Gerenciar email","/rascunho":"Rascunho de email","/memo":"Criar memo","/memos":"Listar memos","/note":"Criar nota","/notas":"Listar notas","/anotar":"Criar nota","/tags":"Ver tags","/memotags":"Tags de memos","/rmmemo":"Remover memo","/rmnota":"Remover nota","/index":"Indexar conteudo","/indexar":"Indexar conteudo","/reindex":"Reindexar tudo","/memory":"Ver memoria","/memoria":"Ver memoria","/clipboard":"Ver clipboard","/area":"Ver area de transferencia","/tela":"Capturar tela","/screen":"Capturar tela","/ps1":"Customizar prompt","/refresh":"Atualizar dados","/renovar":"Atualizar dados","/vault":"Gerenciar vault","/backup":"Fazer backup","/feeds":"Ver feeds RSS","/fontes":"Ver fontes RSS","/addfeed":"Adicionar feed","/novafonte":"Adicionar fonte","/rmfeed":"Remover feed","/rmfonte":"Remover fonte","/disablefeed":"Desativar feed","/desativarfonte":"Desativar fonte","/enablefeed":"Ativar feed","/ativarfonte":"Ativar fonte","/projeto":"Ver projeto","/project":"Ver projeto","/projetos":"Listar projetos","/projects":"Listar projetos","/sessao":"Sessao de trabalho","/session":"Work session","/relatorio":"Gerar relatorio","/report":"Gerar relatorio","/oportunidades":"Ver oportunidades","/opportunities":"Ver oportunidades","/schedule":"Ver agenda"};ghostText="";tabCycleMatches=[];tabCycleIndex=-1;tabCycleBase="";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 t3}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 Zz(ZF(this.dataDir,"history"));this.setupEventListeners(),E(B.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(z0.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(z0.on("status:update",($)=>{let Z=$.level==="error"?S.err:$.level==="warning"?S.prompt:$.level==="success"?S.sys:B.dim;if(this.lines.push({text:` ${Z}[${$.source}]${B.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z0.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${S.prompt}\u26A0 ${$.message}${B.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${S.err}\u26A0 Rate limit: ${$.message}${B.reset}`});else this.lines.push({text:` ${B.dim}[telemetry] ${$.message}${B.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z0.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${B.dim}[backup] ${$.message||"Backup concluido"}${B.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${S.sys}[pomodoro] ${$.message}${B.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${S.err}[${$.taskType}] ${$.message}${B.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z0.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(z0.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(B.show),E(B.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=BZ(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=BZ(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:` ${S.tool}\u2699 ${$}${B.reset} ${B.dim}${Q}${B.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
1480
- `),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:` ${B.dim}${X}${B.reset}`})}if(Y.length>8)this.lines.push({text:` ${B.dim}... (${Y.length-8} more lines)${B.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${S.prompt}? ${$}${B.reset} ${B.dim}[y]es / [n]o / [a]ll${B.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(Q)=>{let z=Q.toString().toLowerCase();if(z==="y"||z==="\r"||z===`
1481
- `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${S.sys}approved${B.reset}`}),this.renderAll(),Z(!0);else if(z==="n"||z==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${S.err}rejected${B.reset}`}),this.renderAll(),Z(!1);else if(z==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${S.sys}approved all for this session${B.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${B.dim}timeout \u2014 auto-rejected${B.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=$.findIndex((G)=>G.isCurrent);if(Y<0)Y=0;let Q="",z=!1,J=()=>{if(!Q)return $;let G=Q.toLowerCase();return $.filter((H)=>H.name.toLowerCase().includes(G))},X=()=>{let W=this.height-2-2,U=J();if(Y>=U.length)Y=Math.max(0,U.length-1);let q=2,N=2,C=W-q-N,M=Math.max(1,C),F=0;if(U.length>M)F=Math.max(0,Y-Math.floor(M/2)),F=Math.min(F,U.length-M);let T=U.slice(F,F+M);if(E(B.hide),E(B.to(3,1)),E(B.clearLine),z)E(` ${S.heading}${B.bold}Sessions${B.reset} ${B.dim}filter: ${Q}\u2588${B.reset}`);else E(` ${S.heading}${B.bold}Sessions${B.reset} ${B.dim}(${U.length})${B.reset}`);E(B.to(4,1)),E(B.clearLine);for(let x=0;x<M;x++){let c=2+q+x+1;if(E(B.to(c,1)),E(B.clearLine),x>=T.length)continue;let V0=T[x],C0=F+x===Y,r=V0.isCurrent?"*":" ",M0=V0.isArchived?`${B.dim}[arch] ${B.reset}`:" ",r0=`${V0.messageCount} msgs`.padEnd(10),k0=QF(V0.updated);if(C0)E(` ${S.prompt}${B.bold}\u203A ${r} ${M0}${S.prompt}${B.bold}${V0.name.padEnd(20)}${B.reset} ${B.dim}${r0} ${k0}${B.reset}`);else{let P0=V0.isArchived?B.dim:S.sys;E(` ${r} ${M0}${P0}${V0.name.padEnd(20)}${B.reset} ${B.dim}${r0} ${k0}${B.reset}`)}}for(let x=T.length;x<M;x++){let c=2+q+x+1;E(B.to(c,1)),E(B.clearLine)}let v=2+q+M+1;if(E(B.to(v,1)),E(B.clearLine),U.length>M){let x=Math.round((Y+1)/U.length*100);E(` ${B.dim}${F>0?"\u2191":" "} ${x}% ${F+M<U.length?"\u2193":" "}${B.reset}`)}let D=this.height-2;E(B.to(D,1)),E(B.clearLine),E(` ${B.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${B.reset}`)},K=(G)=>{this.pickerActive=!1,process.stdin.removeListener("data",V),this.renderAll(),Z(G)},V=(G)=>{let H=G.toString("utf-8"),W=J();if(H==="\x1B"&&G.length===1){if(z)z=!1,Q="",X();else K(null);return}if(H==="\x03"){K(null);return}if(H==="\r"||H===`
1482
- `){if(W.length>0&&Y<W.length)K({action:"load",name:W[Y].name});return}if(H==="\x1B[A"||H==="w"&&!z){if(Y>0)Y--,X();return}if(H==="\x1B[B"||H==="s"&&!z){if(Y<W.length-1)Y++,X();return}if(H==="d"&&z===!1){if(W.length>0&&Y<W.length){let U=W[Y];if(!U.isCurrent)K({action:"delete",name:U.name,isArchived:U.isArchived})}return}if(H==="a"&&z===!1){if(W.length>0&&Y<W.length){let U=W[Y];if(!U.isCurrent){let q=U.isArchived?"unarchive":"archive";K({action:q,name:U.name})}}return}if(H==="/"&&z===!1){z=!0,Q="",X();return}if(z){if(H==="\x7F"||H==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,X();else z=!1,X();return}if(H.length===1&&H>=" "){Q+=H,Y=0,X();return}}};process.stdin.on("data",V),X()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=0,Q="",z=!1,J="",X=[...new Set($.map((U)=>U.category))].sort(),K=()=>{let U=J?$.filter((q)=>q.category===J):$;if(Q){let q=Q.toLowerCase();U=U.filter((N)=>N.title.toLowerCase().includes(q)||N.source.toLowerCase().includes(q))}return U},V=(U)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[U]||U},G=()=>{let N=this.height-2-2,C=K();if(Y>=C.length)Y=Math.max(0,C.length-1);let M=2,F=2,T=N-M-F,v=Math.max(1,T),D=0;if(C.length>v)D=Math.max(0,Y-Math.floor(v/2)),D=Math.min(D,C.length-v);let x=C.slice(D,D+v);if(E(B.hide),E(B.to(3,1)),E(B.clearLine),z)E(` ${S.heading}${B.bold}Noticias${B.reset} ${B.dim}filtro: ${Q}\u2588${B.reset}`);else{let g=J?V(J):"Todas";E(` ${S.heading}${B.bold}Noticias${B.reset} ${B.dim}(${C.length}) ${g}${B.reset}`)}E(B.to(4,1)),E(B.clearLine);for(let g=0;g<v;g++){let C0=2+M+g+1;if(E(B.to(C0,1)),E(B.clearLine),g>=x.length)continue;let r=x[g],M0=D+g===Y,r0=r.time?`[${r.time}]`:" ",k0=this.width-30,P0=r.title.length>k0?r.title.slice(0,k0-1)+"\u2026":r.title;if(M0)E(` ${S.prompt}${B.bold}\u203A ${r0} ${P0}${B.reset} ${B.dim}(${r.source})${B.reset}`);else E(` ${B.dim}${r0}${B.reset} ${S.sys}${P0}${B.reset} ${B.dim}(${r.source})${B.reset}`)}for(let g=x.length;g<v;g++){let C0=2+M+g+1;E(B.to(C0,1)),E(B.clearLine)}let c=2+M+v+1;if(E(B.to(c,1)),E(B.clearLine),C.length>v){let g=Math.round((Y+1)/C.length*100);E(` ${B.dim}${D>0?"\u2191":" "} ${g}% ${D+v<C.length?"\u2193":" "}${B.reset}`)}let V0=this.height-2;E(B.to(V0,1)),E(B.clearLine),E(` ${B.dim}\u2191\u2193 navegar Enter abrir Ctrl+Enter ler aqui Esc cancelar / filtrar Tab categoria${B.reset}`)},H=(U)=>{this.pickerActive=!1,process.stdin.removeListener("data",W),this.renderAll(),Z(U)},W=(U)=>{let q=U.toString("utf-8"),N=K();if(q==="\x1B"&&U.length===1){if(z)z=!1,Q="",G();else H(null);return}if(q==="\x03"){H(null);return}if(q===`
1483
- `||q==="\x1B\r"||q==="\x1BOM"){if(N.length>0&&Y<N.length)H({action:"read",link:N[Y].link});return}if(q==="\r"||q===`
1484
- `){if(N.length>0&&Y<N.length)H({action:"open",link:N[Y].link});return}if(q==="\x1B[A"||q==="w"&&!z){if(Y>0)Y--,G();return}if(q==="\x1B[B"||q==="s"&&!z){if(Y<N.length-1)Y++,G();return}if(q==="\t"){if(!J)J=X[0]||"";else{let C=X.indexOf(J);J=C<X.length-1?X[C+1]:""}Y=0,G();return}if(q==="/"&&!z){z=!0,Q="",G();return}if(z){if(q==="\x7F"||q==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,G();else z=!1,G();return}if(q.length===1&&q>=" "){Q+=q,Y=0,G();return}}};process.stdin.on("data",W),G()})}showUsage($){this.lines.push({text:` ${B.dim}tokens: ${$}${B.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){let Z=this.width-6;for(let Y of $.split(`
1485
- `))for(let Q of N1(Y,Z))this.lines.push({text:` ${S.err}\u2717 ${Q}${B.reset}`});this.lines.push({text:""}),this.renderAll()}showSystem($){let Z=this.width-4;for(let Y of $.split(`
1486
- `))for(let Q of N1(Y,Z))this.lines.push({text:` ${S.sys}${Q}${B.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(B.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),MZ(),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=OZ(this.metaLearningEntries,Q);Z=[...Z,z]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),CZ(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=Xz($,{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(B.hide);for(let Y=0;Y<$.length;Y++)E(B.to(Z+Y,1)),E(B.clearLine),E($[Y]);E(B.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;E(B.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)E(B.to($+Z,1)),E(B.clearLine);E(B.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(z0.emit("insight:accepted",Z),this.lines.push({text:` ${S.sys}\u2713 Dica aceita: ${$.title}${B.reset}`}),$.suggestedAction)this.lines.push({text:` ${B.dim}Executando: ${$.suggestedAction.command}${B.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=OZ($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=tQ($),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(B.hide),E(B.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),V=Math.floor((Y-X*(J+1))/J),G=0;for(let H=0;H<J;H++)for(let W=0;W<z&&G<Q.length;W++){let U=Q[G],q=$+X+H*(V+X)+1,N=X+W*(K+X)+1;this.drawDashboardPanel(U,q,N,K,V),G++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(B.show)}drawDashboardPanel($,Z,Y,Q,z){let J=this.personaMode==="sharpen_or_relax"?this.palette.muted:B.dim,X=this.palette.primary,K=s3($.content.slice(0,z-2),Q,{title:$.title,borderColor:J,titleColor:X});for(let V=0;V<K.length&&V<z;V++)E(B.to(Z+V,Y)),E(K[V])}renderStickyStatusBar(){if(!this.statusBarEnabled)return;let $=this.height-2;this.stickyStatusRow=$;let Z=[];if(this.personaMode!=="productivity"){let Q=this.personaMode==="spillover_alert"?this.palette.accent:this.palette.primary;Z.push({label:"MODE",value:this.getPersonaLabel(),color:Q})}if(this.timeContext&&this.personaMode==="spillover_alert"){let Q=this.timeContext.urgentTasks.length+this.timeContext.overdueTasks.length+this.timeContext.pendingCommits.length;if(Q>0)Z.push({label:"PEND",value:String(Q),color:this.palette.accent})}let Y={model:this.model,project:this.activeProject||void 0,tokens:{input:this.inputTokens,output:this.outputTokens},sessionCost:this.sessionCost||void 0,vaultStatus:this.vaultStatus,customItems:Z.length>0?Z:void 0};E(B.to($,1)),E(this.renderPersonaAwareStatusBar(Y))}renderPersonaAwareStatusBar($){let Z=a3($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${E2(Z)}${B.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(E(B.hide),E(B.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(B.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){E(B.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();E(Z),E(B.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(B.reset),E(B.to(2,1));let K=this.personaMode==="sharpen_or_relax"?this.palette.muted:B.dim;E(`${K}${"\u2500".repeat(this.width)}${B.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return B.bg(52);case"sharpen_or_relax":return B.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),V=z.slice(X,K);E(B.hide);for(let G=0;G<Q;G++)if(E(B.to(2+G+1,1)),E(B.clearLine),G<V.length)E(V[G].text)}resetTabCycle(){this.tabCycleMatches=[],this.tabCycleIndex=-1,this.tabCycleBase=""}updateGhostText(){let $=this.inputBuf;if(this.ghostText="",this.inputPos!==$.length)return;if($.length===0)return;if($.startsWith("/")){let Z=$.split(" ");if(Z.length===1){let Y=r3($,this.commands);if(Y.length>0){let Q=Y[0].item;if(Q!==$&&Q.startsWith($)){let z=Q.slice($.length),J=this.commandDescriptions[Q];this.ghostText=J?`${z} ${J}`:z;return}if(Q!==$){let z=this.commandDescriptions[Q];this.ghostText=z?` \u2192 ${Q} ${z}`:` \u2192 ${Q}`;return}}}else{let Y=Z[0],Q=this.subcommands[Y];if(Q&&Q.length>0){let z=Z[Z.length-1].toLowerCase();if(z){let J=Q.filter((X)=>X.toLowerCase().startsWith(z));if(J.length>0){this.ghostText=J[0].slice(z.length);return}}else{this.ghostText=Q[0];return}}}}if(!$.startsWith("/")&&$.length>=2&&this.history){let Z=this.history.getEntries();for(let Q=Z.length-1;Q>=0;Q--)if(Z[Q].startsWith($)&&Z[Q]!==$){this.ghostText=Z[Q].slice($.length);return}let Y=r3($,[...Z].reverse().slice(0,100));if(Y.length>0&&Y[0].match.score>50){let Q=Y[0].item;if(Q!==$)this.ghostText=` \u2192 ${Q}`}}}completeInput($){let Z=$.split(" "),Y=Z[0];if(this.tabCycleMatches.length>1&&this.tabCycleBase){this.tabCycleIndex=(this.tabCycleIndex+1)%this.tabCycleMatches.length;let X=this.tabCycleMatches[this.tabCycleIndex],K=`[${this.tabCycleIndex+1}/${this.tabCycleMatches.length}]`,V=this.commandDescriptions[X],G=V?`${K} ${V}`:K;if(Z.length===1||this.tabCycleBase.split(" ").length===1){let H=this.subcommands[X];return{value:X+(H?.length?" ":" "),options:G}}else{let H=this.tabCycleBase.split(" ");return H[H.length-1]=X,{value:H.join(" ")+" ",options:G}}}if(Z.length===1){let X=this.commands.filter((M)=>M.startsWith(Y)),K=Y.length>=2?r3(Y,this.commands).map((M)=>M.item):[],V=new Set(X),G=[...X,...K.filter((M)=>!V.has(M))];if(G.length===0)return null;if(G.length===1){let M=G[0],F=this.subcommands[M],T=this.commandDescriptions[M],v=F?.length?`Opcoes: ${F.join(" ")}`:void 0,D=T?v?`${T}
1487
- ${v}`:T:v;return{value:M+" ",options:D}}this.tabCycleMatches=G,this.tabCycleIndex=0,this.tabCycleBase=$;let H=G[0],W=this.commandDescriptions[H],U=G.slice(0,12).map((M)=>{let F=this.commandDescriptions[M];return F?`${M} ${B.dim}${F}${B.reset}`:M}),q=G.length>12?` ${B.dim}+${G.length-12} mais${B.reset}`:"",N=`[1/${G.length}]`;if(X.length>1){let M=X[0];for(let F of X)while(!F.startsWith(M))M=M.slice(0,-1);if(M.length>$.length)return{value:M,options:`${N}
1482
+ `)}catch{}}}var $F={consecutiveBonus:15,wordBoundaryBonus:30,startBonus:25,caseSensitiveBonus:5,gapPenalty:1};function ZF($,Z){if(Z===0)return!0;let Y=$[Z-1],Q=$[Z];if(Y==="-"||Y==="_"||Y==="."||Y===" "||Y==="/")return!0;if(Y===Y.toLowerCase()&&Q===Q.toUpperCase()&&Q!==Q.toLowerCase())return!0;return!1}function YF($,Z,Y={}){let Q={...$F,...Y};if($.length===0)return{item:Z,score:1,indices:[]};if($.length>Z.length)return null;let z=$.toLowerCase(),J=Z.toLowerCase(),X=[],K=0,V=0,G=-1;for(let H=0;H<Z.length&&V<$.length;H++)if(J[H]===z[V]){if(X.push(H),K+=10,G===H-1)K+=Q.consecutiveBonus;if(ZF(Z,H))K+=Q.wordBoundaryBonus;if(H===0)K+=Q.startBonus;if(Z[H]===$[V])K+=Q.caseSensitiveBonus;if(G>=0){let U=H-G-1;K-=U*Q.gapPenalty}G=H,V++}if(V!==$.length)return null;K+=$.length*5;let W=$.length/Z.length;return K=Math.round(K*(0.5+W*0.5)),{item:Z,score:K,indices:X}}function s3($,Z,Y=(z)=>String(z),Q={}){let z=[];for(let J of Z){let X=Y(J),K=YF($,X,Q);if(K)z.push({item:J,match:{...K,item:X}})}return z.sort((J,X)=>X.match.score-J.match.score),z}import{join as MF}from"path";var QF=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],zF=" ";function Kz($,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=NF($,Y),V=z-Q||1,W=K.map((U)=>{if(U===0&&Q===0)return zF;let q=(U-Q)/V,N=Math.min(7,Math.floor(q*8));return QF[N]}).join(""),H=J?`${J}${W}${B.reset}`:W;if(X)return`${B.dim}${Q.toFixed(0)}${B.reset}${H}${B.dim}${z.toFixed(0)}${B.reset}`;return H}var JF="\u2588",XF="\u2589",KF="\u258A",VF="\u258B",GF="\u258C",WF="\u258D",HF="\u258E",UF="\u258F",qF="\u2591",BF=[" ",UF,HF,WF,GF,VF,KF,XF];function Vz($,Z={}){let{width:Y=20,maxValue:Q=100,showValue:z=!0,color:J=B.fg(75),label:X=""}=Z,K=Math.min(1,Math.max(0,$/Q)),V=Math.floor(K*Y),G=K*Y-V,W=Math.floor(G*8),H=JF.repeat(V);if(W>0&&V<Y)H+=BF[W];let U=Y-C0(H);H+=qF.repeat(Math.max(0,U));let q=J?`${J}${H}${B.reset}`:H,N=[];if(X)N.push(`${B.dim}${X.padEnd(12)}${B.reset}`);if(N.push(q),z)N.push(` ${B.dim}${$.toFixed(1)}%${B.reset}`);return N.join("")}function t3($,Z){let Y=[];if(Y.push(`${w.ai}${$.model}${B.reset}`),$.project)Y.push(`${w.heading}${$.project}${B.reset}`);if($.tokens){let{input:X,output:K}=$.tokens;Y.push(`${B.dim}${kW(X)}/${kW(K)} tok${B.reset}`)}if($.sessionCost)Y.push(`${B.dim}${$.sessionCost}${B.reset}`);if($.vaultStatus){let X=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",K=$.vaultStatus==="ok"?B.fg(114):$.vaultStatus==="warn"?B.fg(220):B.fg(196);Y.push(`${K}${X}${B.reset}`)}if($.customItems)for(let X of $.customItems){let K=X.color||"";Y.push(`${B.dim}${X.label}:${B.reset}${K}${X.value}${B.reset}`)}let Q=Y.join(` ${B.dim}\u2502${B.reset} `),z=C0(Q),J=Math.max(0,Z-z-2);return`${B.inv} ${Q}${" ".repeat(J)} ${B.reset}`}function Gz($,Z=40){let Y=[];Y.push(`${B.dim}${"\u2500".repeat(Z)}${B.reset}`),Y.push(`${w.heading}${B.bold} System${B.reset}`);let Q=Kz($.cpu,{width:15,color:B.fg(75)}),z=Vz($.currentCpu,{width:10,showValue:!1,color:B.fg(75)});Y.push(` ${B.dim}CPU:${B.reset} ${Q} ${z} ${$.currentCpu.toFixed(0)}%`);let J=Kz($.memory,{width:15,color:B.fg(114)}),X=Vz($.currentMem,{width:10,showValue:!1,color:B.fg(114)});return Y.push(` ${B.dim}MEM:${B.reset} ${J} ${X} ${$.currentMem.toFixed(0)}%`),Y.push(`${B.dim}${"\u2500".repeat(Z)}${B.reset}`),Y}function NF($,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),V=K.reduce((G,W)=>G+W,0)/K.length;Q.push(V)}return Q}function kW($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function e3($,Z,Y={}){let{title:Q="",padding:z=1,borderColor:J=B.dim,titleColor:X=w.heading}=Y,K=Z-2-z*2,V=[];if(Q){let W=C0(Q),H=2,U=Math.max(1,Z-W-2-4);V.push(`${J}\u250C${"\u2500".repeat(2)}${B.reset}${X}${B.bold} ${Q} ${B.reset}${J}${"\u2500".repeat(U)}\u2510${B.reset}`)}else V.push(`${J}\u250C${"\u2500".repeat(Z-2)}\u2510${B.reset}`);let G=" ".repeat(z);for(let W of $){let H=C0(W)>K?C1(W,K):[W];for(let U of H){let q=C0(U),N=Math.max(0,K-q);V.push(`${J}\u2502${B.reset}${G}${U}${" ".repeat(N)}${G}${J}\u2502${B.reset}`)}}return V.push(`${J}\u2514${"\u2500".repeat(Z-2)}\u2518${B.reset}`),V}function Wz($,Z,Y,Q,z={}){let J=e3($,Q,z);for(let X=0;X<J.length;X++)E(B.to(Z+X,Y)),E(J[X])}var EZ={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},OF={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function Hz($,Z={}){let{width:Y=60,showActions:Q=!0,compact:z=!1}=Z,J=[],X=OF[$.category]||"\uD83D\uDCA1",K=EZ.dimYellow+EZ.italic;if(z){let W=$.title.length>Y-10?$.title.slice(0,Y-13)+"...":$.title;return J.push(` ${K}${X} ${W}${B.reset}`),J}J.push(` ${K}${X} ${$.title}${B.reset}`);let V=Y-6,G=C1($.explanation,V);for(let W of G)J.push(` ${K} ${L2(W)}${B.reset}`);if($.suggestedAction)J.push(` ${EZ.dimCyan} \u2192 ${$.suggestedAction.label}${B.reset}`);if(Q)J.push(` ${B.dim} [Y] Aceitar [N] Ignorar${B.reset}`);return J}function fW($,Z=40){let Y=[],Q=[...$].sort((z,J)=>J.frequency-z.frequency).slice(0,3);if(Q.length===0)return Y.push(`${B.dim} Nenhuma dica disponivel ainda.${B.reset}`),Y.push(`${B.dim} Continue usando para gerar insights.${B.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",V=Z-8,G=J.title.length>V?J.title.slice(0,V-3)+"...":J.title;Y.push(`${K} ${EZ.dimYellow}${G}${B.reset}`);let W=Z-4,H=J.description.length>W?J.description.slice(0,W-3)+"...":J.description;Y.push(` ${B.dim}${H}${B.reset}`);let U=J.frequency===1?"vez":"vezes";if(Y.push(` ${B.dim}Detectado ${J.frequency}x${B.reset}`),z<Q.length-1)Y.push("")}return Y}function FZ($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:fW($,Z)}}class $8{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(B.to($,1)),E(t3(this.statusConfig,this.width))}clearScreen(){E(B.clear),E(B.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)E(B.to(Z,1)),E(B.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 V=0;V<$.length;V++){let G=$[V],W=G.row??X,H=G.col??K,U=G.width??J,q=G.height??Math.floor(z/Math.ceil($.length/Z));if(this.drawDashboardPanel(G,W,H,U,q),(V+1)%Z===0)X+=q+Y,K=1+Y;else K+=U+Y}this.renderStatusBar()}drawDashboardPanel($,Z,Y,Q,z){let J=z-2,X=$.content.slice(0,J);Wz(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:Gz($,35)}],columns:1,gap:1}}}function LZ($,Z){E(`\x1B[${$};${Z}r`)}function RZ(){E("\x1B[r")}var CF=new $8;X1();class Uz{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=Qz("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"]};commandDescriptions={"/help":"Mostrar todos os comandos","/ajuda":"Mostrar todos os comandos","/clear":"Limpar tela","/limpar":"Limpar tela","/commit":"Git commit com mensagem IA","/commitar":"Git commit com mensagem IA","/persona":"Trocar modo de persona","/modo":"Trocar modo de persona","/copy":"Copiar ultima resposta","/copiar":"Copiar ultima resposta","/fork":"Bifurcar sessao atual","/new":"Nova sessao","/novo":"Nova sessao","/load":"Carregar sessao","/carregar":"Carregar sessao","/sessions":"Listar sessoes","/sessoes":"Listar sessoes","/delete":"Deletar sessao","/deletar":"Deletar sessao","/model":"Trocar modelo IA","/modelo":"Trocar modelo IA","/export":"Exportar conversa","/exportar":"Exportar conversa","/cost":"Ver custo da sessao","/custo":"Ver custo da sessao","/retry":"Repetir ultima mensagem","/repetir":"Repetir ultima mensagem","/undo":"Desfazer ultima acao","/desfazer":"Desfazer ultima acao","/search":"Buscar na conversa","/buscar":"Buscar na conversa","/lang":"Trocar idioma","/idioma":"Trocar idioma","/config":"Configuracoes","/exit":"Sair do aplicativo","/sair":"Sair do aplicativo","/briefing":"Resumo diario","/resumo":"Resumo diario","/news":"Feed de noticias","/noticias":"Feed de noticias","/open":"Abrir aplicativo","/abrir":"Abrir aplicativo","/openfile":"Abrir arquivo","/openurl":"Abrir URL","/apps":"Listar aplicativos","/programas":"Listar aplicativos","/sysinfo":"Info do sistema","/sistema":"Info do sistema","/calendar":"Ver calendario","/calendario":"Ver calendario","/agenda":"Ver calendario","/ask":"Perguntar ao modelo","/perguntar":"Perguntar ao modelo","/budget":"Ver orcamento","/orcamento":"Ver orcamento","/plugins":"Gerenciar plugins","/task":"Criar tarefa","/tarefa":"Criar tarefa","/tasks":"Listar tarefas","/tarefas":"Listar tarefas","/done":"Concluir tarefa","/feito":"Concluir tarefa","/concluido":"Concluir tarefa","/rmtask":"Remover tarefa","/rmtarefa":"Remover tarefa","/people":"Gerenciar pessoas","/pessoas":"Gerenciar pessoas","/team":"Ver equipe","/equipe":"Ver equipe","/family":"Ver familia","/familia":"Ver familia","/person":"Ver pessoa","/pessoa":"Ver pessoa","/addperson":"Adicionar pessoa","/novapessoa":"Adicionar pessoa","/addpessoa":"Adicionar pessoa","/delegate":"Delegar tarefa","/delegar":"Delegar tarefa","/delegations":"Ver delegacoes","/delegacoes":"Ver delegacoes","/delegados":"Ver delegacoes","/followups":"Ver follow-ups","/dashboard":"Painel visual","/painel":"Painel visual","/contacts":"Ver contatos","/contatos":"Ver contatos","/investigar":"Iniciar investigacao","/investigate":"Start investigation","/investigacoes":"Ver investigacoes","/monitor":"Monitorar recurso","/vigiar":"Monitorar recurso","/workflow":"Gerenciar workflows","/fluxo":"Gerenciar workflows","/macro":"Gerenciar macros","/macros":"Listar macros","/atalho":"Gerenciar atalhos","/atalhos":"Listar atalhos","/pomodoro":"Timer Pomodoro","/foco":"Timer Pomodoro","/entrada":"Registrar receita","/income":"Registrar receita","/saida":"Registrar despesa","/expense":"Registrar despesa","/finance":"Ver financas","/financas":"Ver financas","/balanco":"Ver balanco","/decisions":"Registro de decisoes","/decisoes":"Registro de decisoes","/email":"Gerenciar email","/rascunho":"Rascunho de email","/memo":"Criar memo","/memos":"Listar memos","/note":"Criar nota","/notas":"Listar notas","/anotar":"Criar nota","/tags":"Ver tags","/memotags":"Tags de memos","/rmmemo":"Remover memo","/rmnota":"Remover nota","/index":"Indexar conteudo","/indexar":"Indexar conteudo","/reindex":"Reindexar tudo","/memory":"Ver memoria","/memoria":"Ver memoria","/clipboard":"Ver clipboard","/area":"Ver area de transferencia","/tela":"Capturar tela","/screen":"Capturar tela","/ps1":"Customizar prompt","/refresh":"Atualizar dados","/renovar":"Atualizar dados","/vault":"Gerenciar vault","/backup":"Fazer backup","/feeds":"Ver feeds RSS","/fontes":"Ver fontes RSS","/addfeed":"Adicionar feed","/novafonte":"Adicionar fonte","/rmfeed":"Remover feed","/rmfonte":"Remover fonte","/disablefeed":"Desativar feed","/desativarfonte":"Desativar fonte","/enablefeed":"Ativar feed","/ativarfonte":"Ativar fonte","/projeto":"Ver projeto","/project":"Ver projeto","/projetos":"Listar projetos","/projects":"Listar projetos","/sessao":"Sessao de trabalho","/session":"Work session","/relatorio":"Gerar relatorio","/report":"Gerar relatorio","/oportunidades":"Ver oportunidades","/opportunities":"Ver oportunidades","/schedule":"Ver agenda"};ghostText="";tabCycleMatches=[];tabCycleIndex=-1;tabCycleBase="";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 $8}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 Xz(MF(this.dataDir,"history"));this.setupEventListeners(),E(B.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(J0.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(J0.on("status:update",($)=>{let Z=$.level==="error"?w.err:$.level==="warning"?w.prompt:$.level==="success"?w.sys:B.dim;if(this.lines.push({text:` ${Z}[${$.source}]${B.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(J0.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${w.prompt}\u26A0 ${$.message}${B.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${w.err}\u26A0 Rate limit: ${$.message}${B.reset}`});else this.lines.push({text:` ${B.dim}[telemetry] ${$.message}${B.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(J0.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${B.dim}[backup] ${$.message||"Backup concluido"}${B.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${w.sys}[pomodoro] ${$.message}${B.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${w.err}[${$.taskType}] ${$.message}${B.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(J0.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(J0.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(B.show),E(B.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=MZ(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=MZ(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:` ${w.tool}\u2699 ${$}${B.reset} ${B.dim}${Q}${B.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
1483
+ `),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:` ${B.dim}${X}${B.reset}`})}if(Y.length>8)this.lines.push({text:` ${B.dim}... (${Y.length-8} more lines)${B.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${w.prompt}? ${$}${B.reset} ${B.dim}[y]es / [n]o / [a]ll${B.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(Q)=>{let z=Q.toString().toLowerCase();if(z==="y"||z==="\r"||z===`
1484
+ `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${w.sys}approved${B.reset}`}),this.renderAll(),Z(!0);else if(z==="n"||z==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${w.err}rejected${B.reset}`}),this.renderAll(),Z(!1);else if(z==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${w.sys}approved all for this session${B.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${B.dim}timeout \u2014 auto-rejected${B.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=$.findIndex((G)=>G.isCurrent);if(Y<0)Y=0;let Q="",z=!1,J=()=>{if(!Q)return $;let G=Q.toLowerCase();return $.filter((W)=>W.name.toLowerCase().includes(G))},X=()=>{let H=this.height-2-2,U=J();if(Y>=U.length)Y=Math.max(0,U.length-1);let q=2,N=2,C=H-q-N,M=Math.max(1,C),F=0;if(U.length>M)F=Math.max(0,Y-Math.floor(M/2)),F=Math.min(F,U.length-M);let T=U.slice(F,F+M);if(E(B.hide),E(B.to(3,1)),E(B.clearLine),z)E(` ${w.heading}${B.bold}Sessions${B.reset} ${B.dim}filter: ${Q}\u2588${B.reset}`);else E(` ${w.heading}${B.bold}Sessions${B.reset} ${B.dim}(${U.length})${B.reset}`);E(B.to(4,1)),E(B.clearLine);for(let x=0;x<M;x++){let l=2+q+x+1;if(E(B.to(l,1)),E(B.clearLine),x>=T.length)continue;let G0=T[x],M0=F+x===Y,a=G0.isCurrent?"*":" ",E0=G0.isArchived?`${B.dim}[arch] ${B.reset}`:" ",s0=`${G0.messageCount} msgs`.padEnd(10),b0=FF(G0.updated);if(M0)E(` ${w.prompt}${B.bold}\u203A ${a} ${E0}${w.prompt}${B.bold}${G0.name.padEnd(20)}${B.reset} ${B.dim}${s0} ${b0}${B.reset}`);else{let A0=G0.isArchived?B.dim:w.sys;E(` ${a} ${E0}${A0}${G0.name.padEnd(20)}${B.reset} ${B.dim}${s0} ${b0}${B.reset}`)}}for(let x=T.length;x<M;x++){let l=2+q+x+1;E(B.to(l,1)),E(B.clearLine)}let v=2+q+M+1;if(E(B.to(v,1)),E(B.clearLine),U.length>M){let x=Math.round((Y+1)/U.length*100);E(` ${B.dim}${F>0?"\u2191":" "} ${x}% ${F+M<U.length?"\u2193":" "}${B.reset}`)}let D=this.height-2;E(B.to(D,1)),E(B.clearLine),E(` ${B.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${B.reset}`)},K=(G)=>{this.pickerActive=!1,process.stdin.removeListener("data",V),this.renderAll(),Z(G)},V=(G)=>{let W=G.toString("utf-8"),H=J();if(W==="\x1B"&&G.length===1){if(z)z=!1,Q="",X();else K(null);return}if(W==="\x03"){K(null);return}if(W==="\r"||W===`
1485
+ `){if(H.length>0&&Y<H.length)K({action:"load",name:H[Y].name});return}if(W==="\x1B[A"||W==="w"&&!z){if(Y>0)Y--,X();return}if(W==="\x1B[B"||W==="s"&&!z){if(Y<H.length-1)Y++,X();return}if(W==="d"&&z===!1){if(H.length>0&&Y<H.length){let U=H[Y];if(!U.isCurrent)K({action:"delete",name:U.name,isArchived:U.isArchived})}return}if(W==="a"&&z===!1){if(H.length>0&&Y<H.length){let U=H[Y];if(!U.isCurrent){let q=U.isArchived?"unarchive":"archive";K({action:q,name:U.name})}}return}if(W==="/"&&z===!1){z=!0,Q="",X();return}if(z){if(W==="\x7F"||W==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,X();else z=!1,X();return}if(W.length===1&&W>=" "){Q+=W,Y=0,X();return}}};process.stdin.on("data",V),X()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=0,Q="",z=!1,J="",X=[...new Set($.map((U)=>U.category))].sort(),K=()=>{let U=J?$.filter((q)=>q.category===J):$;if(Q){let q=Q.toLowerCase();U=U.filter((N)=>N.title.toLowerCase().includes(q)||N.source.toLowerCase().includes(q))}return U},V=(U)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[U]||U},G=()=>{let N=this.height-2-2,C=K();if(Y>=C.length)Y=Math.max(0,C.length-1);let M=2,F=2,T=N-M-F,v=Math.max(1,T),D=0;if(C.length>v)D=Math.max(0,Y-Math.floor(v/2)),D=Math.min(D,C.length-v);let x=C.slice(D,D+v);if(E(B.hide),E(B.to(3,1)),E(B.clearLine),z)E(` ${w.heading}${B.bold}Noticias${B.reset} ${B.dim}filtro: ${Q}\u2588${B.reset}`);else{let m=J?V(J):"Todas";E(` ${w.heading}${B.bold}Noticias${B.reset} ${B.dim}(${C.length}) ${m}${B.reset}`)}E(B.to(4,1)),E(B.clearLine);for(let m=0;m<v;m++){let M0=2+M+m+1;if(E(B.to(M0,1)),E(B.clearLine),m>=x.length)continue;let a=x[m],E0=D+m===Y,s0=a.time?`[${a.time}]`:" ",b0=this.width-30,A0=a.title.length>b0?a.title.slice(0,b0-1)+"\u2026":a.title;if(E0)E(` ${w.prompt}${B.bold}\u203A ${s0} ${A0}${B.reset} ${B.dim}(${a.source})${B.reset}`);else E(` ${B.dim}${s0}${B.reset} ${w.sys}${A0}${B.reset} ${B.dim}(${a.source})${B.reset}`)}for(let m=x.length;m<v;m++){let M0=2+M+m+1;E(B.to(M0,1)),E(B.clearLine)}let l=2+M+v+1;if(E(B.to(l,1)),E(B.clearLine),C.length>v){let m=Math.round((Y+1)/C.length*100);E(` ${B.dim}${D>0?"\u2191":" "} ${m}% ${D+v<C.length?"\u2193":" "}${B.reset}`)}let G0=this.height-2;E(B.to(G0,1)),E(B.clearLine),E(` ${B.dim}\u2191\u2193 navegar Enter abrir Ctrl+Enter ler aqui Esc cancelar / filtrar Tab categoria${B.reset}`)},W=(U)=>{this.pickerActive=!1,process.stdin.removeListener("data",H),this.renderAll(),Z(U)},H=(U)=>{let q=U.toString("utf-8"),N=K();if(q==="\x1B"&&U.length===1){if(z)z=!1,Q="",G();else W(null);return}if(q==="\x03"){W(null);return}if(q===`
1486
+ `||q==="\x1B\r"||q==="\x1BOM"){if(N.length>0&&Y<N.length)W({action:"read",link:N[Y].link});return}if(q==="\r"||q===`
1487
+ `){if(N.length>0&&Y<N.length)W({action:"open",link:N[Y].link});return}if(q==="\x1B[A"||q==="w"&&!z){if(Y>0)Y--,G();return}if(q==="\x1B[B"||q==="s"&&!z){if(Y<N.length-1)Y++,G();return}if(q==="\t"){if(!J)J=X[0]||"";else{let C=X.indexOf(J);J=C<X.length-1?X[C+1]:""}Y=0,G();return}if(q==="/"&&!z){z=!0,Q="",G();return}if(z){if(q==="\x7F"||q==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,G();else z=!1,G();return}if(q.length===1&&q>=" "){Q+=q,Y=0,G();return}}};process.stdin.on("data",H),G()})}showUsage($){this.lines.push({text:` ${B.dim}tokens: ${$}${B.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){let Z=this.width-6;for(let Y of $.split(`
1488
+ `))for(let Q of C1(Y,Z))this.lines.push({text:` ${w.err}\u2717 ${Q}${B.reset}`});this.lines.push({text:""}),this.renderAll()}showSystem($){let Z=this.width-4;for(let Y of $.split(`
1489
+ `))for(let Q of C1(Y,Z))this.lines.push({text:` ${w.sys}${Q}${B.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(B.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),RZ(),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=FZ(this.metaLearningEntries,Q);Z=[...Z,z]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),LZ(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=Hz($,{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(B.hide);for(let Y=0;Y<$.length;Y++)E(B.to(Z+Y,1)),E(B.clearLine),E($[Y]);E(B.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;E(B.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)E(B.to($+Z,1)),E(B.clearLine);E(B.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(J0.emit("insight:accepted",Z),this.lines.push({text:` ${w.sys}\u2713 Dica aceita: ${$.title}${B.reset}`}),$.suggestedAction)this.lines.push({text:` ${B.dim}Executando: ${$.suggestedAction.command}${B.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=FZ($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=Qz($),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(B.hide),E(B.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),V=Math.floor((Y-X*(J+1))/J),G=0;for(let W=0;W<J;W++)for(let H=0;H<z&&G<Q.length;H++){let U=Q[G],q=$+X+W*(V+X)+1,N=X+H*(K+X)+1;this.drawDashboardPanel(U,q,N,K,V),G++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(B.show)}drawDashboardPanel($,Z,Y,Q,z){let J=this.personaMode==="sharpen_or_relax"?this.palette.muted:B.dim,X=this.palette.primary,K=e3($.content.slice(0,z-2),Q,{title:$.title,borderColor:J,titleColor:X});for(let V=0;V<K.length&&V<z;V++)E(B.to(Z+V,Y)),E(K[V])}renderStickyStatusBar(){if(!this.statusBarEnabled)return;let $=this.height-2;this.stickyStatusRow=$;let Z=[];if(this.personaMode!=="productivity"){let Q=this.personaMode==="spillover_alert"?this.palette.accent:this.palette.primary;Z.push({label:"MODE",value:this.getPersonaLabel(),color:Q})}if(this.timeContext&&this.personaMode==="spillover_alert"){let Q=this.timeContext.urgentTasks.length+this.timeContext.overdueTasks.length+this.timeContext.pendingCommits.length;if(Q>0)Z.push({label:"PEND",value:String(Q),color:this.palette.accent})}let Y={model:this.model,project:this.activeProject||void 0,tokens:{input:this.inputTokens,output:this.outputTokens},sessionCost:this.sessionCost||void 0,vaultStatus:this.vaultStatus,customItems:Z.length>0?Z:void 0};E(B.to($,1)),E(this.renderPersonaAwareStatusBar(Y))}renderPersonaAwareStatusBar($){let Z=t3($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${L2(Z)}${B.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(E(B.hide),E(B.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(B.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){E(B.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();E(Z),E(B.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-C0(Q)-J.length);E(Q+" ".repeat(X)+J),E(B.reset),E(B.to(2,1));let K=this.personaMode==="sharpen_or_relax"?this.palette.muted:B.dim;E(`${K}${"\u2500".repeat(this.width)}${B.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return B.bg(52);case"sharpen_or_relax":return B.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),V=z.slice(X,K);E(B.hide);for(let G=0;G<Q;G++)if(E(B.to(2+G+1,1)),E(B.clearLine),G<V.length)E(V[G].text)}resetTabCycle(){this.tabCycleMatches=[],this.tabCycleIndex=-1,this.tabCycleBase=""}updateGhostText(){let $=this.inputBuf;if(this.ghostText="",this.inputPos!==$.length)return;if($.length===0)return;if($.startsWith("/")){let Z=$.split(" ");if(Z.length===1){let Y=s3($,this.commands);if(Y.length>0){let Q=Y[0].item;if(Q!==$&&Q.startsWith($)){let z=Q.slice($.length),J=this.commandDescriptions[Q];this.ghostText=J?`${z} ${J}`:z;return}if(Q!==$){let z=this.commandDescriptions[Q];this.ghostText=z?` \u2192 ${Q} ${z}`:` \u2192 ${Q}`;return}}}else{let Y=Z[0],Q=this.subcommands[Y];if(Q&&Q.length>0){let z=Z[Z.length-1].toLowerCase();if(z){let J=Q.filter((X)=>X.toLowerCase().startsWith(z));if(J.length>0){this.ghostText=J[0].slice(z.length);return}}else{this.ghostText=Q[0];return}}}}if(!$.startsWith("/")&&$.length>=2&&this.history){let Z=this.history.getEntries();for(let Q=Z.length-1;Q>=0;Q--)if(Z[Q].startsWith($)&&Z[Q]!==$){this.ghostText=Z[Q].slice($.length);return}let Y=s3($,[...Z].reverse().slice(0,100));if(Y.length>0&&Y[0].match.score>50){let Q=Y[0].item;if(Q!==$)this.ghostText=` \u2192 ${Q}`}}}completeInput($){let Z=$.split(" "),Y=Z[0];if(this.tabCycleMatches.length>1&&this.tabCycleBase){this.tabCycleIndex=(this.tabCycleIndex+1)%this.tabCycleMatches.length;let X=this.tabCycleMatches[this.tabCycleIndex],K=`[${this.tabCycleIndex+1}/${this.tabCycleMatches.length}]`,V=this.commandDescriptions[X],G=V?`${K} ${V}`:K;if(Z.length===1||this.tabCycleBase.split(" ").length===1){let W=this.subcommands[X];return{value:X+(W?.length?" ":" "),options:G}}else{let W=this.tabCycleBase.split(" ");return W[W.length-1]=X,{value:W.join(" ")+" ",options:G}}}if(Z.length===1){let X=this.commands.filter((M)=>M.startsWith(Y)),K=Y.length>=2?s3(Y,this.commands).map((M)=>M.item):[],V=new Set(X),G=[...X,...K.filter((M)=>!V.has(M))];if(G.length===0)return null;if(G.length===1){let M=G[0],F=this.subcommands[M],T=this.commandDescriptions[M],v=F?.length?`Opcoes: ${F.join(" ")}`:void 0,D=T?v?`${T}
1490
+ ${v}`:T:v;return{value:M+" ",options:D}}this.tabCycleMatches=G,this.tabCycleIndex=0,this.tabCycleBase=$;let W=G[0],H=this.commandDescriptions[W],U=G.slice(0,12).map((M)=>{let F=this.commandDescriptions[M];return F?`${M} ${B.dim}${F}${B.reset}`:M}),q=G.length>12?` ${B.dim}+${G.length-12} mais${B.reset}`:"",N=`[1/${G.length}]`;if(X.length>1){let M=X[0];for(let F of X)while(!F.startsWith(M))M=M.slice(0,-1);if(M.length>$.length)return{value:M,options:`${N}
1488
1491
  ${U.join(`
1489
- `)}${q}`}}let C=this.subcommands[H];return{value:H+(C?.length?" ":" "),options:`${N}${W?" "+W:""}
1492
+ `)}${q}`}}let C=this.subcommands[W];return{value:W+(C?.length?" ":" "),options:`${N}${H?" "+H:""}
1490
1493
  ${U.join(`
1491
- `)}${q}`}}let Q=this.subcommands[Y];if(!Q||Q.length===0)return null;let z=Z[Z.length-1].toLowerCase(),J=z?Q.filter((X)=>X.toLowerCase().startsWith(z)):[...Q];if(J.length===0&&z){let X=r3(z,Q);if(X.length>0){let K=X.map((V)=>V.item);if(K.length===1)return Z[Z.length-1]=K[0],{value:Z.join(" ")+" "};return this.tabCycleMatches=K,this.tabCycleIndex=0,this.tabCycleBase=$,Z[Z.length-1]=K[0],{value:Z.join(" ")+" ",options:`[1/${K.length}] ${K.join(" ")}`}}return null}if(J.length===1)return Z[Z.length-1]=J[0],{value:Z.join(" ")+" "};if(J.length>1)return this.tabCycleMatches=J,this.tabCycleIndex=0,this.tabCycleBase=$,Z[Z.length-1]=J[0],{value:Z.join(" ")+" ",options:`[1/${J.length}] ${J.join(" ")}`};return null}renderInput(){let $=this.height-1,Z=this.height;if(E(B.to($,1)),E(B.clearLine),E(`${B.dim}${"\u2500".repeat(this.width)}${B.reset}`),E(B.to(Z,1)),E(B.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);E(` ${S.ai}${this.getSpinnerChar()}${B.reset} ${B.dim}streaming... ${Y}s${B.reset}`),E(B.hide)}else{let Y=`${S.prompt}\u276F${B.reset} `,Q=this.width-3,z=O0(this.inputBuf)>Q?this.inputBuf.slice(this.inputBuf.length-Q):this.inputBuf;if(E(Y+z),this.ghostText&&this.inputPos===this.inputBuf.length){let K=Q-O0(this.inputBuf);if(K>2){let V=this.ghostText.length>K?this.ghostText.slice(0,K-1)+"\u2026":this.ghostText;E(`${B.dim}${B.italic}${V}${B.reset}`)}}let J=this.inputBuf.slice(0,this.inputPos),X=O0(J)+3;E(B.to(Z,Math.min(X,this.width))),E(B.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(this.viewMode==="dashboard"){this.enterChatMode();return}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.ghostText="",this.resetTabCycle(),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.ghostText="",this.renderInput(),Y.options)this.showSystem(Y.options)}}else if(this.ghostText){let Y=this.ghostText.startsWith(" \u2192")?"":this.ghostText;if(Y)this.inputBuf+=Y,this.inputPos=this.inputBuf.length,this.ghostText="",this.renderInput()}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!jH(Z)){this.resetTabCycle();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.updateGhostText(),this.renderInput();return}if(Z==="\r"||Z===`
1494
+ `)}${q}`}}let Q=this.subcommands[Y];if(!Q||Q.length===0)return null;let z=Z[Z.length-1].toLowerCase(),J=z?Q.filter((X)=>X.toLowerCase().startsWith(z)):[...Q];if(J.length===0&&z){let X=s3(z,Q);if(X.length>0){let K=X.map((V)=>V.item);if(K.length===1)return Z[Z.length-1]=K[0],{value:Z.join(" ")+" "};return this.tabCycleMatches=K,this.tabCycleIndex=0,this.tabCycleBase=$,Z[Z.length-1]=K[0],{value:Z.join(" ")+" ",options:`[1/${K.length}] ${K.join(" ")}`}}return null}if(J.length===1)return Z[Z.length-1]=J[0],{value:Z.join(" ")+" "};if(J.length>1)return this.tabCycleMatches=J,this.tabCycleIndex=0,this.tabCycleBase=$,Z[Z.length-1]=J[0],{value:Z.join(" ")+" ",options:`[1/${J.length}] ${J.join(" ")}`};return null}renderInput(){let $=this.height-1,Z=this.height;if(E(B.to($,1)),E(B.clearLine),E(`${B.dim}${"\u2500".repeat(this.width)}${B.reset}`),E(B.to(Z,1)),E(B.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);E(` ${w.ai}${this.getSpinnerChar()}${B.reset} ${B.dim}streaming... ${Y}s${B.reset}`),E(B.hide)}else{let Y=`${w.prompt}\u276F${B.reset} `,Q=this.width-3,z=C0(this.inputBuf)>Q?this.inputBuf.slice(this.inputBuf.length-Q):this.inputBuf;if(E(Y+z),this.ghostText&&this.inputPos===this.inputBuf.length){let K=Q-C0(this.inputBuf);if(K>2){let V=this.ghostText.length>K?this.ghostText.slice(0,K-1)+"\u2026":this.ghostText;E(`${B.dim}${B.italic}${V}${B.reset}`)}}let J=this.inputBuf.slice(0,this.inputPos),X=C0(J)+3;E(B.to(Z,Math.min(X,this.width))),E(B.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(this.viewMode==="dashboard"){this.enterChatMode();return}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.ghostText="",this.resetTabCycle(),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.ghostText="",this.renderInput(),Y.options)this.showSystem(Y.options)}}else if(this.ghostText){let Y=this.ghostText.startsWith(" \u2192")?"":this.ghostText;if(Y)this.inputBuf+=Y,this.inputPos=this.inputBuf.length,this.ghostText="",this.renderInput()}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!vW(Z)){this.resetTabCycle();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.updateGhostText(),this.renderInput();return}if(Z==="\r"||Z===`
1492
1495
  `){if(this.resetTabCycle(),this.ghostText="",this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
1493
- `,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.resetTabCycle(),this.inputPos>0){let Y=LH(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-Y)+this.inputBuf.slice(this.inputPos),this.inputPos-=Y,this.updateGhostText(),this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(this.resetTabCycle(),Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=LH(this.inputBuf,this.inputPos),this.ghostText="",this.renderInput();break;case"C":if(this.ghostText&&this.inputPos===this.inputBuf.length){let Q=this.ghostText.startsWith(" \u2192")?"":this.ghostText;if(Q){let z=Q.indexOf(" "),J=z>=0?Q.slice(0,z):Q;this.inputBuf+=J,this.inputPos=this.inputBuf.length,this.ghostText="",this.updateGhostText(),this.renderInput();break}}if(this.inputPos<this.inputBuf.length)this.inputPos+=RH(this.inputBuf,this.inputPos),this.updateGhostText(),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.updateGhostText(),this.renderInput();break}case"B":{let Q=this.history?.next();if(Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.updateGhostText(),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.ghostText="",this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.updateGhostText(),this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Q=RH(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.updateGhostText(),this.renderInput()}break}}return}if(YF(Z))this.resetTabCycle(),this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.updateGhostText(),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")CZ(3,this.height-2);else MZ();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${S.user}${B.bold} You${B.reset} ${B.dim}${Z}${B.reset}`});else this.lines.push({text:`${S.ai}${B.bold} Claude${B.reset} ${B.dim}${Z}${B.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=N1(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=BZ($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function jH($){return[...$].length===1}function YF($){if(!jH($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function LH($,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 RH($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function QF($){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 e3={"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}},zF={input:3,output:15};function PH($,Z){let Y=JF(Z),Q=$.inputTokens/1e6*Y.input*100,z=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:z,totalCostCents:Q+z}}function JF($){if(e3[$])return e3[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return e3["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return e3["claude-opus-4-20250514"];if(Z.includes("sonnet"))return e3["claude-sonnet-4-20250514"];return zF}class Vz{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=PH($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=PH($,this.model);return`${EZ($.inputTokens)} in / ${EZ($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${EZ(this.totalInput)} in / ${EZ(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function EZ($){return $.toLocaleString("en-US")}import{existsSync as AH,readFileSync as DH,statSync as TH}from"fs";import{basename as XF,extname as IH,resolve as wH}from"path";var SH=new Set([".png",".jpg",".jpeg",".gif",".webp"]),KF=20971520,VF=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"]),GF=1048576;function kH($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=IH(J).toLowerCase();if(SH.has(X)){let K=wH(J);if(AH(K))try{if(TH(K).size>KF){Q.push(`[image too large: ${J}]`);continue}let H=DH(K).toString("base64"),W=HF(X);Z.push({path:K,mediaType:W,base64:H}),Q.push(`[image: ${J}]`)}catch{Q.push(z)}else Q.push(z)}else Q.push(z)}return{text:Q.join(" "),images:Z}}function HF($){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 fH($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=IH(J).toLowerCase();if(SH.has(X)){Q.push(z);continue}if(!(VF.has(X)||(J.includes("/")||J.includes("\\"))&&X.length>0)){Q.push(z);continue}let V=wH(J);if(!AH(V)){Q.push(z);continue}try{let G=TH(V);if(!G.isFile()){Q.push(z);continue}if(G.size>GF){Q.push(`[file too large: ${J} (${(G.size/1024).toFixed(0)}KB)]`);continue}if(G.size===0){Q.push(`[empty file: ${J}]`);continue}let H=DH(V,"utf-8"),W=XF(V);Z.push({path:V,name:W,content:H,size:G.size}),Q.push(`[file: ${W}]`)}catch{Q.push(z)}}return{text:Q.join(" "),files:Z}}J2();import{existsSync as bH,readFileSync as WF}from"fs";import{join as yH}from"path";Z0();function UF(){let $=new Date().getDay();return $===0||$===6}function qF(){return UF()?"weekend":"weekday"}async function BF($){let Z=[],Y=[],Q=[],z=new Date,J=new Date(z);J.setHours(23,59,59,999);let X=yH($,"tasks.json");if(bH(X))try{let G=JSON.parse(WF(X,"utf-8"));for(let H of G){if(H.done)continue;if(H.dueAt){let W=new Date(H.dueAt),U=W<z,q=!U&&W<=J;if(U)Y.push({id:H.id,title:H.title,dueAt:H.dueAt,isOverdue:!0});else if(q)Z.push({id:H.id,title:H.title,dueAt:H.dueAt,isOverdue:!1})}}}catch(G){l.debug("Failed to parse task for spillover check",{error:G})}let K=D5(!0);for(let G of K.slice(0,5)){let H=await NF(G);if(H)Q.push(H)}return{hasSpillover:Z.length>0||Y.length>0||Q.length>0,urgentTasks:Z,overdueTasks:Y,pendingCommits:Q}}async function NF($){if(!bH(yH($.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){l.debug("Git status check failed for project",{error:Z})}return null}function OF($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function $8($){let Z=qF(),Y=await BF($),Q=OF(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function CF($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
1496
+ `,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.resetTabCycle(),this.inputPos>0){let Y=bW(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-Y)+this.inputBuf.slice(this.inputPos),this.inputPos-=Y,this.updateGhostText(),this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(this.resetTabCycle(),Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=bW(this.inputBuf,this.inputPos),this.ghostText="",this.renderInput();break;case"C":if(this.ghostText&&this.inputPos===this.inputBuf.length){let Q=this.ghostText.startsWith(" \u2192")?"":this.ghostText;if(Q){let z=Q.indexOf(" "),J=z>=0?Q.slice(0,z):Q;this.inputBuf+=J,this.inputPos=this.inputBuf.length,this.ghostText="",this.updateGhostText(),this.renderInput();break}}if(this.inputPos<this.inputBuf.length)this.inputPos+=yW(this.inputBuf,this.inputPos),this.updateGhostText(),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.updateGhostText(),this.renderInput();break}case"B":{let Q=this.history?.next();if(Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.updateGhostText(),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.ghostText="",this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.updateGhostText(),this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Q=yW(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.updateGhostText(),this.renderInput()}break}}return}if(EF(Z))this.resetTabCycle(),this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.updateGhostText(),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")LZ(3,this.height-2);else RZ();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${w.user}${B.bold} You${B.reset} ${B.dim}${Z}${B.reset}`});else this.lines.push({text:`${w.ai}${B.bold} Claude${B.reset} ${B.dim}${Z}${B.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=C1(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=MZ($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function vW($){return[...$].length===1}function EF($){if(!vW($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function bW($,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 yW($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function FF($){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 Z8={"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}},LF={input:3,output:15};function xW($,Z){let Y=RF(Z),Q=$.inputTokens/1e6*Y.input*100,z=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:z,totalCostCents:Q+z}}function RF($){if(Z8[$])return Z8[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return Z8["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return Z8["claude-opus-4-20250514"];if(Z.includes("sonnet"))return Z8["claude-sonnet-4-20250514"];return LF}class qz{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=xW($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=xW($,this.model);return`${jZ($.inputTokens)} in / ${jZ($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${jZ(this.totalInput)} in / ${jZ(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function jZ($){return $.toLocaleString("en-US")}import{existsSync as _W,readFileSync as hW,statSync as gW}from"fs";import{basename as jF,extname as mW,resolve as pW}from"path";var uW=new Set([".png",".jpg",".jpeg",".gif",".webp"]),PF=20971520,AF=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"]),DF=1048576;function dW($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=mW(J).toLowerCase();if(uW.has(X)){let K=pW(J);if(_W(K))try{if(gW(K).size>PF){Q.push(`[image too large: ${J}]`);continue}let W=hW(K).toString("base64"),H=TF(X);Z.push({path:K,mediaType:H,base64:W}),Q.push(`[image: ${J}]`)}catch{Q.push(z)}else Q.push(z)}else Q.push(z)}return{text:Q.join(" "),images:Z}}function TF($){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 cW($){let Z=[],Y=$.split(/\s+/),Q=[];for(let z of Y){let J=z.replace(/^["']|["']$/g,""),X=mW(J).toLowerCase();if(uW.has(X)){Q.push(z);continue}if(!(AF.has(X)||(J.includes("/")||J.includes("\\"))&&X.length>0)){Q.push(z);continue}let V=pW(J);if(!_W(V)){Q.push(z);continue}try{let G=gW(V);if(!G.isFile()){Q.push(z);continue}if(G.size>DF){Q.push(`[file too large: ${J} (${(G.size/1024).toFixed(0)}KB)]`);continue}if(G.size===0){Q.push(`[empty file: ${J}]`);continue}let W=hW(V,"utf-8"),H=jF(V);Z.push({path:V,name:H,content:W,size:G.size}),Q.push(`[file: ${H}]`)}catch{Q.push(z)}}return{text:Q.join(" "),files:Z}}K2();import{existsSync as lW,readFileSync as IF}from"fs";import{join as oW}from"path";Y0();function SF(){let $=new Date().getDay();return $===0||$===6}function wF(){return SF()?"weekend":"weekday"}async function kF($){let Z=[],Y=[],Q=[],z=new Date,J=new Date(z);J.setHours(23,59,59,999);let X=oW($,"tasks.json");if(lW(X))try{let G=JSON.parse(IF(X,"utf-8"));for(let W of G){if(W.done)continue;if(W.dueAt){let H=new Date(W.dueAt),U=H<z,q=!U&&H<=J;if(U)Y.push({id:W.id,title:W.title,dueAt:W.dueAt,isOverdue:!0});else if(q)Z.push({id:W.id,title:W.title,dueAt:W.dueAt,isOverdue:!1})}}}catch(G){o.debug("Failed to parse task for spillover check",{error:G})}let K=I5(!0);for(let G of K.slice(0,5)){let W=await fF(G);if(W)Q.push(W)}return{hasSpillover:Z.length>0||Y.length>0||Q.length>0,urgentTasks:Z,overdueTasks:Y,pendingCommits:Q}}async function fF($){if(!lW(oW($.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){o.debug("Git status check failed for project",{error:Z})}return null}function bF($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function Y8($){let Z=wF(),Y=await kF($),Q=bF(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function yF($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
1494
1497
  Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${Y}
1495
1498
  \u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${Y}
1496
- Modo: Sharpen or Relax`}}function MF($){let Z=[];if($.overdueTasks.length>0){Z.push(`
1499
+ Modo: Sharpen or Relax`}}function vF($){let Z=[];if($.overdueTasks.length>0){Z.push(`
1497
1500
  --- 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(`
1498
1501
  --- 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(`
1499
1502
  --- 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(`
1500
- `)}function EF($){if($.persona!=="sharpen_or_relax")return"";return`
1503
+ `)}function xF($){if($.persona!=="sharpen_or_relax")return"";return`
1501
1504
  --- Fim de Semana Livre ---
1502
1505
 
1503
1506
  [A] Amolar o Machado
1504
1507
  Estudo de arquitetura, refatoracao, melhoria do CLI
1505
1508
 
1506
1509
  [B] Descompressao Criativa
1507
- Projetos paralelos sem prazo, foco pessoal/familia`}function FF($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
1510
+ Projetos paralelos sem prazo, foco pessoal/familia`}function _F($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
1508
1511
  --- Sugestao: Timebox ---
1509
1512
  Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
1510
- Depois: descanso merecido.`}async function vH($){let Z=[],Y=null;if($)Y=await $8($),Z.push(CF(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await p2();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let J=MF(Y);if(J)Z.push(J);let X=FF(Y);if(X)Z.push(X)}if(Y){let J=EF(Y);if(J)Z.push(J)}if(R)try{let J=await G1();Z.push(`
1513
+ Depois: descanso merecido.`}async function iW($){let Z=[],Y=null;if($)Y=await Y8($),Z.push(yF(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await d2();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let J=vF(Y);if(J)Z.push(J);let X=_F(Y);if(X)Z.push(X)}if(Y){let J=xF(Y);if(J)Z.push(J)}if(R)try{let J=await H1();Z.push(`
1511
1514
  --- Agenda ---
1512
1515
  ${J}`)}catch{Z.push(`
1513
1516
  --- Agenda ---
1514
- Outlook nao disponivel.`)}if(R)try{let J=await m2();Z.push(`
1517
+ Outlook nao disponivel.`)}if(R)try{let J=await u2();Z.push(`
1515
1518
  --- Sistema ---
1516
- ${J}`)}catch(J){l.debug("System info unavailable for briefing",{error:J})}let z=Y?.persona==="sharpen_or_relax"?2:3;try{let J=await P1(["finance","business","tech"],z);Z.push(`
1519
+ ${J}`)}catch(J){o.debug("System info unavailable for briefing",{error:J})}let z=Y?.persona==="sharpen_or_relax"?2:3;try{let J=await D1(["finance","business","tech"],z);Z.push(`
1517
1520
  ${J}`)}catch{Z.push(`
1518
1521
  --- Noticias ---
1519
1522
  Falha ao carregar noticias.`)}return Z.push(`
1520
1523
  ======================`),Z.join(`
1521
- `)}Z0();Q1();var d=null,FZ=null,Gz=null,Hz=0;function hH($){Gz=$}function gH($="foco",Z=25,Y=5){if(d)return`Pomodoro ja ativo: "${d.label}" (${uH()}). Use /pomodoro stop para parar.`;return d={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},Hz++,pH(),`Pomodoro #${Hz} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function mH(){if(!d)return"Nenhum pomodoro ativo.";let $=d.label,Z=Math.floor((Date.now()-d.startedAt)/60000);return LZ(),d=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function Wz(){if(!d)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=uH();return`${d.type==="work"?"Trabalhando":"Pausa"}: "${d.label}" \u2014 ${$} restante(s) (ciclo #${Hz})`}function pH(){if(!d)return;LZ();let $=d.startedAt+d.durationMs-Date.now();if($<=0){xH();return}FZ=setTimeout(xH,$)}function xH(){if(!d)return;if(d.type==="work"){let $=`Pomodoro: "${d.label}" concluido! Hora da pausa (${d.breakMs/60000}min).`;_H("Pausa!",`"${d.label}" concluido. Descanse ${d.breakMs/60000} minutos.`),Gz?.($),d={...d,type:"break",startedAt:Date.now(),durationMs:d.breakMs},pH()}else _H("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),Gz?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),LZ(),d=null}function LZ(){if(FZ)clearTimeout(FZ),FZ=null}function uH(){if(!d)return"0min";let $=Math.max(0,d.startedAt+d.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function _H($,Z){if(!R)return;try{await m1($,Z,{timeout:1e4})}catch{}}function dH(){LZ(),d=null}Z0();Q1();var Z1=new Map,Uz=null;function lH($){Uz=$}function oH($,Z=60){if(!R)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(Z1.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>cH(Y),Z*1000);return Z1.set(Y,{name:$,interval:Q,lastSeen:!0}),cH(Y),`Monitorando "${$}" a cada ${Z}s.`}function iH($){let Z=$.toLowerCase(),Y=Z1.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),Z1.delete(Z),`Monitor parado: "${$}"`}function nH(){if(Z1.size===0)return"Nenhum processo monitorado.";let $=[...Z1.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${Z1.size}):
1524
+ `)}Y0();J1();var c=null,PZ=null,Bz=null,Nz=0;function aW($){Bz=$}function sW($="foco",Z=25,Y=5){if(c)return`Pomodoro ja ativo: "${c.label}" (${$H()}). Use /pomodoro stop para parar.`;return c={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},Nz++,eW(),`Pomodoro #${Nz} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function tW(){if(!c)return"Nenhum pomodoro ativo.";let $=c.label,Z=Math.floor((Date.now()-c.startedAt)/60000);return AZ(),c=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function Oz(){if(!c)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=$H();return`${c.type==="work"?"Trabalhando":"Pausa"}: "${c.label}" \u2014 ${$} restante(s) (ciclo #${Nz})`}function eW(){if(!c)return;AZ();let $=c.startedAt+c.durationMs-Date.now();if($<=0){nW();return}PZ=setTimeout(nW,$)}function nW(){if(!c)return;if(c.type==="work"){let $=`Pomodoro: "${c.label}" concluido! Hora da pausa (${c.breakMs/60000}min).`;rW("Pausa!",`"${c.label}" concluido. Descanse ${c.breakMs/60000} minutos.`),Bz?.($),c={...c,type:"break",startedAt:Date.now(),durationMs:c.breakMs},eW()}else rW("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),Bz?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),AZ(),c=null}function AZ(){if(PZ)clearTimeout(PZ),PZ=null}function $H(){if(!c)return"0min";let $=Math.max(0,c.startedAt+c.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function rW($,Z){if(!R)return;try{await u1($,Z,{timeout:1e4})}catch{}}function ZH(){AZ(),c=null}Y0();J1();var z1=new Map,Cz=null;function QH($){Cz=$}function zH($,Z=60){if(!R)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(z1.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>YH(Y),Z*1000);return z1.set(Y,{name:$,interval:Q,lastSeen:!0}),YH(Y),`Monitorando "${$}" a cada ${Z}s.`}function JH($){let Z=$.toLowerCase(),Y=z1.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),z1.delete(Z),`Monitor parado: "${$}"`}function XH(){if(z1.size===0)return"Nenhum processo monitorado.";let $=[...z1.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${z1.size}):
1522
1525
  ${$.join(`
1523
- `)}`}function rH(){for(let $ of Z1.values())clearInterval($.interval);Z1.clear()}async function cH($){let Z=Z1.get($);if(!Z)return;let Y=await G8(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;m1("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),Uz?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;Uz?.(Q)}Z1.set($,{...Z,lastSeen:Y})}h();z1();var LF=60000,RF=300000,n0={timer:null,lastRefresh:0,refreshCount:0,running:!1},F2=null;function aH($,Z={}){qz(),F2=$;let Y=Z.checkIntervalMs??LF,Q=Z.refreshBufferMs??RF,z=setInterval(()=>{PF(Q,Z)},Y);if(z.unref)z.unref();n0={timer:z,lastRefresh:Date.now(),refreshCount:0,running:!0},l.debug("Auto-refresh started",{checkInterval:Y,refreshBuffer:Q}),G0("status:update",{source:"auto-refresh",message:"Auto-refresh ativo",level:"info",timestamp:Date.now()})}function qz(){if(n0.timer)clearInterval(n0.timer);n0={...n0,timer:null,running:!1},F2=null}function sH($){F2=$}function jF(){let $=F2?.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:n0.running,lastRefresh:n0.lastRefresh,refreshCount:n0.refreshCount,tokenExpiresAt:$,tokenExpiresIn:Z}}function tH(){let $=jF(),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(`
1524
- `)}function PF($,Z){if(!F2)return;let Y=Date.now(),Q=F2.expiresAt-Y;if(Q>$)return;l.debug("Token near expiration, attempting refresh",{expiresIn:Math.round(Q/1000)}),G0("status:update",{source:"auto-refresh",message:"Renovando token automaticamente...",level:"warning",timestamp:Y});try{let z=j2();if(z&&z.expiresAt>F2.expiresAt){eH(z,Y,Z);return}AF(Y,Z)}catch(z){let J=`Erro ao renovar: ${z instanceof Error?z.message:String(z)}`;Z.onRefreshFailed?.(J),G0("status:update",{source:"auto-refresh",message:J,level:"error",timestamp:Y})}}function eH($,Z,Y){F2=$,n0={...n0,lastRefresh:Z,refreshCount:n0.refreshCount+1},Y.onRefreshed?.($),G0("status:update",{source:"auto-refresh",message:`Token renovado (expira ${DF($.expiresAt)})`,level:"success",timestamp:Z}),l.debug("Auto-refresh successful",{expiresAt:new Date($.expiresAt).toISOString(),refreshCount:n0.refreshCount})}function AF($,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=j2();if(z&&z.expiresAt>$)eH(z,Date.now(),Z);else Z.onRefreshFailed?.("Falha ao renovar token \u2014 claude nao rotacionou credenciais"),G0("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),G0("status:update",{source:"auto-refresh",message:z,level:"error",timestamp:Date.now()})})}catch{Z.onRefreshFailed?.("claude CLI nao encontrado \u2014 renovacao automatica indisponivel"),G0("status:update",{source:"auto-refresh",message:"claude CLI nao encontrado \u2014 renovacao automatica indisponivel",level:"error",timestamp:Date.now()})}}function DF($){return new Date($).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}J2();import{existsSync as TF,readFileSync as IF,writeFileSync as wF}from"fs";import{join as SF}from"path";Z0();var $W="",ZW=()=>SF($W,"last-morning.txt");function YW($){$W=$;let Z=ZW(),Y=new Date().toISOString().split("T")[0];if(!TF(Z))return!0;try{return IF(Z,"utf-8").trim()!==Y}catch{return!0}}function QW(){let $=new Date().toISOString().split("T")[0];wF(ZW(),$)}async function zW(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
1525
- `);let Q=await p2();$.push(Q);let J=s0().filter((U)=>{if(!U.dueAt)return!1;let q=new Date(U.dueAt),N=new Date;return q.toDateString()===N.toDateString()});if(J.length>0)$.push(`
1526
- --- Tarefas do dia ---`),$.push(f2(J));let X=R5();if(X.length>0)$.push(`
1527
- --- Follow-ups pendentes ---`),$.push(_6(X));let V=v2().filter((U)=>U.status==="atrasado");if(V.length>0)$.push(`
1528
- --- Delegacoes atrasadas ---`),$.push(x6(V));let G=a6();if(G)$.push(`
1529
- ${G}`);if(R)try{let U=await G1();$.push(`
1530
- --- Agenda ---`),$.push(U)}catch{}try{let U=await P1(["finance","business","tech"],2);$.push(`
1531
- `+U)}catch{}let H=t0();if(H.length>0){$.push(`
1532
- --- Lokaliza ---`);let U=H.reduce((N,C)=>N+C.pois.length,0),q=H.reduce((N,C)=>N+C.layers.length,0);$.push(`${H.length} bairro(s) monitorado(s), ${U} POIs, ${q} camadas de dados.`);for(let N of H.slice(0,5)){let C=N.metadata?.poiBreakdown,M=C?Object.entries(C).sort((F,T)=>T[1]-F[1]).slice(0,3).map(([F,T])=>`${F}: ${T}`).join(", "):`${N.pois.length} POIs`;$.push(` \u2022 ${N.name} (${N.city}/${N.state}) \u2014 ${M}`)}if(H.length>5)$.push(` ... e mais ${H.length-5} bairro(s).`)}let W=s0();if(W.length>0&&J.length!==W.length)$.push(`
1533
- ${W.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);try{let U=l2(),q=O9(),N=q.bestHours.includes(Z);if($.push(`
1534
- --- Energia ---`),$.push(N9(U)),N)$.push(`Este e um dos seus horarios de pico (${q.bestHours.map((C)=>`${C}h`).join(", ")}). Aproveite!`)}catch{}try{let U=U3();if(U.blockedToday>0)$.push(`
1526
+ `)}`}function KH(){for(let $ of z1.values())clearInterval($.interval);z1.clear()}async function YH($){let Z=z1.get($);if(!Z)return;let Y=await q8(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;u1("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),Cz?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;Cz?.(Q)}z1.set($,{...Z,lastSeen:Y})}g();X1();var hF=60000,gF=300000,a0={timer:null,lastRefresh:0,refreshCount:0,running:!1},R2=null;function VH($,Z={}){Mz(),R2=$;let Y=Z.checkIntervalMs??hF,Q=Z.refreshBufferMs??gF,z=setInterval(()=>{pF(Q,Z)},Y);if(z.unref)z.unref();a0={timer:z,lastRefresh:Date.now(),refreshCount:0,running:!0},o.debug("Auto-refresh started",{checkInterval:Y,refreshBuffer:Q}),W0("status:update",{source:"auto-refresh",message:"Auto-refresh ativo",level:"info",timestamp:Date.now()})}function Mz(){if(a0.timer)clearInterval(a0.timer);a0={...a0,timer:null,running:!1},R2=null}function GH($){R2=$}function mF(){let $=R2?.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:a0.running,lastRefresh:a0.lastRefresh,refreshCount:a0.refreshCount,tokenExpiresAt:$,tokenExpiresIn:Z}}function WH(){let $=mF(),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(`
1527
+ `)}function pF($,Z){if(!R2)return;let Y=Date.now(),Q=R2.expiresAt-Y;if(Q>$)return;o.debug("Token near expiration, attempting refresh",{expiresIn:Math.round(Q/1000)}),W0("status:update",{source:"auto-refresh",message:"Renovando token automaticamente...",level:"warning",timestamp:Y});try{let z=A2();if(z&&z.expiresAt>R2.expiresAt){HH(z,Y,Z);return}uF(Y,Z)}catch(z){let J=`Erro ao renovar: ${z instanceof Error?z.message:String(z)}`;Z.onRefreshFailed?.(J),W0("status:update",{source:"auto-refresh",message:J,level:"error",timestamp:Y})}}function HH($,Z,Y){R2=$,a0={...a0,lastRefresh:Z,refreshCount:a0.refreshCount+1},Y.onRefreshed?.($),W0("status:update",{source:"auto-refresh",message:`Token renovado (expira ${dF($.expiresAt)})`,level:"success",timestamp:Z}),o.debug("Auto-refresh successful",{expiresAt:new Date($.expiresAt).toISOString(),refreshCount:a0.refreshCount})}function uF($,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=A2();if(z&&z.expiresAt>$)HH(z,Date.now(),Z);else Z.onRefreshFailed?.("Falha ao renovar token \u2014 claude nao rotacionou credenciais"),W0("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),W0("status:update",{source:"auto-refresh",message:z,level:"error",timestamp:Date.now()})})}catch{Z.onRefreshFailed?.("claude CLI nao encontrado \u2014 renovacao automatica indisponivel"),W0("status:update",{source:"auto-refresh",message:"claude CLI nao encontrado \u2014 renovacao automatica indisponivel",level:"error",timestamp:Date.now()})}}function dF($){return new Date($).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}K2();import{existsSync as cF,readFileSync as lF,writeFileSync as oF}from"fs";import{join as iF}from"path";Y0();var UH="",qH=()=>iF(UH,"last-morning.txt");function BH($){UH=$;let Z=qH(),Y=new Date().toISOString().split("T")[0];if(!cF(Z))return!0;try{return lF(Z,"utf-8").trim()!==Y}catch{return!0}}function NH(){let $=new Date().toISOString().split("T")[0];oF(qH(),$)}async function OH(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
1528
+ `);let Q=await d2();$.push(Q);let J=$1().filter((U)=>{if(!U.dueAt)return!1;let q=new Date(U.dueAt),N=new Date;return q.toDateString()===N.toDateString()});if(J.length>0)$.push(`
1529
+ --- Tarefas do dia ---`),$.push(y2(J));let X=P5();if(X.length>0)$.push(`
1530
+ --- Follow-ups pendentes ---`),$.push(p6(X));let V=_2().filter((U)=>U.status==="atrasado");if(V.length>0)$.push(`
1531
+ --- Delegacoes atrasadas ---`),$.push(m6(V));let G=$9();if(G)$.push(`
1532
+ ${G}`);if(R)try{let U=await H1();$.push(`
1533
+ --- Agenda ---`),$.push(U)}catch{}try{let U=await D1(["finance","business","tech"],2);$.push(`
1534
+ `+U)}catch{}let W=Z1();if(W.length>0){$.push(`
1535
+ --- Lokaliza ---`);let U=W.reduce((N,C)=>N+C.pois.length,0),q=W.reduce((N,C)=>N+C.layers.length,0);$.push(`${W.length} bairro(s) monitorado(s), ${U} POIs, ${q} camadas de dados.`);for(let N of W.slice(0,5)){let C=N.metadata?.poiBreakdown,M=C?Object.entries(C).sort((F,T)=>T[1]-F[1]).slice(0,3).map(([F,T])=>`${F}: ${T}`).join(", "):`${N.pois.length} POIs`;$.push(` \u2022 ${N.name} (${N.city}/${N.state}) \u2014 ${M}`)}if(W.length>5)$.push(` ... e mais ${W.length-5} bairro(s).`)}let H=$1();if(H.length>0&&J.length!==H.length)$.push(`
1536
+ ${H.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);try{let U=i2(),q=F9(),N=q.bestHours.includes(Z);if($.push(`
1537
+ --- Energia ---`),$.push(E9(U)),N)$.push(`Este e um dos seus horarios de pico (${q.bestHours.map((C)=>`${C}h`).join(", ")}). Aproveite!`)}catch{}try{let U=B3();if(U.blockedToday>0)$.push(`
1535
1538
  ${U.blockedToday} notificacao(oes) filtrada(s) hoje pelo modo foco.`)}catch{}return $.push(`
1536
1539
  ==============================`),$.join(`
1537
- `)}h();h();J2();Z0();Q1();import{existsSync as JW,mkdirSync as kF,readFileSync as fF}from"fs";import{join as bF}from"path";import{randomUUID as yF}from"crypto";var XW="",j0=[],KW=()=>bF(XW,"workflows.json");function Z8(){P(KW(),JSON.stringify(j0,null,2))}function vF(){let $=KW();if(!JW($)){j0=Bz(),Z8();return}try{let Z=JSON.parse(fF($,"utf-8"));if(!Array.isArray(Z)){j0=Bz(),Z8();return}j0=Z.map((Y)=>({id:Y.id||Nz(),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{j0=Bz(),Z8()}}function Bz(){let $=new Date().toISOString();return[{id:Nz(),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:Nz(),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 VW($){if(XW=$,!JW($))kF($,{recursive:!0});vF()}function Y8($){let Z=$.toLowerCase().trim();return j0.find((Y)=>Y.id===$)||j0.find((Y)=>Y.name.toLowerCase()===Z)||j0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function GW($){let Z=[...j0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z}function Oz($,Z){let Y=Y8($);if(!Y)return null;return j0=j0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),Z8(),j0.find((Q)=>Q.id===Y.id)||null}function HW($){let Z=Y8($);if(!Z)return!1;return j0=j0.filter((Y)=>Y.id!==Z.id),Z8(),!0}async function Cz($,Z){let Y=Y8($);if(!Y){let z=j0.map((J)=>J.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${z}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await WW(Y.name,Y.steps,Z);return _F(Q)}async function WW($,Z,Y){let Q=performance.now(),z=[`Executando workflow: "${$}"`],J=0,X=0,K=0,V=!0;for(let G=0;G<Z.length;G++){let H=Z[G],W=H.label||`${H.action}:${H.target}`,U=`[${G+1}/${Z.length}]`,q=H.on_error||"continue";Y?.(`${U} ${W}...`);try{let N=await xF(H,Y);z.push(` ${U} ${N}`),J++}catch(N){let C=N instanceof Error?N.message:String(N);switch(K++,q){case"stop":return z.push(` ${U} ERRO (parando): ${C}`),V=!1,{workflow:$,success:V,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)};case"skip":z.push(` ${U} ERRO (pulado): ${C}`),X++;break;case"continue":default:z.push(` ${U} ERRO (continuando): ${C}`);break}}}return{workflow:$,success:V,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)}}async function xF($,Z){switch($.action){case"open_app":{if(!R)return`skip: ${$.target} (not Windows)`;return await S1($.target)}case"open_url":{if(!R)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 V1(Y)}case"run_command":{if(!R)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await q0(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(R)try{m1("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!R)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 WW(`${$.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 UW($){let Z=$||j0;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 V=K.label||K.target;return K.action==="wait"?`${K.target}s`:V}).join(" -> ");return` ${Q.name}${z}${J} \u2014 ${Q.description}
1540
+ `)}g();Q8();g();K2();Y0();J1();import{existsSync as RH,mkdirSync as HL,readFileSync as UL}from"fs";import{join as qL}from"path";import{randomUUID as BL}from"crypto";var jH="",P0=[],PH=()=>qL(jH,"workflows.json");function z8(){j(PH(),JSON.stringify(P0,null,2))}function NL(){let $=PH();if(!RH($)){P0=Dz(),z8();return}try{let Z=JSON.parse(UL($,"utf-8"));if(!Array.isArray(Z)){P0=Dz(),z8();return}P0=Z.map((Y)=>({id:Y.id||Tz(),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{P0=Dz(),z8()}}function Dz(){let $=new Date().toISOString();return[{id:Tz(),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:Tz(),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 AH($){if(jH=$,!RH($))HL($,{recursive:!0});NL()}function J8($){let Z=$.toLowerCase().trim();return P0.find((Y)=>Y.id===$)||P0.find((Y)=>Y.name.toLowerCase()===Z)||P0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function DH($){let Z=[...P0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z}function Iz($,Z){let Y=J8($);if(!Y)return null;return P0=P0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),z8(),P0.find((Q)=>Q.id===Y.id)||null}function TH($){let Z=J8($);if(!Z)return!1;return P0=P0.filter((Y)=>Y.id!==Z.id),z8(),!0}async function Sz($,Z){let Y=J8($);if(!Y){let z=P0.map((J)=>J.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${z}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await IH(Y.name,Y.steps,Z);return CL(Q)}async function IH($,Z,Y){let Q=performance.now(),z=[`Executando workflow: "${$}"`],J=0,X=0,K=0,V=!0;for(let G=0;G<Z.length;G++){let W=Z[G],H=W.label||`${W.action}:${W.target}`,U=`[${G+1}/${Z.length}]`,q=W.on_error||"continue";Y?.(`${U} ${H}...`);try{let N=await OL(W,Y);z.push(` ${U} ${N}`),J++}catch(N){let C=N instanceof Error?N.message:String(N);switch(K++,q){case"stop":return z.push(` ${U} ERRO (parando): ${C}`),V=!1,{workflow:$,success:V,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)};case"skip":z.push(` ${U} ERRO (pulado): ${C}`),X++;break;case"continue":default:z.push(` ${U} ERRO (continuando): ${C}`);break}}}return{workflow:$,success:V,stepsRun:J,stepsSkipped:X,stepsFailed:K,log:z,duration:Math.round(performance.now()-Q)}}async function OL($,Z){switch($.action){case"open_app":{if(!R)return`skip: ${$.target} (not Windows)`;return await f1($.target)}case"open_url":{if(!R)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 W1(Y)}case"run_command":{if(!R)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await B0(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(R)try{u1("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!R)return"skip: condition (not Windows)";let Y=$.target.toLowerCase(),Q=await q8(Y,{timeout:5000});if(Q&&$.condition_steps&&$.condition_steps.length>0){let z=await IH(`${$.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 SH($){let Z=$||P0;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 V=K.label||K.target;return K.action==="wait"?`${K.target}s`:V}).join(" -> ");return` ${Q.name}${z}${J} \u2014 ${Q.description}
1538
1541
  ${" ".repeat(4)}${X} {${Q.id}}`});return`Workflows (${Z.length}):
1539
1542
  ${Y.join(`
1540
1543
 
1541
- `)}`}function qW($){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 V of z.condition_steps)Q.push(` \u21B3 ${V.action}: ${V.target}`)}),Q.join(`
1542
- `)}function _F($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
1543
- `)}function Nz(){return yF().slice(0,8)}h();J2();Z0();Q1();import{existsSync as BW,mkdirSync as hF,readFileSync as gF}from"fs";import{join as mF}from"path";import{randomUUID as pF}from"crypto";var NW="",$0=[],OW=()=>mF(NW,"macros.json");function p5(){P(OW(),JSON.stringify($0,null,2))}function uF(){let $=OW();if(!BW($)){$0=Mz(),p5();return}try{let Z=JSON.parse(gF($,"utf-8"));if(!Array.isArray(Z)){$0=Mz(),p5();return}$0=Z.map((Y)=>({id:Y.id||U0(),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{$0=Mz(),p5()}}function Mz(){let $=new Date().toISOString();return[{id:U0(),name:"vscode",description:"Abrir VS Code",action:"open_app",target:"vscode",icon:"\uD83D\uDCBB",tags:["dev","editor"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"terminal",description:"Abrir Terminal Windows",action:"open_app",target:"terminal",icon:"\u2328\uFE0F",tags:["dev","terminal"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"excel",description:"Abrir Microsoft Excel",action:"open_app",target:"excel",icon:"\uD83D\uDCCA",tags:["office","planilha"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"word",description:"Abrir Microsoft Word",action:"open_app",target:"word",icon:"\uD83D\uDCDD",tags:["office","documento"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"outlook",description:"Abrir Microsoft Outlook",action:"open_app",target:"outlook",icon:"\uD83D\uDCE7",tags:["office","email"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"teams",description:"Abrir Microsoft Teams",action:"open_app",target:"teams",icon:"\uD83D\uDCAC",tags:["office","comunicacao"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"edge",description:"Abrir Microsoft Edge",action:"open_app",target:"edge",icon:"\uD83C\uDF10",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"chrome",description:"Abrir Google Chrome",action:"open_app",target:"chrome",icon:"\uD83D\uDD35",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"explorer",description:"Abrir Explorador de Arquivos",action:"open_app",target:"explorer",icon:"\uD83D\uDCC1",tags:["sistema","arquivos"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"calc",description:"Abrir Calculadora",action:"open_app",target:"calculator",icon:"\uD83D\uDD22",tags:["sistema","utilitario"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"notepad",description:"Abrir Bloco de Notas",action:"open_app",target:"notepad",icon:"\uD83D\uDCC4",tags:["editor","texto"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"tarefas",description:"Abrir Gerenciador de Tarefas",action:"open_app",target:"taskmanager",icon:"\uD83D\uDCCB",tags:["sistema","monitor"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"settings",description:"Abrir Configuracoes do Windows",action:"open_app",target:"settings",icon:"\u2699\uFE0F",tags:["sistema","config"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"github",description:"Abrir GitHub",action:"open_url",target:"https://github.com",icon:"\uD83D\uDC19",tags:["dev","web"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"claude",description:"Abrir Claude.ai",action:"open_url",target:"https://claude.ai",icon:"\uD83E\uDD16",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$},{id:U0(),name:"chatgpt",description:"Abrir ChatGPT",action:"open_url",target:"https://chat.openai.com",icon:"\uD83D\uDCAC",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$}]}function CW($){if(NW=$,!BW($))hF($,{recursive:!0});uF()}function Q8($){let Z=$.toLowerCase().trim();return $0.find((Y)=>Y.id===$)||$0.find((Y)=>Y.name.toLowerCase()===Z)||$0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function MW($){let Z=[...$0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z.filter((Y)=>Y.enabled)}function EW(){return[...$0]}function FW($,Z,Y,Q,z){let J=new Date().toISOString();$0=$0.filter((K)=>K.name.toLowerCase()!==$.toLowerCase().trim());let X={id:U0(),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 $0=[...$0,X],p5(),X}function Ez($,Z){let Y=Q8($);if(!Y)return null;return $0=$0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),p5(),$0.find((Q)=>Q.id===Y.id)||null}function LW($){let Z=Q8($);if(!Z)return!1;return $0=$0.filter((Y)=>Y.id!==Z.id),p5(),!0}async function RW($){let Z=performance.now(),Y=Q8($);if(!Y){let Q=$.toLowerCase().trim(),z=$0.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=$0.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 dF(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 dF($){switch($.action){case"open_app":{if(!R)return`skip: ${$.target} (not Windows)`;return await S1($.target,$.args)}case"open_url":{if(!R)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 V1(Z)}case"open_file":{if(!R)return`skip: ${$.target} (not Windows)`;return await g2($.target)}case"run_command":{if(!R)return"skip: command (not Windows)";let Z=$.args?`${$.target} ${$.args}`:$.target;if(!Z.trim())throw Error("Comando vazio");let Y=await q0(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 Fz($){let Z=$||$0.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(`
1544
+ `)}`}function wH($){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 V of z.condition_steps)Q.push(` \u21B3 ${V.action}: ${V.target}`)}),Q.join(`
1545
+ `)}function CL($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
1546
+ `)}function Tz(){return BL().slice(0,8)}g();K2();Y0();J1();import{existsSync as kH,mkdirSync as ML,readFileSync as EL}from"fs";import{join as FL}from"path";import{randomUUID as LL}from"crypto";var fH="",Z0=[],bH=()=>FL(fH,"macros.json");function d5(){j(bH(),JSON.stringify(Z0,null,2))}function RL(){let $=bH();if(!kH($)){Z0=wz(),d5();return}try{let Z=JSON.parse(EL($,"utf-8"));if(!Array.isArray(Z)){Z0=wz(),d5();return}Z0=Z.map((Y)=>({id:Y.id||q0(),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{Z0=wz(),d5()}}function wz(){let $=new Date().toISOString();return[{id:q0(),name:"vscode",description:"Abrir VS Code",action:"open_app",target:"vscode",icon:"\uD83D\uDCBB",tags:["dev","editor"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"terminal",description:"Abrir Terminal Windows",action:"open_app",target:"terminal",icon:"\u2328\uFE0F",tags:["dev","terminal"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"excel",description:"Abrir Microsoft Excel",action:"open_app",target:"excel",icon:"\uD83D\uDCCA",tags:["office","planilha"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"word",description:"Abrir Microsoft Word",action:"open_app",target:"word",icon:"\uD83D\uDCDD",tags:["office","documento"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"outlook",description:"Abrir Microsoft Outlook",action:"open_app",target:"outlook",icon:"\uD83D\uDCE7",tags:["office","email"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"teams",description:"Abrir Microsoft Teams",action:"open_app",target:"teams",icon:"\uD83D\uDCAC",tags:["office","comunicacao"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"edge",description:"Abrir Microsoft Edge",action:"open_app",target:"edge",icon:"\uD83C\uDF10",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"chrome",description:"Abrir Google Chrome",action:"open_app",target:"chrome",icon:"\uD83D\uDD35",tags:["browser","web"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"explorer",description:"Abrir Explorador de Arquivos",action:"open_app",target:"explorer",icon:"\uD83D\uDCC1",tags:["sistema","arquivos"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"calc",description:"Abrir Calculadora",action:"open_app",target:"calculator",icon:"\uD83D\uDD22",tags:["sistema","utilitario"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"notepad",description:"Abrir Bloco de Notas",action:"open_app",target:"notepad",icon:"\uD83D\uDCC4",tags:["editor","texto"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"tarefas",description:"Abrir Gerenciador de Tarefas",action:"open_app",target:"taskmanager",icon:"\uD83D\uDCCB",tags:["sistema","monitor"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"settings",description:"Abrir Configuracoes do Windows",action:"open_app",target:"settings",icon:"\u2699\uFE0F",tags:["sistema","config"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"github",description:"Abrir GitHub",action:"open_url",target:"https://github.com",icon:"\uD83D\uDC19",tags:["dev","web"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"claude",description:"Abrir Claude.ai",action:"open_url",target:"https://claude.ai",icon:"\uD83E\uDD16",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$},{id:q0(),name:"chatgpt",description:"Abrir ChatGPT",action:"open_url",target:"https://chat.openai.com",icon:"\uD83D\uDCAC",tags:["ia","web"],enabled:!0,createdAt:$,updatedAt:$}]}function yH($){if(fH=$,!kH($))ML($,{recursive:!0});RL()}function X8($){let Z=$.toLowerCase().trim();return Z0.find((Y)=>Y.id===$)||Z0.find((Y)=>Y.name.toLowerCase()===Z)||Z0.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function vH($){let Z=[...Z0];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((z)=>z.toLowerCase()===Y))}return Z.filter((Y)=>Y.enabled)}function xH(){return[...Z0]}function _H($,Z,Y,Q,z){let J=new Date().toISOString();Z0=Z0.filter((K)=>K.name.toLowerCase()!==$.toLowerCase().trim());let X={id:q0(),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 Z0=[...Z0,X],d5(),X}function kz($,Z){let Y=X8($);if(!Y)return null;return Z0=Z0.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),d5(),Z0.find((Q)=>Q.id===Y.id)||null}function hH($){let Z=X8($);if(!Z)return!1;return Z0=Z0.filter((Y)=>Y.id!==Z.id),d5(),!0}async function gH($){let Z=performance.now(),Y=X8($);if(!Y){let Q=$.toLowerCase().trim(),z=Z0.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=Z0.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 jL(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 jL($){switch($.action){case"open_app":{if(!R)return`skip: ${$.target} (not Windows)`;return await f1($.target,$.args)}case"open_url":{if(!R)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 W1(Z)}case"open_file":{if(!R)return`skip: ${$.target} (not Windows)`;return await p2($.target)}case"run_command":{if(!R)return"skip: command (not Windows)";let Z=$.args?`${$.target} ${$.args}`:$.target;if(!Z.trim())throw Error("Comando vazio");let Y=await B0(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 fz($){let Z=$||Z0.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(`
1544
1547
  [${X}]`);for(let K of Y[X]){let V=K.icon||"\u25B8",G=K.enabled?"":" (desativado)";z.push(` ${V} ${K.name.padEnd(12)} ${K.description}${G}`)}}if(Q.length>0){z.push(`
1545
1548
  [outros]`);for(let X of Q){let K=X.icon||"\u25B8",V=X.enabled?"":" (desativado)";z.push(` ${K} ${X.name.padEnd(12)} ${X.description}${V}`)}}return z.push(`
1546
1549
  Uso: /macro <nome> para executar`),z.join(`
1547
- `)}function jW($){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(`
1548
- `)}function U0(){return pF().slice(0,8)}s$();var PW=!1;function Lz($,Z){if(PW)return;PW=!0,tz($,E8().replace(/[/\\]config\.json$/,"")),YX($),L7($),HX($),K7($),mQ(Z),h7($),m7(),l7($),VW($),CW($),f4($),pV($),RX($),kX($),aX($),AV($),oK($),VV($),NV($),q9(),R4($,()=>{})}function AW($,Z,Y){Lz($,Y),hH((Q)=>Z.showSystem(`
1550
+ `)}function mH($){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(`
1551
+ `)}function q0(){return LL().slice(0,8)}e$();var pH=!1;function bz($,Z){if(pH)return;pH=!0,WJ($,j8().replace(/[/\\]config\.json$/,"")),BX($),b7($),RX($),E7($),lQ(Z),a7($),t7(),Lz($),QX($),AH($),yH($),_4($),eV($),yX($),dX($),VK($),_V($),zV($),FV($),TV($),C9(),T4($,()=>{})}function uH($,Z,Y){bz($,Y),aW((Q)=>Z.showSystem(`
1549
1552
  *** ${Q} ***
1550
- `)),BK($,(Q)=>{Z.showSystem(`
1553
+ `)),DK($,(Q)=>{Z.showSystem(`
1551
1554
  *** Meta-Insight: ${Q.title} ***
1552
1555
  ${Q.recommendation}
1553
- `)}),lH((Q)=>Z.showSystem(`
1556
+ `)}),QH((Q)=>Z.showSystem(`
1554
1557
  *** ${Q} ***
1555
- `)),w7($,(Q)=>Z.showSystem(`
1558
+ `)),p7($,(Q)=>Z.showSystem(`
1556
1559
  *** ${Q} ***
1557
- `)),R4($,(Q)=>{Z.showSystem(`
1560
+ `)),T4($,(Q)=>{Z.showSystem(`
1558
1561
  *** LEMBRETE: ${Q.title} ***
1559
- `)})}function DW($,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 V=cF(K.name,K.input);z.push(`> **Tool:** \`${K.name}\`${V}`);let G=K.result.split(`
1562
+ `)})}function dH($,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 V=PL(K.name,K.input);z.push(`> **Tool:** \`${K.name}\`${V}`);let G=K.result.split(`
1560
1563
  `).slice(0,5).join(`
1561
- `);if(G.trim()){z.push("> ```");for(let H of G.split(`
1562
- `))z.push(`> ${H}`);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(`
1563
- `)}function cF($,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 $5(...$){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 TW(){let $=await $5("git","diff","--cached"),Z=await $5("git","diff"),Y=await $5("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
1564
+ `);if(G.trim()){z.push("> ```");for(let W of G.split(`
1565
+ `))z.push(`> ${W}`);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(`
1566
+ `)}function PL($,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 Y5(...$){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 cH(){let $=await Y5("git","diff","--cached"),Z=await Y5("git","diff"),Y=await Y5("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
1564
1567
  `+$.stdout);if(Z.stdout)Q.push(`=== UNSTAGED ===
1565
1568
  `+Z.stdout);if(Y.stdout)Q.push(`=== UNTRACKED ===
1566
1569
  `+Y.stdout);return Q.join(`
1567
1570
 
1568
- `)||"(no changes)"}async function IW(){let $=await $5("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function wW(){return(await $5("git","add","-A")).ok}async function SW($){let Z=await $5("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function kW(){let $=await $5("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var fW={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.
1571
+ `)||"(no changes)"}async function lH(){let $=await Y5("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function oH(){return(await Y5("git","add","-A")).ok}async function iH($){let Z=await Y5("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function nH(){let $=await Y5("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var rH={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.
1569
1572
 
1570
1573
  Behavior:
1571
1574
  - Write clean, production-grade code. No shortcuts.
@@ -1596,73 +1599,74 @@ Behavior:
1596
1599
  - Be specific. Show the line, explain the problem, suggest the fix.
1597
1600
  - Check for: error handling, input validation, edge cases, naming, complexity.
1598
1601
  - Don't nitpick formatting unless it affects readability.
1599
- - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function bW($){return fW[$.toLowerCase()]||null}function yW($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(fW)){let z=Y===$?" *":" ";Z.push(`${z} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
1600
- `)}Z0();async function vW($){try{let Z=R?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:pz?["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}}h();J2();import{writeFileSync as lF}from"fs";async function xW($,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((V)=>{let G=Z.sessions.getInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:V===Z.sessions.session.name,isArchived:!1}}),X=Z.sessions.listArchived().map((V)=>{let G=Z.sessions.getArchivedInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:!1,isArchived:!0}}),K=await Z.tui.promptSessionPicker([...J,...X]);if(K)switch(K.action){case"load":{let V=K.name;if(X.some((H)=>H.name===V))Z.sessions.unarchive(V);Z.sessions.switchTo(V),Z.tui.clearMessages();for(let H of Z.sessions.messages)if(H.role==="user")Z.tui.addUserMessage(H.content);else Z.tui.addAssistantMessage(H.content);Z.tui.updateSession(V),Z.tui.showSystem(`Loaded: ${V}`);break}case"delete":{let V=K.name;if(K.isArchived?Z.sessions.deleteArchived(V):Z.sessions.delete(V))Z.tui.showSystem(`Deleted: ${V}`);else Z.tui.showError(`Not found: ${V}`);break}case"archive":if(Z.sessions.archive(K.name))Z.tui.showSystem(`Archived: ${K.name}`);else Z.tui.showError(`Failed to archive: ${K.name}`);break;case"unarchive":if(Z.sessions.unarchive(K.name))Z.tui.showSystem(`Restored: ${K.name}`);else Z.tui.showError(`Not found in archive: ${K.name}`);break}break}case"delete":case"deletar":case"rm":{let 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 V=Z.sessions.getArchivedInfo(K),G=V?oF(V.updated):"",H=V?`${V.messageCount} msgs`:"";return` ${K.padEnd(20)} ${H.padEnd(10)} ${G}`});Z.tui.showSystem(`Sessoes arquivadas (${J.length}):
1602
+ - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function aH($){return rH[$.toLowerCase()]||null}function sH($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(rH)){let z=Y===$?" *":" ";Z.push(`${z} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
1603
+ `)}Y0();async function tH($){try{let Z=R?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:ez?["pbcopy"]:["xclip","-selection","clipboard"],Y=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return Y.stdin.write($),Y.stdin.end(),await Y.exited===0}catch{return!1}}g();K2();import{writeFileSync as AL}from"fs";async function eH($,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((V)=>{let G=Z.sessions.getInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:V===Z.sessions.session.name,isArchived:!1}}),X=Z.sessions.listArchived().map((V)=>{let G=Z.sessions.getArchivedInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:!1,isArchived:!0}}),K=await Z.tui.promptSessionPicker([...J,...X]);if(K)switch(K.action){case"load":{let V=K.name;if(X.some((W)=>W.name===V))Z.sessions.unarchive(V);Z.sessions.switchTo(V),Z.tui.clearMessages();for(let W of Z.sessions.messages)if(W.role==="user")Z.tui.addUserMessage(W.content);else Z.tui.addAssistantMessage(W.content);Z.tui.updateSession(V),Z.tui.showSystem(`Loaded: ${V}`);break}case"delete":{let V=K.name;if(K.isArchived?Z.sessions.deleteArchived(V):Z.sessions.delete(V))Z.tui.showSystem(`Deleted: ${V}`);else Z.tui.showError(`Not found: ${V}`);break}case"archive":if(Z.sessions.archive(K.name))Z.tui.showSystem(`Archived: ${K.name}`);else Z.tui.showError(`Failed to archive: ${K.name}`);break;case"unarchive":if(Z.sessions.unarchive(K.name))Z.tui.showSystem(`Restored: ${K.name}`);else Z.tui.showError(`Not found in archive: ${K.name}`);break}break}case"delete":case"deletar":case"rm":{let 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 V=Z.sessions.getArchivedInfo(K),G=V?DL(V.updated):"",W=V?`${V.messageCount} msgs`:"";return` ${K.padEnd(20)} ${W.padEnd(10)} ${G}`});Z.tui.showSystem(`Sessoes arquivadas (${J.length}):
1601
1604
  ${X.join(`
1602
- `)}`);break}case"model":case"modelo":{let J=z[0];if(!J){Z.tui.showSystem(KJ(Z.config.model)+`
1605
+ `)}`);break}case"model":case"modelo":{let J=z[0];if(!J){Z.tui.showSystem(EJ(Z.config.model)+`
1603
1606
 
1604
- `+JH());break}let{provider:X,model:K}=WZ(J),V=X==="anthropic"?L8(K):K;if(Z.config.model=X==="anthropic"?V:`${X}:${V}`,M8(Z.config),X==="anthropic")Z.claude.setModel(V);else Z.tui.showSystem(`Note: ${X} provider selected. Restart smolerclaw for full provider switch.`);Z.tracker.setModel(V),Z.tui.updateModel(Z.config.model),Z.tui.showSystem(`Model -> ${Z.config.model}`);break}case"skills":case"habilidades":{Z.tui.showSystem(OH(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
1605
- 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=j2();if(K){if(Z.auth.auth=K,"updateToken"in Z.claude)Z.claude.updateToken(K.token);sH(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(tH());break}case"config":Z.tui.showSystem(`Config: ${E8()}`);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=DW(Z.sessions.session);lF(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((G)=>G.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 V=J.images?.length?J.content:J.content;await Z.handleSubmit(V);break}case"help":case"ajuda":case"?":Z.tui.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar Deletar sessao"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma"," /commit /commitar Git commit com IA"," /exit /sair Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias"," /open /abrir Abrir app Windows"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral"," /verificar /status Energia, foco e Lokaliza","","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(`
1606
- `));break;case"commit":case"commitar":{if(!await kW()){Z.tui.showError("Not a git repository.");break}let J=await IW();if(J==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
1607
+ `+CW());break}let{provider:X,model:K}=NZ(J),V=X==="anthropic"?A8(K):K;if(Z.config.model=X==="anthropic"?V:`${X}:${V}`,R8(Z.config),X==="anthropic")Z.claude.setModel(V);else Z.tui.showSystem(`Note: ${X} provider selected. Restart smolerclaw for full provider switch.`);Z.tracker.setModel(V),Z.tui.updateModel(Z.config.model),Z.tui.showSystem(`Model -> ${Z.config.model}`);break}case"skills":case"habilidades":{Z.tui.showSystem(IW(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
1608
+ 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=A2();if(K){if(Z.auth.auth=K,"updateToken"in Z.claude)Z.claude.updateToken(K.token);GH(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(WH());break}case"config":Z.tui.showSystem(`Config: ${j8()}`);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=dH(Z.sessions.session);AL(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((G)=>G.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 V=J.images?.length?J.content:J.content;await Z.handleSubmit(V);break}case"help":case"ajuda":case"?":Z.tui.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda /? Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar /rm Deletar sessao"," /fork <nome> Duplicar sessao atual"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /skills /habilidades Listar skills disponiveis"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /budget /orcamento Definir orcamento maximo (centavos)"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma (pt, en, auto)"," /ask /perguntar Pergunta one-shot (nao salva na sessao)"," /commit /commitar Git commit com IA"," /config Mostrar caminho do config"," /exit /sair /quit /q Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias (ex: /news tech)"," /feeds /fontes Listar fontes RSS (built-in + custom)"," /addfeed /novafonte Adicionar fonte RSS custom"," /rmfeed /rmfonte Remover fonte custom"," /disablefeed Desativar fonte built-in"," /enablefeed Reativar fonte"," /open /abrir Abrir app Windows (ex: /open excel)"," /openfile /abrirarquivo Abrir arquivo com app padrao"," /openurl <url> Abrir URL no navegador"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda /cal Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /contacts /contatos Listar contatos"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral de pessoas"," /verificar /status Energia, foco e Lokaliza"," /chat Modo chat com pessoa cadastrada","","Monitor:"," /monitor /vigiar Monitorar processo (ex: /monitor nginx)"," /monitor stop <nome> Parar monitoramento"," /monitor list Listar monitoramentos ativos","","Workflows:"," /workflow /fluxo Listar workflows"," /workflow run <nome> Executar (ex: /workflow iniciar-dia)"," /workflow info <n> Detalhes de um workflow"," /workflow delete <n> Remover workflow"," /workflow enable/disable <n> Ativar/desativar","","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"," /macro delete <n> Remover macro"," /macro enable/disable <n> Ativar/desativar"," /macro all Listar todos (incluindo desativados)","","Pomodoro:"," /pomodoro /foco Iniciar (ex: /foco revisar codigo)"," /pomodoro status Ver tempo restante"," /pomodoro stop Parar","","Agendador / Scheduler:"," /schedule /agendar Agendar notificacao (once/daily/weekly)"," /schedule list Listar jobs agendados"," /schedule info <id> Detalhes de um job"," /schedule run <id> Executar job agora"," /schedule delete <id> Remover job"," /schedule enable/disable <id> Ativar/desativar"," /schedules /agendamentos Listar todos os jobs","","Financas / Finance:"," /entrada /income <$> <cat> Registrar entrada"," /saida /expense <$> <cat> Registrar saida"," /finance /balanco Resumo mensal","","Auth:"," /auth Status de autenticacao"," /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 /note Salvar memo (ex: /memo senha wifi #casa)"," /memos /notas Buscar memos (ex: /memos docker, /memos #casa)"," /tags /memotags Listar tags"," /rmmemo /rmnota Remover memo","","Materiais / Materials:"," /material /mat Salvar material (ex: /mat titulo | conteudo)"," /materials /materiais Listar/buscar materiais (#tag, @categoria)"," /matcats /categorias Listar categorias"," /rmmat /rmmaterial Remover material","","Memoria RAG / Local Search:"," /index /indexar Construir/atualizar indice RAG"," /reindex Reconstruir indice do zero"," /memory /memoria Buscar na memoria local (ou ver status)","","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","","Empresas BR / Brazil OSINT (BrasilAPI + Registro.br):"," /cnpj /empresa <cnpj> Ficha publica de empresa"," /cnpj refresh <cnpj> Forca nova consulta (ignora cache)"," /cep <cep> Endereco completo por CEP"," /whois-br /dominio-br RDAP/WHOIS publico de dominios .br","","Tarefas / Tasks:"," /task /tarefa Criar tarefa (ex: /tarefa 18h buscar pao)"," /tasks /tarefas Listar pendentes (/tarefas all p/ todas)"," /done /feito Marcar como concluida"," /rmtask /rmtarefa Remover tarefa","","Projetos / Projects:"," /project /projeto Definir/ver projeto ativo"," /project auto Auto-detectar do diretorio atual"," /projects /projetos Listar todos os projetos"," /session /sessao start Iniciar timer de trabalho"," /session /sessao stop Parar timer"," /session /sessao Ver sessao ativa"," /report /relatorio Relatorio (today/week/month)"," /opportunities /oportunidades Listar oportunidades","","Vault / Backup:"," /vault status Integridade dos dados"," /vault backup Backup manual"," /vault sync Push backup para remote git"," /vault init Inicializar sistema de backup"," /backup Backup rapido","","Windows Agent (Avancado):"," /clipboard /area Ler clipboard (texto ou OCR de imagem)"," /screen /tela Analisar janelas em foco"," /ps1 <script> PowerShell inline (com safety guards)","","Integracoes / Integrations:"," /m365 Microsoft 365 (Outlook, Calendar, Teams)"," /gws Google Workspace (Gmail, Calendar, Drive)","","Meta-Learning:"," /reflect /reflexao /aprender 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(`
1609
+ `));break;case"commit":case"commitar":{if(!await nH()){Z.tui.showError("Not a git repository.");break}let J=await lH();if(J==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
1607
1610
  `+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.
1608
1611
 
1609
1612
  Diff:
1610
- ${(await TW()).slice(0,8000)}`;Z.tui.startStream();let V="";for await(let H 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(H.type==="text")V+=H.text,Z.tui.appendStream(H.text);else if(H.type==="error")Z.tui.showError(H.error);if(Z.tui.endStream(),V=V.trim().replace(/^["']|["']$/g,""),!V){Z.tui.showError("Failed to generate commit message. Aborting.");break}await wW();let G=await SW(V);if(G.ok)Z.tui.showSystem(`Committed: ${V}`);else Z.tui.showError(`Commit failed: ${G.output}`)}catch(X){Z.tui.showError(`Commit error: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput();break}case"persona":case"modo":{let J=z[0];if(!J){Z.tui.showSystem(yW(Z.currentPersona));break}let X=bW(J);if(!X){Z.tui.showError(`Unknown persona: ${J}. Try /persona to see options.`);break}if(Z.setCurrentPersona(X.name),X.systemPrompt)Z.setActiveSystemPrompt(qZ(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 vW(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(RG(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 jG(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 PG(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=AG(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(J==="installed"||J==="instalados"){let X=DG();if(X.length===0)Z.tui.showSystem("Nenhum plugin instalado do GitHub.");else{let K=["Plugins instalados do GitHub:"];for(let V of X){let G=new Date(V.installedAt).toLocaleDateString("pt-BR");K.push(` ${V.name} \u2014 github.com/${V.source} (${G})`)}Z.tui.showSystem(K.join(`
1611
- `))}}else if(J==="info"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin info <nome>");break}let K=TG(X);if(K)Z.tui.showSystem(`${K.name} v${K.version} (${K.type})
1613
+ ${(await cH()).slice(0,8000)}`;Z.tui.startStream();let V="";for await(let W 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(W.type==="text")V+=W.text,Z.tui.appendStream(W.text);else if(W.type==="error")Z.tui.showError(W.error);if(Z.tui.endStream(),V=V.trim().replace(/^["']|["']$/g,""),!V){Z.tui.showError("Failed to generate commit message. Aborting.");break}await oH();let G=await iH(V);if(G.ok)Z.tui.showSystem(`Committed: ${V}`);else Z.tui.showError(`Commit failed: ${G.output}`)}catch(X){Z.tui.showError(`Commit error: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput();break}case"persona":case"modo":{let J=z[0];if(!J){Z.tui.showSystem(sH(Z.currentPersona));break}let X=aH(J);if(!X){Z.tui.showError(`Unknown persona: ${J}. Try /persona to see options.`);break}if(Z.setCurrentPersona(X.name),X.systemPrompt)Z.setActiveSystemPrompt(CZ(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 tH(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(yG(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 vG(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 xG(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=_G(X);if(K.success)Z.tui.showSystem(K.message);else Z.tui.showError(K.message)}else if(J==="installed"||J==="instalados"){let X=hG();if(X.length===0)Z.tui.showSystem("Nenhum plugin instalado do GitHub.");else{let K=["Plugins instalados do GitHub:"];for(let V of X){let G=new Date(V.installedAt).toLocaleDateString("pt-BR");K.push(` ${V.name} \u2014 github.com/${V.source} (${G})`)}Z.tui.showSystem(K.join(`
1614
+ `))}}else if(J==="info"){let X=z[1];if(!X){Z.tui.showSystem("Uso: /plugin info <nome>");break}let K=gG(X);if(K)Z.tui.showSystem(`${K.name} v${K.version} (${K.type})
1612
1615
  ${K.description}
1613
1616
  Status: ${K.enabled?"ativo":"desabilitado"}
1614
1617
  Source: ${K.source}
1615
- Tools: ${K.tools.map((V)=>V.name).join(", ")||"nenhuma"}`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else Z.tui.showSystem(IG());break}case"budget":case"orcamento":{let J=z[0];if(!J){let K=Z.config.maxSessionCost,V=Z.tracker.totals.costCents;if(K===0)Z.tui.showSystem(`Budget: unlimited (spent ~$${(V/100).toFixed(4)})`);else{let G=Math.round(V/K*100);Z.tui.showSystem(`Budget: ~$${(V/100).toFixed(4)} / $${(K/100).toFixed(4)} (${G}%)`)}break}let X=Number(J);if(isNaN(X)||X<0){Z.tui.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Z.config.maxSessionCost=X,M8(Z.config),Z.tui.showSystem(X===0?"Budget: unlimited":`Budget set: $${(X/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!m5.peek()){Z.tui.showError("Nothing to undo.");break}let X=m5.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 V=K.content.slice(0,100).replace(/\n/g," "),G=new Date(K.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});X.push(` [${K.role} ${G}] ${V}${K.content.length>100?"...":""}`)}Z.tui.showSystem(X.length>0?`Found ${X.length} match${X.length>1?"es":""}:
1618
+ Tools: ${K.tools.map((V)=>V.name).join(", ")||"nenhuma"}`);else Z.tui.showError(`Plugin "${X}" nao encontrado.`)}else Z.tui.showSystem(mG());break}case"budget":case"orcamento":{let J=z[0];if(!J){let K=Z.config.maxSessionCost,V=Z.tracker.totals.costCents;if(K===0)Z.tui.showSystem(`Budget: unlimited (spent ~$${(V/100).toFixed(4)})`);else{let G=Math.round(V/K*100);Z.tui.showSystem(`Budget: ~$${(V/100).toFixed(4)} / $${(K/100).toFixed(4)} (${G}%)`)}break}let X=Number(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(!u5.peek()){Z.tui.showError("Nothing to undo.");break}let X=u5.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 V=K.content.slice(0,100).replace(/\n/g," "),G=new Date(K.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});X.push(` [${K.role} ${G}] ${V}${K.content.length>100?"...":""}`)}Z.tui.showSystem(X.length>0?`Found ${X.length} match${X.length>1?"es":""}:
1616
1619
  ${X.join(`
1617
- `)}`:`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,M8(Z.config),Z.tui.showSystem(`Language -> ${J}`);break}case"briefing":case"resumo":{Z.tui.showSystem("Carregando briefing..."),Z.tui.disableInput();try{let J=await vH(Z.config.dataDir);Z.tui.showSystem(J);let X=await $8(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 F4(J?[J]:void 0);if(X.length===0){Z.tui.showSystem(K.length>0?`Nenhuma noticia encontrada.
1618
- Falhas: ${K.join(", ")}`:"Nenhuma noticia encontrada."),Z.tui.enableInput();break}let V=X.map((H)=>({title:H.title,link:H.link,source:H.source,category:H.category,time:H.pubDate?H.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),G=await Z.tui.promptNewsPicker(V);if(G){if(G.action==="open"){let{openUrl:H}=await Promise.resolve().then(() => (J2(),jK));H(G.link),Z.tui.showSystem(`Abrindo: ${G.link}`)}else if(G.action==="read"){Z.tui.showSystem("Buscando conteudo...");let H=await G7(G.link);if(typeof H==="string")Z.tui.showError(H);else{let U=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
1620
+ `)}`:`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 iW(Z.config.dataDir);Z.tui.showSystem(J);let X=await Y8(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 A4(J?[J]:void 0);if(X.length===0){Z.tui.showSystem(K.length>0?`Nenhuma noticia encontrada.
1621
+ Falhas: ${K.join(", ")}`:"Nenhuma noticia encontrada."),Z.tui.enableInput();break}let V=X.map((W)=>({title:W.title,link:W.link,source:W.source,category:W.category,time:W.pubDate?W.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),G=await Z.tui.promptNewsPicker(V);if(G){if(G.action==="open"){let{openUrl:W}=await Promise.resolve().then(() => (K2(),vK));W(G.link),Z.tui.showSystem(`Abrindo: ${G.link}`)}else if(G.action==="read"){Z.tui.showSystem("Buscando conteudo...");let W=await L7(G.link);if(typeof W==="string")Z.tui.showError(W);else{let U=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
1619
1622
 
1620
- ${`Noticia: ${H.title}
1623
+ ${`Noticia: ${W.title}
1621
1624
  Fonte: ${G.link}
1622
1625
 
1623
- ${H.content}`}`;Z.tui.enableInput(),Z.handleSubmit(U);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(z6());break}case"addfeed":case"novafonte":{if(z.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
1624
- Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let J=z[0],X=z[1],K=z[2],V=p$(J,X,K);if(typeof V==="string")Z.tui.showError(V);else Z.tui.showSystem(`Fonte adicionada: ${V.name} (${V.category}) \u2014 ${V.url}`);break}case"rmfeed":case"rmfonte":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /rmfeed <nome ou url>");break}if(Z6(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(Y6(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(Q6(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: ${qY().join(", ")}
1625
- Uso: /open <app> ou /open <app> <arquivo>`);break}let X=z.length>1?z.slice(1).join(" "):void 0,K=await S1(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 g2(J);Z.tui.showSystem(X);break}case"openurl":{let J=z[0];if(!J){Z.tui.showError("Uso: /openurl <url>");break}let X=await V1(J);Z.tui.showSystem(X);break}case"apps":case"programas":{Z.tui.disableInput();try{let J=await Z3();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 m2();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 p2(),X=await G1();Z.tui.showSystem(`${J}
1626
+ ${W.content}`}`;Z.tui.enableInput(),Z.handleSubmit(U);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(V6());break}case"addfeed":case"novafonte":{if(z.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
1627
+ Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let J=z[0],X=z[1],K=z[2],V=d$(J,X,K);if(typeof V==="string")Z.tui.showError(V);else Z.tui.showSystem(`Fonte adicionada: ${V.name} (${V.category}) \u2014 ${V.url}`);break}case"rmfeed":case"rmfonte":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /rmfeed <nome ou url>");break}if(J6(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(X6(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(K6(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: ${MY().join(", ")}
1628
+ Uso: /open <app> ou /open <app> <arquivo>`);break}let X=z.length>1?z.slice(1).join(" "):void 0,K=await f1(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 p2(J);Z.tui.showSystem(X);break}case"openurl":{let J=z[0];if(!J){Z.tui.showError("Uso: /openurl <url>");break}let X=await W1(J);Z.tui.showSystem(X);break}case"apps":case"programas":{Z.tui.disableInput();try{let J=await Q3();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 u2();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 d2(),X=await H1();Z.tui.showSystem(`${J}
1626
1629
 
1627
1630
  --- Agenda ---
1628
- ${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(nH());else if(J==="stop"||J==="parar"){let X=z[1];if(!X){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(iH(X))}else{let X=parseInt(z[1])||60;Z.tui.showSystem(oH(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(UW(GW(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 Cz(X,(V)=>Z.tui.showSystem(V));Z.tui.showSystem(K)}catch(K){Z.tui.showError(`Workflow: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput()}else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow info <nome>");break}let K=Y8(X);if(K)Z.tui.showSystem(qW(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(HW(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=Oz(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=Oz(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 Cz(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(Fz(MW(X)))}else if(J==="all"||J==="todos")Z.tui.showSystem(Fz(EW()));else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro info <nome>");break}let K=Q8(X);if(K)Z.tui.showSystem(jW(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],V=z[3];if(!X||!K||!V){Z.tui.showSystem(`Uso: /macro create <nome> <acao> <target> [descricao]
1631
+ ${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(XH());else if(J==="stop"||J==="parar"){let X=z[1];if(!X){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(JH(X))}else{let X=parseInt(z[1])||60;Z.tui.showSystem(zH(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(SH(DH(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 Sz(X,(V)=>Z.tui.showSystem(V));Z.tui.showSystem(K)}catch(K){Z.tui.showError(`Workflow: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput()}else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /workflow info <nome>");break}let K=J8(X);if(K)Z.tui.showSystem(wH(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(TH(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=Iz(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=Iz(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 Sz(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(fz(vH(X)))}else if(J==="all"||J==="todos")Z.tui.showSystem(fz(xH()));else if(J==="info"||J==="detalhe"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro info <nome>");break}let K=X8(X);if(K)Z.tui.showSystem(mH(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],V=z[3];if(!X||!K||!V){Z.tui.showSystem(`Uso: /macro create <nome> <acao> <target> [descricao]
1629
1632
  Acoes: open_app, open_url, open_file, run_command
1630
1633
  Exemplos:
1631
1634
  /macro create mysite open_url https://example.com "Meu site"
1632
1635
  /macro create docs open_file C:\\Users\\Docs "Pasta de documentos"
1633
- /macro create cleanup run_command "Remove-Item $env:TEMP\\* -Force"`);break}let G=["open_app","open_url","open_file","run_command"];if(!G.includes(K)){Z.tui.showError(`Acao invalida: ${K}. Use: ${G.join(", ")}`);break}let H=z.slice(4).join(" ")||`Macro: ${X}`,W=FW(X,H,K,V);Z.tui.showSystem(`Macro criado: "${W.name}" (${W.action}: ${W.target})`)}else if(J==="delete"||J==="deletar"||J==="rm"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro delete <nome>");break}if(LW(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=Ez(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=Ez(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 RW(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(mH());else if(J==="status")Z.tui.showSystem(Wz());else if(!J)Z.tui.showSystem(Wz());else{let X=z.join(" "),K=25,V=5;Z.tui.showSystem(gH(X,25,5))}break}case"agendar":case"schedule":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let N=c$(z[1]==="all"||z[1]==="todos");Z.tui.showSystem(l$(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 N6(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 O6(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 C6(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 M6(z[1]));break}if(J==="clear"||J==="limpar"){Z.tui.showSystem(await b7());break}if(J==="detail"||J==="detalhe"||J==="info"){if(!z[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let N=S7(z[1]);Z.tui.showSystem(N?I4(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]
1636
+ /macro create cleanup run_command "Remove-Item $env:TEMP\\* -Force"`);break}let G=["open_app","open_url","open_file","run_command"];if(!G.includes(K)){Z.tui.showError(`Acao invalida: ${K}. Use: ${G.join(", ")}`);break}let W=z.slice(4).join(" ")||`Macro: ${X}`,H=_H(X,W,K,V);Z.tui.showSystem(`Macro criado: "${H.name}" (${H.action}: ${H.target})`)}else if(J==="delete"||J==="deletar"||J==="rm"){let X=z[1];if(!X){Z.tui.showError("Uso: /macro delete <nome>");break}if(hH(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=kz(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=kz(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 gH(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(tW());else if(J==="status")Z.tui.showSystem(Oz());else if(!J)Z.tui.showSystem(Oz());else{let X=z.join(" "),K=25,V=5;Z.tui.showSystem(sW(X,25,5))}break}case"agendar":case"schedule":{let J=z[0]?.toLowerCase();if(!J||J==="list"||J==="listar"){let N=o$(z[1]==="all"||z[1]==="todos");Z.tui.showSystem(i$(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 E6(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 F6(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 L6(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 R6(z[1]));break}if(J==="clear"||J==="limpar"){Z.tui.showSystem(await l7());break}if(J==="detail"||J==="detalhe"||J==="info"){if(!z[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let N=u7(z[1]);Z.tui.showSystem(N?b4(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]
1634
1637
  Exemplos:
1635
1638
  /agendar "Reuniao" "14:00"
1636
1639
  /agendar "Standup" "09:00" daily
1637
1640
  /agendar "Review" "15:00" weekly sexta
1638
- /agendar "Dentista" "10:00" once 15/04/2026`);break}let V=K[0].slice(1,-1),G=K[1].slice(1,-1),H=E6(G);if(!H){Z.tui.showSystem(`Horario invalido: "${G}". Use formato HH:MM ou HHh.`);break}let W=X.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),U="once",q;for(let N of W){let C=N.toLowerCase();if(C==="daily"||C==="diario")U="daily";else if(C==="weekly"||C==="semanal")U="weekly";else if(C==="once"||C==="uma-vez")U="once";else if(U==="weekly"){let M=L6(N);if(M)q=M}else if(U==="once"){let M=F6(N);if(M)q=M}}if(U==="once"&&!q){let N=new Date,[C,M]=H.split(":").map(Number),F=new Date(N);if(F.setHours(C,M,0,0),F<=N)F.setDate(F.getDate()+1);q=[String(F.getMonth()+1).padStart(2,"0"),String(F.getDate()).padStart(2,"0"),String(F.getFullYear())].join("/")}try{let N=await B6(V,U,H,"toast",V,q);Z.tui.showSystem(`Tarefa "${N.name}" agendada para ${I4(N).split(`
1639
- `).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=c$(z[0]==="all"||z[0]==="todos");Z.tui.showSystem(l$(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(" "),V=i$("entrada",J,X,K);if(!V.allowed){Z.tui.showError(V.blocked);break}let G=o$("entrada",J,X,K);n$("entrada",J,X);let H=r$(V);if(Z.tui.showSystem(`+ R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description}`),H)Z.tui.showSystem(H);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(" "),V=i$("saida",J,X,K);if(!V.allowed){Z.tui.showError(V.blocked);break}let G=o$("saida",J,X,K);n$("saida",J,X);let H=r$(V);if(Z.tui.showSystem(`- R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description}`),H)Z.tui.showSystem(H);break}case"finance":case"financas":case"balanco":{let J=z[0];if(J==="recent"||J==="recentes")Z.tui.showSystem(S4());else Z.tui.showSystem(j6()+`
1641
+ /agendar "Dentista" "10:00" once 15/04/2026`);break}let V=K[0].slice(1,-1),G=K[1].slice(1,-1),W=j6(G);if(!W){Z.tui.showSystem(`Horario invalido: "${G}". Use formato HH:MM ou HHh.`);break}let H=X.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),U="once",q;for(let N of H){let C=N.toLowerCase();if(C==="daily"||C==="diario")U="daily";else if(C==="weekly"||C==="semanal")U="weekly";else if(C==="once"||C==="uma-vez")U="once";else if(U==="weekly"){let M=A6(N);if(M)q=M}else if(U==="once"){let M=P6(N);if(M)q=M}}if(U==="once"&&!q){let N=new Date,[C,M]=W.split(":").map(Number),F=new Date(N);if(F.setHours(C,M,0,0),F<=N)F.setDate(F.getDate()+1);q=[String(F.getMonth()+1).padStart(2,"0"),String(F.getDate()).padStart(2,"0"),String(F.getFullYear())].join("/")}try{let N=await M6(V,U,W,"toast",V,q);Z.tui.showSystem(`Tarefa "${N.name}" agendada para ${b4(N).split(`
1642
+ `).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=o$(z[0]==="all"||z[0]==="todos");Z.tui.showSystem(i$(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(" "),V=r$("entrada",J,X,K);if(!V.allowed){Z.tui.showError(V.blocked);break}let G=n$("entrada",J,X,K);a$("entrada",J,X);let W=s$(V);if(Z.tui.showSystem(`+ R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description}`),W)Z.tui.showSystem(W);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(" "),V=r$("saida",J,X,K);if(!V.allowed){Z.tui.showError(V.blocked);break}let G=n$("saida",J,X,K);a$("saida",J,X);let W=s$(V);if(Z.tui.showSystem(`- R$ ${G.amount.toFixed(2)} (${G.category}) \u2014 ${G.description}`),W)Z.tui.showSystem(W);break}case"finance":case"financas":case"balanco":{let J=z[0];if(J==="recent"||J==="recentes")Z.tui.showSystem(v4());else Z.tui.showSystem(T6()+`
1640
1643
 
1641
- `+S4(5));break}case"decisions":case"decisoes":{let J=z.join(" ");if(J){let X=y2(J);Z.tui.showSystem(L5(X))}else Z.tui.showSystem(L5(T6()));break}case"investigar":case"investigate":case"investigacoes":{let J=z.join(" ");if(J){let{searchInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (s$(),d4));Z.tui.showSystem(K(X(J)))}else{let{listInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (s$(),d4));Z.tui.showSystem(K(X()))}break}case"email":case"rascunho":{if(!z.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
1644
+ `+v4(5));break}case"decisions":case"decisoes":{let J=z.join(" ");if(J){let X=x2(J);Z.tui.showSystem(j5(X))}else Z.tui.showSystem(j5(k6()));break}case"investigar":case"investigate":case"investigacoes":{let J=z.join(" ");if(J){let{searchInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (e$(),n4));Z.tui.showSystem(K(X(J)))}else{let{listInvestigations:X,formatInvestigationList:K}=await Promise.resolve().then(() => (e$(),n4));Z.tui.showSystem(K(X()))}break}case"cnpj":case"empresa":{let J=z[0];if(!J){Z.tui.showSystem(`Uso: /cnpj <cnpj> (ex: /cnpj 00.000.000/0001-00)
1645
+ /cnpj refresh <cnpj> forca nova consulta`);break}let X=await Promise.resolve().then(() => (Q8(),TZ)),K=J==="refresh"||J==="-r",V=K?z[1]:J;if(!V){Z.tui.showError("Informe o CNPJ. Ex: /cnpj 00.000.000/0001-00");break}if(!X.normalizeCnpj(V)){Z.tui.showError("CNPJ invalido. Use 14 digitos (com ou sem formatacao).");break}Z.tui.disableInput();try{let G=await X.lookupCnpj(V,{refresh:K});Z.tui.showSystem(X.formatCompany(G))}catch(G){let W=G instanceof Error?G.message:String(G);if(W==="not_found")Z.tui.showError("CNPJ nao encontrado na base da Receita (BrasilAPI).");else if(W==="rate_limited")Z.tui.showError("BrasilAPI limitou a taxa de consultas. Tente de novo em alguns segundos.");else if(W==="invalid_cnpj")Z.tui.showError("CNPJ invalido.");else Z.tui.showError(`Falha ao consultar CNPJ: ${W}`)}Z.tui.enableInput();break}case"cep":{let J=z[0];if(!J){Z.tui.showSystem("Uso: /cep <cep> (ex: /cep 01311-000)");break}let X=await Promise.resolve().then(() => (Q8(),TZ));if(!X.normalizeCep(J)){Z.tui.showError("CEP invalido. Use 8 digitos (com ou sem hifen).");break}Z.tui.disableInput();try{let K=await X.lookupCep(J);Z.tui.showSystem(X.formatCepInfo(K))}catch(K){let V=K instanceof Error?K.message:String(K);if(V==="not_found")Z.tui.showError("CEP nao encontrado (BrasilAPI).");else Z.tui.showError(`Falha ao consultar CEP: ${V}`)}Z.tui.enableInput();break}case"whois-br":case"dominio-br":case"dominiobr":{let J=z[0];if(!J){Z.tui.showSystem("Uso: /whois-br <dominio.br> (ex: /whois-br registro.br)");break}let X=await Promise.resolve().then(() => (Q8(),TZ)),K=X.normalizeDomain(J);if(!K){Z.tui.showError("Dominio invalido.");break}if(!X.isBrDomain(K)){Z.tui.showError("Este comando consulta apenas dominios .br (Registro.br RDAP).");break}Z.tui.disableInput();try{let V=await X.lookupDomain(K);Z.tui.showSystem(X.formatDomain(V))}catch(V){let G=V instanceof Error?V.message:String(V);if(G==="not_found")Z.tui.showError("Dominio nao encontrado no Registro.br.");else Z.tui.showError(`Falha ao consultar dominio: ${G}`)}Z.tui.enableInput();break}case"email":case"rascunho":{if(!z.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
1642
1646
  Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let X=z[0],K=z.slice(1).join(" "),V=K.indexOf("|");if(V===-1){Z.tui.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
1643
- Use | para separar assunto do corpo.`);break}let G=K.slice(0,V).trim(),H=K.slice(V+1).trim();if(!G||!H){Z.tui.showError("Assunto e corpo sao obrigatorios.");break}let W={to:X,subject:G,body:H};Z.tui.showSystem(H6(W)),Z.tui.disableInput();try{let U=await G6(W);Z.tui.showSystem(U)}catch(U){Z.tui.showError(`Email: ${U instanceof Error?U.message:String(U)}`)}Z.tui.enableInput();break}case"memo":case"anotar":case"note":{let J=z.join(" ");if(!J){let V=d$();Z.tui.showSystem(b2(V));break}let X=u$(J),K=X.tags.length>0?` [${X.tags.map((V)=>"#"+V).join(" ")}]`:"";Z.tui.showSystem(`Memo salvo${K} {${X.id}}`);break}case"memos":case"notas":{let J=z.join(" ");if(J){let X=V6(J);Z.tui.showSystem(b2(X))}else{let X=d$();Z.tui.showSystem(b2(X))}break}case"memotags":case"tags":{Z.tui.showSystem(j7());break}case"rmmemo":case"rmnota":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmemo <id>");break}if(R7(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 W=P5(10);Z.tui.showSystem($2(W));break}if(/^[a-z0-9]{6}$/.test(J)){let W=UX(J);if(W)Z.tui.showSystem(NX(W));else Z.tui.showError(`Material nao encontrado: ${J}`);break}let X=J.indexOf("|");if(X===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
1644
- Ou peca a IA: "salva esse material sobre..."`);break}let K=J.slice(0,X).trim(),V=J.slice(X+1).trim();if(!K||!V){Z.tui.showError("Titulo e conteudo sao obrigatorios.");break}let G=h6(K,V),H=G.tags.length>0?` [${G.tags.map((W)=>"#"+W).join(" ")}]`:"";Z.tui.showSystem(`Material salvo: "${G.title}" (${G.category})${H} {${G.id}}`);break}case"materials":case"materiais":{let J=z.join(" ");if(J){let X=j5(J);Z.tui.showSystem($2(X))}else{let X=P5();Z.tui.showSystem($2(X))}break}case"matcats":case"categorias":{Z.tui.showSystem(OX());break}case"rmmat":case"rmmaterial":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmat <id>");break}if(g6(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 w5();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=c9();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=l9(J);Z.tui.showSystem(o9(X))}else{let X=d9(),K=X.builtAt?new Date(X.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
1647
+ Use | para separar assunto do corpo.`);break}let G=K.slice(0,V).trim(),W=K.slice(V+1).trim();if(!G||!W){Z.tui.showError("Assunto e corpo sao obrigatorios.");break}let H={to:X,subject:G,body:W};Z.tui.showSystem(B6(H)),Z.tui.disableInput();try{let U=await q6(H);Z.tui.showSystem(U)}catch(U){Z.tui.showError(`Email: ${U instanceof Error?U.message:String(U)}`)}Z.tui.enableInput();break}case"memo":case"anotar":case"note":{let J=z.join(" ");if(!J){let V=l$();Z.tui.showSystem(v2(V));break}let X=c$(J),K=X.tags.length>0?` [${X.tags.map((V)=>"#"+V).join(" ")}]`:"";Z.tui.showSystem(`Memo salvo${K} {${X.id}}`);break}case"memos":case"notas":{let J=z.join(" ");if(J){let X=U6(J);Z.tui.showSystem(v2(X))}else{let X=l$();Z.tui.showSystem(v2(X))}break}case"memotags":case"tags":{Z.tui.showSystem(v7());break}case"rmmemo":case"rmnota":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmemo <id>");break}if(y7(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 H=D5(10);Z.tui.showSystem(Y2(H));break}if(/^[a-z0-9]{6}$/.test(J)){let H=PX(J);if(H)Z.tui.showSystem(TX(H));else Z.tui.showError(`Material nao encontrado: ${J}`);break}let X=J.indexOf("|");if(X===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
1648
+ Ou peca a IA: "salva esse material sobre..."`);break}let K=J.slice(0,X).trim(),V=J.slice(X+1).trim();if(!K||!V){Z.tui.showError("Titulo e conteudo sao obrigatorios.");break}let G=u6(K,V),W=G.tags.length>0?` [${G.tags.map((H)=>"#"+H).join(" ")}]`:"";Z.tui.showSystem(`Material salvo: "${G.title}" (${G.category})${W} {${G.id}}`);break}case"materials":case"materiais":{let J=z.join(" ");if(J){let X=A5(J);Z.tui.showSystem(Y2(X))}else{let X=D5();Z.tui.showSystem(Y2(X))}break}case"matcats":case"categorias":{Z.tui.showSystem(IX());break}case"rmmat":case"rmmaterial":{let J=z[0];if(!J){Z.tui.showError("Uso: /rmmat <id>");break}if(d6(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 k5();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=n9();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=r9(J);Z.tui.showSystem(a9(X))}else{let X=i9(),K=X.builtAt?new Date(X.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
1645
1649
  Chunks: ${X.chunks}
1646
1650
  Fontes: ${X.sources}
1647
- Ultima indexacao: ${K}`)}break}case"vault":{let J=z[0]?.toLowerCase();if(!J||J==="status")Z.tui.showSystem(N8(B8()));else if(J==="backup"){Z.tui.showSystem("Realizando backup...");let X=z.slice(1).join(" ")||void 0,K=await Q5(X);Z.tui.showSystem(K)}else if(J==="sync"||J==="push"){Z.tui.showSystem("Sincronizando com remote...");let X=await C8();Z.tui.showSystem(X)}else if(J==="init"){let X=await O8();Z.tui.showSystem(X),$J(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 Q5();Z.tui.showSystem(J);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let J=await C9();switch(J.type){case"text":Z.tui.showSystem(`Clipboard (texto):
1648
- ${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 M9();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 q3(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(`
1649
- `));break}case"projeto":case"project":{let J=z.join(" ");if(J){let X=u6(J);if(X)T5(X.id),Z.tui.showSystem(n6(X));else if(J==="auto"){let K=s6(process.cwd());if(K)T5(K.id),Z.tui.showSystem(`Projeto detectado: ${n6(K)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${J}"`)}else{let X=Y2();if(X)Z.tui.showSystem(n6(X));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(i6(D5()));break}case"sessao":case"session":{let J=z[0],X=Y2();if(!X){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(J==="start"||J==="iniciar"){let K=z.slice(1).join(" "),V=d6(X.id,K);if(V)Z.tui.showSystem(`Sessao iniciada para "${X.name}" [${V.id}]`)}else if(J==="stop"||J==="parar"){let K=Q2(X.id);if(K){let V=c6(K.id,z.slice(1).join(" "));if(V)Z.tui.showSystem(`Sessao encerrada: ${V.durationMinutes} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta.")}else{let K=Q2(X.id);if(K){let V=Math.round((Date.now()-new Date(K.startedAt).getTime())/60000);Z.tui.showSystem(`Sessao aberta: ${V} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let J=Y2();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 o6(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=l6(J);Z.tui.showSystem(r6(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=f6(X);Z.tui.showSystem(y6(K));break}case"person":case"pessoa":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /person <nome>");break}let X=A1(J);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${J}"`);break}Z.tui.showSystem(v6(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]
1650
- 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[V,...G]=K.split(","),H=G.join(",").trim()||void 0,W=k6(V.trim(),J,H);Z.tui.showSystem(`Adicionado: ${W.name} (${J}) [${W.id}]`);break}case"delegate":case"delegar":{let J=z[0];if(!J||z.length<2){Z.tui.showSystem(`Uso: /delegate <pessoa> <tarefa>
1651
- Ex: /delegate Joao revisar relatorio`);break}let X=z.slice(1).join(" "),K=b6(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=v2(J);Z.tui.showSystem(x6(X));break}case"followups":{let J=R5();Z.tui.showSystem(_6(J));break}case"verificar":case"status":{let J=[],X=l2(),K={alto:"\uD83D\uDFE2",medio:"\uD83D\uDFE1",baixo:"\uD83D\uDFE0",critico:"\uD83D\uDD34"},V={aquecimento:"Aquecimento",pico:"Pico",sustentado:"Sustentado",declinio:"Declinio",esgotado:"Esgotado"};J.push({id:"energy",title:`${K[X.level]} Energia: ${X.score}/100`,content:[`Fase: ${V[X.phase]??X.phase}`,`Sessao: ${X.sessionDurationMin} min`,`Streak: ${X.currentStreak} min sem pausa`,`Pausas: ${X.breaksTaken}`,`Interacoes: ${X.interactionCount}`,"",X.suggestion]});let G=U3(),H={desligado:"Desligado",leve:"Leve",profundo:"Profundo",nao_perturbe:"Nao Perturbe"};J.push({id:"attention",title:`Foco: ${H[G.focusMode]??G.focusMode}`,content:[`Pendentes: ${G.pending}`,`Bloqueadas hoje: ${G.blockedToday}`,`Total hoje: ${G.totalToday}`]});let W=O9();if(W.totalSessions>=3)J.push({id:"profile",title:"Perfil de Energia",content:[`Melhores horarios: ${W.bestHours.map((M)=>`${M}h`).join(", ")}`,`Sessao media: ${W.avgSessionMin} min`,`Intervalo entre pausas: ${W.avgBreakInterval} min`,`Total sessoes: ${W.totalSessions}`]});let U=t0();if(U.length>0){let M=U.reduce((T,v)=>T+v.pois.length,0),F=U.reduce((T,v)=>T+v.layers.length,0);J.push({id:"lokaliza",title:`Lokaliza (${U.length} bairros)`,content:[`POIs: ${M} | Camadas: ${F}`,...U.slice(0,5).map((T)=>`\u2022 ${T.name} \u2014 ${T.city}/${T.state}`),...U.length>5?[`... +${U.length-5} mais`]:[]]})}let q=s0(),N=s0(!0).filter((M)=>M.done);J.push({id:"tasks-summary",title:"Tarefas",content:[`Pendentes: ${q.length}`,`Concluidas hoje: ${N.filter((M)=>{return new Date(M.createdAt).toDateString()===new Date().toDateString()}).length}`]});let C={panels:J,columns:2,gap:1};Z.tui.enterDashboardMode(C),process.stdin.once("data",()=>{if(Z.tui.getViewMode()==="dashboard")Z.tui.enterChatMode()});break}case"dashboard":case"painel":{let J=await Rz(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 H=s0();Z.tui.showSystem(f2(H));break}let X=E5(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 V=X6(K,X||void 0),G=X?` \u2014 lembrete: ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";Z.tui.showSystem(`Tarefa criada: "${V.title}"${G} [${V.id}]`);break}case"tasks":case"tarefas":{let J=z[0]==="all"||z[0]==="todas",X=s0(J);Z.tui.showSystem(f2(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=K6(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(N7(J))Z.tui.showSystem("Tarefa removida.");else Z.tui.showError(`Tarefa nao encontrada: "${J}"`);break}case"m365":{await WQ(z,{showSystem:(J)=>Z.tui.showSystem(J),showError:(J)=>Z.tui.showError(J)});break}case"gws":{await wQ(z,{showSystem:(J)=>Z.tui.showSystem(J),showError:(J)=>Z.tui.showError(J),enterDashboard:(J)=>{let X={panels:J.map((K,V)=>({...K,col:V,row:0})),columns:3,gap:1};Z.tui.enterDashboardMode(X)}});break}default:Z.tui.showError(`Unknown command: /${Q}. Try /help`)}}async function Rz($){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=s0(),X=J.filter((W)=>{if(!W.dueAt)return!0;let U=new Date(W.dueAt),q=new Date;return U.toDateString()===q.toDateString()});if(X.length>0||J.length>0){let W=X.slice(0,8).map((U)=>{let q=U.dueAt?new Date(U.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${q?`[${q}] `:""}${U.title}`});if(J.length>X.length)W.push(`... +${J.length-X.length} outras`);Z.push({id:"tasks",title:`${Q}! Tarefas (${X.length})`,content:W.length>0?W:["Nenhuma tarefa para hoje"]})}let K=R5();if(K.length>0){let W=K.slice(0,6).map((U)=>{let q=U.person.name||"Alguem",N=U.interaction.summary||"Follow-up pendente";return`${q}: ${N.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${K.length})`,content:W})}let G=v2().filter((W)=>W.status==="atrasado");if(G.length>0){let W=G.slice(0,5).map((U)=>{return`${A1(U.personId)?.name||"Alguem"}: ${U.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${G.length})`,content:W})}try{let U=(await G1()).split(`
1652
- `).filter((N)=>N.trim()).slice(0,6);if(U.length===1&&(U[0].startsWith("Outlook nao disponivel")||U[0].startsWith("Outlook timeout")||U[0].startsWith("Outlook integration only")))Z.push({id:"calendar",title:"Agenda",content:[U[0]]}),l.debug("Calendar fallback in dashboard",{message:U[0]});else if(U.length>0)Z.push({id:"calendar",title:`Agenda (${U.length>1||U[0]!=="Nenhum evento hoje."?U.length:0})`,content:U})}catch(W){l.debug("Calendar unavailable for dashboard",{error:W}),Z.push({id:"calendar",title:"Agenda",content:["Erro ao acessar Outlook"]})}let H=a6();if(H){let W=H.split(`
1653
- `).filter((U)=>U.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:W})}try{let U=(await P1(["finance","business","tech"],2)).split(`
1654
- `).filter((q)=>q.trim()).slice(0,6);if(U.length>0)Z.push({id:"news",title:"Noticias",content:U})}catch(W){l.debug("News fetch failed for dashboard",{error:W})}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 oF($){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 _W($,Z,Y,Q,z,J,X,K,V,G){let H=new Vz(Y.model),W=new Kz(Y.model,Z.session.name,XJ(Q.auth),Y.dataDir),U="default",q=X;AW(Y.dataDir,W,Z);let N=null;try{N=await $8(Y.dataDir),W.setTimeContext(N)}catch(D){l.debug("Time context init failed, using productivity mode",{error:D}),W.setPersonaMode("productivity")}if(aH(Q.auth,{onRefreshed:(D)=>{if(Q.auth=D,"updateToken"in $)$.updateToken(D.token)},onRefreshFailed:(D)=>{W.showError(`Auto-refresh: ${D}`)}}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(D,x,c)=>{if(D==="edit_file"&&x.old_text&&x.new_text){let C0=zH(String(x.old_text),String(x.new_text));for(let r of C0)W.showSystem(r)}let V0=QH(D,x),g=await W.promptApproval(V0);if(W._approveAllRequested)$.setAutoApproveAll?.(!0),W._approveAllRequested=!1;return g});for(let D of Z.messages)if(D.role==="user")W.addUserMessage(D.content);else W.addAssistantMessage(D.content);let C=null;async function M(D){if(D.startsWith("/")){await xW(D,T);return}if(Y.maxSessionCost>0){let m=H.totals.costCents;if(m>=Y.maxSessionCost){W.showError(`Budget exceeded (~$${(m/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(m>=Y.maxSessionCost*0.8)W.showSystem(`Budget: ${Math.round(m/Y.maxSessionCost*100)}% used`)}let{text:x,images:c}=kH(D),{text:V0,files:g}=fH(x),C0=V0;if(g.length>0)C0=`${g.map((J8)=>`<file name="${J8.name}" path="${J8.path}" size="${J8.size}">
1655
- ${J8.content}
1651
+ Ultima indexacao: ${K}`)}break}case"vault":{let J=z[0]?.toLowerCase();if(!J||J==="status")Z.tui.showSystem(E8(M8()));else if(J==="backup"){Z.tui.showSystem("Realizando backup...");let X=z.slice(1).join(" ")||void 0,K=await J5(X);Z.tui.showSystem(K)}else if(J==="sync"||J==="push"){Z.tui.showSystem("Sincronizando com remote...");let X=await L8();Z.tui.showSystem(X)}else if(J==="init"){let X=await F8();Z.tui.showSystem(X),UJ(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 J5();Z.tui.showSystem(J);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let J=await L9();switch(J.type){case"text":Z.tui.showSystem(`Clipboard (texto):
1652
+ ${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 R9();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 N3(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(`
1653
+ `));break}case"projeto":case"project":{let J=z.join(" ");if(J){let X=o6(J);if(X)S5(X.id),Z.tui.showSystem(t6(X));else if(J==="auto"){let K=Z9(process.cwd());if(K)S5(K.id),Z.tui.showSystem(`Projeto detectado: ${t6(K)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${J}"`)}else{let X=z2();if(X)Z.tui.showSystem(t6(X));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(s6(I5()));break}case"sessao":case"session":{let J=z[0],X=z2();if(!X){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(J==="start"||J==="iniciar"){let K=z.slice(1).join(" "),V=i6(X.id,K);if(V)Z.tui.showSystem(`Sessao iniciada para "${X.name}" [${V.id}]`)}else if(J==="stop"||J==="parar"){let K=J2(X.id);if(K){let V=n6(K.id,z.slice(1).join(" "));if(V)Z.tui.showSystem(`Sessao encerrada: ${V.durationMinutes} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta.")}else{let K=J2(X.id);if(K){let V=Math.round((Date.now()-new Date(K.startedAt).getTime())/60000);Z.tui.showSystem(`Sessao aberta: ${V} minutos em "${X.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let J=z2();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 a6(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=r6(J);Z.tui.showSystem(e6(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=x6(X);Z.tui.showSystem(h6(K));break}case"person":case"pessoa":{let J=z.join(" ");if(!J){Z.tui.showError("Uso: /person <nome>");break}let X=T1(J);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${J}"`);break}Z.tui.showSystem(g6(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]
1654
+ 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[V,...G]=K.split(","),W=G.join(",").trim()||void 0,H=v6(V.trim(),J,W);Z.tui.showSystem(`Adicionado: ${H.name} (${J}) [${H.id}]`);break}case"delegate":case"delegar":{let J=z[0];if(!J||z.length<2){Z.tui.showSystem(`Uso: /delegate <pessoa> <tarefa>
1655
+ Ex: /delegate Joao revisar relatorio`);break}let X=z.slice(1).join(" "),K=_6(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=_2(J);Z.tui.showSystem(m6(X));break}case"followups":{let J=P5();Z.tui.showSystem(p6(J));break}case"verificar":case"status":{let J=[],X=i2(),K={alto:"\uD83D\uDFE2",medio:"\uD83D\uDFE1",baixo:"\uD83D\uDFE0",critico:"\uD83D\uDD34"},V={aquecimento:"Aquecimento",pico:"Pico",sustentado:"Sustentado",declinio:"Declinio",esgotado:"Esgotado"};J.push({id:"energy",title:`${K[X.level]} Energia: ${X.score}/100`,content:[`Fase: ${V[X.phase]??X.phase}`,`Sessao: ${X.sessionDurationMin} min`,`Streak: ${X.currentStreak} min sem pausa`,`Pausas: ${X.breaksTaken}`,`Interacoes: ${X.interactionCount}`,"",X.suggestion]});let G=B3(),W={desligado:"Desligado",leve:"Leve",profundo:"Profundo",nao_perturbe:"Nao Perturbe"};J.push({id:"attention",title:`Foco: ${W[G.focusMode]??G.focusMode}`,content:[`Pendentes: ${G.pending}`,`Bloqueadas hoje: ${G.blockedToday}`,`Total hoje: ${G.totalToday}`]});let H=F9();if(H.totalSessions>=3)J.push({id:"profile",title:"Perfil de Energia",content:[`Melhores horarios: ${H.bestHours.map((M)=>`${M}h`).join(", ")}`,`Sessao media: ${H.avgSessionMin} min`,`Intervalo entre pausas: ${H.avgBreakInterval} min`,`Total sessoes: ${H.totalSessions}`]});let U=Z1();if(U.length>0){let M=U.reduce((T,v)=>T+v.pois.length,0),F=U.reduce((T,v)=>T+v.layers.length,0);J.push({id:"lokaliza",title:`Lokaliza (${U.length} bairros)`,content:[`POIs: ${M} | Camadas: ${F}`,...U.slice(0,5).map((T)=>`\u2022 ${T.name} \u2014 ${T.city}/${T.state}`),...U.length>5?[`... +${U.length-5} mais`]:[]]})}let q=$1(),N=$1(!0).filter((M)=>M.done);J.push({id:"tasks-summary",title:"Tarefas",content:[`Pendentes: ${q.length}`,`Concluidas hoje: ${N.filter((M)=>{return new Date(M.createdAt).toDateString()===new Date().toDateString()}).length}`]});let C={panels:J,columns:2,gap:1};Z.tui.enterDashboardMode(C),process.stdin.once("data",()=>{if(Z.tui.getViewMode()==="dashboard")Z.tui.enterChatMode()});break}case"dashboard":case"painel":{let J=await yz(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 W=$1();Z.tui.showSystem(y2(W));break}let X=L5(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 V=W6(K,X||void 0),G=X?` \u2014 lembrete: ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";Z.tui.showSystem(`Tarefa criada: "${V.title}"${G} [${V.id}]`);break}case"tasks":case"tarefas":{let J=z[0]==="all"||z[0]==="todas",X=$1(J);Z.tui.showSystem(y2(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=H6(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(T7(J))Z.tui.showSystem("Tarefa removida.");else Z.tui.showError(`Tarefa nao encontrada: "${J}"`);break}case"m365":{await OQ(z,{showSystem:(J)=>Z.tui.showSystem(J),showError:(J)=>Z.tui.showError(J)});break}case"gws":{await yQ(z,{showSystem:(J)=>Z.tui.showSystem(J),showError:(J)=>Z.tui.showError(J),enterDashboard:(J)=>{let X={panels:J.map((K,V)=>({...K,col:V,row:0})),columns:3,gap:1};Z.tui.enterDashboardMode(X)}});break}default:Z.tui.showError(`Unknown command: /${Q}. Try /help`)}}async function yz($){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=$1(),X=J.filter((H)=>{if(!H.dueAt)return!0;let U=new Date(H.dueAt),q=new Date;return U.toDateString()===q.toDateString()});if(X.length>0||J.length>0){let H=X.slice(0,8).map((U)=>{let q=U.dueAt?new Date(U.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${q?`[${q}] `:""}${U.title}`});if(J.length>X.length)H.push(`... +${J.length-X.length} outras`);Z.push({id:"tasks",title:`${Q}! Tarefas (${X.length})`,content:H.length>0?H:["Nenhuma tarefa para hoje"]})}let K=P5();if(K.length>0){let H=K.slice(0,6).map((U)=>{let q=U.person.name||"Alguem",N=U.interaction.summary||"Follow-up pendente";return`${q}: ${N.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${K.length})`,content:H})}let G=_2().filter((H)=>H.status==="atrasado");if(G.length>0){let H=G.slice(0,5).map((U)=>{return`${T1(U.personId)?.name||"Alguem"}: ${U.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${G.length})`,content:H})}try{let U=(await H1()).split(`
1656
+ `).filter((N)=>N.trim()).slice(0,6);if(U.length===1&&(U[0].startsWith("Outlook nao disponivel")||U[0].startsWith("Outlook timeout")||U[0].startsWith("Outlook integration only")))Z.push({id:"calendar",title:"Agenda",content:[U[0]]}),o.debug("Calendar fallback in dashboard",{message:U[0]});else if(U.length>0)Z.push({id:"calendar",title:`Agenda (${U.length>1||U[0]!=="Nenhum evento hoje."?U.length:0})`,content:U})}catch(H){o.debug("Calendar unavailable for dashboard",{error:H}),Z.push({id:"calendar",title:"Agenda",content:["Erro ao acessar Outlook"]})}let W=$9();if(W){let H=W.split(`
1657
+ `).filter((U)=>U.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:H})}try{let U=(await D1(["finance","business","tech"],2)).split(`
1658
+ `).filter((q)=>q.trim()).slice(0,6);if(U.length>0)Z.push({id:"news",title:"Noticias",content:U})}catch(H){o.debug("News fetch failed for dashboard",{error:H})}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 DL($){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 $U($,Z,Y,Q,z,J,X,K,V,G){let W=new qz(Y.model),H=new Uz(Y.model,Z.session.name,MJ(Q.auth),Y.dataDir),U="default",q=X;uH(Y.dataDir,H,Z);let N=null;try{N=await Y8(Y.dataDir),H.setTimeContext(N)}catch(D){o.debug("Time context init failed, using productivity mode",{error:D}),H.setPersonaMode("productivity")}if(VH(Q.auth,{onRefreshed:(D)=>{if(Q.auth=D,"updateToken"in $)$.updateToken(D.token)},onRefreshFailed:(D)=>{H.showError(`Auto-refresh: ${D}`)}}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(D,x,l)=>{if(D==="edit_file"&&x.old_text&&x.new_text){let M0=OW(String(x.old_text),String(x.new_text));for(let a of M0)H.showSystem(a)}let G0=NW(D,x),m=await H.promptApproval(G0);if(H._approveAllRequested)$.setAutoApproveAll?.(!0),H._approveAllRequested=!1;return m});for(let D of Z.messages)if(D.role==="user")H.addUserMessage(D.content);else H.addAssistantMessage(D.content);let C=null;async function M(D){if(D.startsWith("/")){await eH(D,T);return}if(Y.maxSessionCost>0){let p=W.totals.costCents;if(p>=Y.maxSessionCost){H.showError(`Budget exceeded (~$${(p/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(p>=Y.maxSessionCost*0.8)H.showSystem(`Budget: ${Math.round(p/Y.maxSessionCost*100)}% used`)}let{text:x,images:l}=dW(D),{text:G0,files:m}=cW(x),M0=G0;if(m.length>0)M0=`${m.map((V8)=>`<file name="${V8.name}" path="${V8.path}" size="${V8.size}">
1659
+ ${V8.content}
1656
1660
  </file>`).join(`
1657
1661
 
1658
1662
  `)}
1659
1663
 
1660
- ${V0}`;let r={role:"user",content:C0,images:c.length>0?c.map((m)=>({mediaType:m.mediaType,base64:m.base64})):void 0,files:g.length>0?g:void 0,timestamp:Date.now()};Z.addMessage(r);let M0=[];if(c.length>0)M0.push(`${c.length} image${c.length>1?"s":""}`);if(g.length>0)M0.push(`${g.length} file${g.length>1?"s":""}`);let r0=M0.length>0?`${V0} (${M0.join(", ")})`:V0;W.addUserMessage(r0),W.disableInput(),W.startStream();let k0="",P0=[],jZ={},u5=0,z8=0;C=new AbortController;try{for await(let m of $.chat(Z.messages,q,K)){if(C.signal.aborted)break;switch(m.type){case"text":W.appendStream(m.text),k0+=m.text;break;case"tool_call":W.flushStream(),W.showToolCall(m.name,m.input),jZ=m.input;break;case"tool_result":W.showToolResult(m.name,m.result),P0.push({id:m.id,name:m.name,input:jZ,result:m.result}),jZ={},W.resetStreamBuffer();break;case"tool_blocked":W.showError(m.reason);break;case"usage":u5+=m.inputTokens,z8+=m.outputTokens;break;case"error":W.showError(m.error);break;case"done":break}}}catch(m){if(!C.signal.aborted)W.showError(m instanceof Error?m.message:String(m))}C=null,W.endStream();let Iz={inputTokens:u5,outputTokens:z8},iW=H.add(Iz);if(u5>0||z8>0)W.showUsage(H.formatUsage(Iz)),W.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let nW={role:"assistant",content:k0,toolCalls:P0.length>0?P0:void 0,usage:u5>0?{inputTokens:u5,outputTokens:z8,costCents:iW.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(nW),Z.trimHistory(Y.maxHistory),W.enableInput()}function F(){Z.saveLastSession(),B7(),dH(),rH(),f7(),xZ(),qz(),wG().catch(()=>{}),w5().catch(()=>{}),W.stop(),process.exit(0)}let T={tui:W,sessions:Z,claude:$,config:Y,auth:Q,skills:z,tracker:H,plugins:V,systemPrompt:J,activeSystemPrompt:q,setActiveSystemPrompt:(D)=>{q=D,T.activeSystemPrompt=D},currentPersona:U,setCurrentPersona:(D)=>{U=D,T.currentPersona=D},timeContext:N,setTimeContext:(D)=>{N=D,T.timeContext=D},handleSubmit:M,cleanup:F};process.on("SIGINT",F),process.on("SIGTERM",F),W.start({onSubmit:M,onCancel:()=>{C?.abort(),W.endStream(),W.showSystem("Cancelled."),W.enableInput()},onExit:F});let v=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(W.showSystem(`smolerclaw v${c5()} \u2014 the micro AI assistant.
1664
+ ${G0}`;let a={role:"user",content:M0,images:l.length>0?l.map((p)=>({mediaType:p.mediaType,base64:p.base64})):void 0,files:m.length>0?m:void 0,timestamp:Date.now()};Z.addMessage(a);let E0=[];if(l.length>0)E0.push(`${l.length} image${l.length>1?"s":""}`);if(m.length>0)E0.push(`${m.length} file${m.length>1?"s":""}`);let s0=E0.length>0?`${G0} (${E0.join(", ")})`:G0;H.addUserMessage(s0),H.disableInput(),H.startStream();let b0="",A0=[],SZ={},c5=0,K8=0;C=new AbortController;try{for await(let p of $.chat(Z.messages,q,K)){if(C.signal.aborted)break;switch(p.type){case"text":H.appendStream(p.text),b0+=p.text;break;case"tool_call":H.flushStream(),H.showToolCall(p.name,p.input),SZ=p.input;break;case"tool_result":H.showToolResult(p.name,p.result),A0.push({id:p.id,name:p.name,input:SZ,result:p.result}),SZ={},H.resetStreamBuffer();break;case"tool_blocked":H.showError(p.reason);break;case"usage":c5+=p.inputTokens,K8+=p.outputTokens;break;case"error":H.showError(p.error);break;case"done":break}}}catch(p){if(!C.signal.aborted)H.showError(p instanceof Error?p.message:String(p))}C=null,H.endStream();let mz={inputTokens:c5,outputTokens:K8},WU=W.add(mz);if(c5>0||K8>0)H.showUsage(W.formatUsage(mz)),H.updateSessionCost(`~$${(W.totals.costCents/100).toFixed(4)}`);let HU={role:"assistant",content:b0,toolCalls:A0.length>0?A0:void 0,usage:c5>0?{inputTokens:c5,outputTokens:K8,costCents:WU.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(HU),Z.trimHistory(Y.maxHistory),H.enableInput()}function F(){Z.saveLastSession(),D7(),ZH(),KH(),c7(),pZ(),Mz(),pG().catch(()=>{}),k5().catch(()=>{}),H.stop(),process.exit(0)}let T={tui:H,sessions:Z,claude:$,config:Y,auth:Q,skills:z,tracker:W,plugins:V,systemPrompt:J,activeSystemPrompt:q,setActiveSystemPrompt:(D)=>{q=D,T.activeSystemPrompt=D},currentPersona:U,setCurrentPersona:(D)=>{U=D,T.currentPersona=D},timeContext:N,setTimeContext:(D)=>{N=D,T.timeContext=D},handleSubmit:M,cleanup:F};process.on("SIGINT",F),process.on("SIGTERM",F),H.start({onSubmit:M,onCancel:()=>{C?.abort(),H.endStream(),H.showSystem("Cancelled."),H.enableInput()},onExit:F});let v=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(H.showSystem(`smolerclaw v${o5()} \u2014 the micro AI assistant.
1661
1665
  Criado por Aldeia Viva - Impactando Vida (aldeia-viva.com.br)
1662
1666
  ${v}
1663
- Type /ajuda for commands.`),YW(Y.dataDir))try{let D=await Rz(Y.dataDir);if(D.panels.length>0){W.enterDashboardMode(D);let x=()=>{W.enterChatMode(),W.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",x)};setTimeout(()=>{if(W.getViewMode()==="dashboard")W.enterChatMode()},30000),process.stdin.once("data",()=>{if(W.getViewMode()==="dashboard")W.enterChatMode()})}else{let x=await zW();W.showSystem(x)}QW()}catch(D){l.debug("Morning briefing failed at startup",{error:D})}if(G)await M(G)}import{exec as GL}from"child_process";import{stat as sF}from"fs/promises";import{join as tF}from"path";var hW=/^\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 jz=($,Z=nF)=>{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 iF={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"},nF=iF;var gW=(...$)=>{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 mW={br:".br",zstd:".zst",gzip:".gz"},rF=Object.keys(mW),aF="index.html",pW=($)=>{let Z=$.root??"./",Y=$.path,Q=$.join??gW;return async(z,J)=>{if(z.finalized)return J();let X;if($.path)X=$.path;else try{if(X=CY(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,aF);let V=$.getContent,G=await V(K,z);if(G instanceof Response)return z.newResponse(G.body,G);if(G){let H=$.mimes&&jz(K,$.mimes)||jz(K);if(z.header("Content-Type",H||"application/octet-stream"),$.precompressed&&(!H||hW.test(H))){let W=new Set(z.req.header("Accept-Encoding")?.split(",").map((U)=>U.trim()));for(let U of rF){if(!W.has(U))continue;let q=await V(K+mW[U],z);if(q){G=q,z.header("Content-Encoding",U),z.header("Vary","Accept-Encoding",{append:!0});break}}}return await $.onFound?.(K,z),z.body(G)}await $.onNotFound?.(K,z),await J();return}};var Pz=($)=>{return async function(Y,Q){return pW({...$,getContent:async(X)=>{let K=Bun.file(X);return await K.exists()?K:null},join:tF,isDir:async(X)=>{let K;try{K=(await sF(X)).isDirectory()}catch{}return K}})(Y,Q)}};var Az="x-hono-disable-ssg",mg=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Az]:"true"}})}catch{return null}})();var{write:Lm}=Bun;var ZL=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 uW=($)=>{return(...Z)=>{if(typeof Z[0]==="function"){let[Y,Q]=Z;return async function(J,X){let K=await Y(J),V=await $(J,K,Q);if(V)return V;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 RZ=($)=>("server"in $.env)?$.env.server:$.env;var YL=uW(($,Z)=>{let Y=RZ($);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});function QL(){let{process:$,Deno:Z}=globalThis;return!(typeof Z?.noColor==="boolean"?Z.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}async function dW(){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}})():!QL())}var zL=($)=>{let[Z,Y]=[",","."];return $.map((z)=>z.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Z)).join(Y)},JL=($)=>{let Z=Date.now()-$;return zL([Z<1000?Z+"ms":Math.round(Z/1000)+"s"])},XL=async($)=>{if(await dW())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 cW($,Z,Y,Q,z=0,J){let X=Z==="<--"?`${Z} ${Y} ${Q}`:`${Z} ${Y} ${Q} ${await XL(z)} ${J}`;$(X)}var lW=($=console.log)=>{return async function(Y,Q){let{method:z,url:J}=Y.req,X=J.slice(J.indexOf("/",8));await cW($,"<--",z,X);let K=Date.now();await Q(),await cW($,"-->",z,X,Y.res.status,JL(K))}};z1();class Dz{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),z0.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 V=z.find((H)=>H.id===K.id);if(V)V.result=K.result,V.status="complete";yield{type:"tool_result",messageId:Z,data:{id:K.id,name:K.name,result:K.result}};break;case"tool_blocked":let G=z.find((H)=>H.id===K.id);if(G)G.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 H={role:"assistant",content:Q,toolCalls:z.map((W)=>({id:W.id,name:W.name,input:W.input,result:W.result||""})),usage:{inputTokens:J,outputTokens:X,costCents:this.calculateCost(J,X)},timestamp:Date.now()};if(this.messages.push(H),this.currentSessionName)this.sessionManager.addMessageTo(this.currentSessionName,H);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 KL={theme:"system",fontSize:"medium",showToolCalls:!0,showCosts:!0,autoScroll:!0,enableSounds:!1};function Tz($){let Z=new K3,Y=new Map;Z.use("*",lW()),Z.use("*",W9()),Z.use("/static/*",Pz({root:"./src/ui/web"})),Z.get("/",(K)=>{return K.html(VL(NG()))}),Z.get("/map",(K)=>K.html(V3())),Z.get("/api/health",(K)=>K.json({status:"ok"})),Z.get("/api/neighborhoods",(K)=>{return K.json(t0())}),Z.get("/api/neighborhoods/:id",(K)=>{let V=k1(K.req.param("id"));if(!V)return K.json({error:"Not found"},404);return K.json(V)}),Z.get("/api/neighborhoods/:id/geojson",(K)=>{let V=k1(K.req.param("id"));if(!V)return K.json({error:"Not found"},404);return K.json(H3(V))}),Z.get("/api/neighborhoods/all/geojson",(K)=>{return K.json(U9())});function Q(K,V){let G=new Dz({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,onApprovalRequired:async(q,N,C)=>{return J(K,{type:"tool_approval_required",payload:{toolCallId:`tool_${Date.now()}`,name:q,input:N,riskLevel:C}}),!0}}),H={chatService:G,settings:{...KL}};Y.set(V,H);let W=$.sessionManager.getCurrentName(),U=G.resumeSession(W)||G.newSession();return J(K,{type:"connected",payload:{sessionId:U.id}}),X(K,G,H.settings),H}async function z(K,V,G,H){switch(H.type){case"chat":{let W=`msg_${Date.now()}`;J(K,{type:"message_start",payload:{messageId:W}});for await(let U of V.chat(H.payload))switch(U.type){case"text":J(K,{type:"text_delta",payload:{messageId:W,text:U.data}});break;case"tool_call":let q=U.data;J(K,{type:"tool_call",payload:{messageId:W,id:q.id,name:q.name,input:q.input,status:"running"}});break;case"tool_result":let N=U.data;J(K,{type:"tool_result",payload:{messageId:W,toolCallId:N.id,result:N.result}});break;case"tool_blocked":let C=U.data;J(K,{type:"tool_blocked",payload:{messageId:W,toolCallId:C.id,reason:C.reason}});break;case"usage":let M=U.data;J(K,{type:"usage",payload:{messageId:W,...M}});break;case"done":J(K,{type:"message_complete",payload:{messageId:W}});break;case"error":J(K,{type:"error",payload:{error:U.data}});break}break}case"new_session":{let W=V.newSession(H.payload?.name);J(K,{type:"connected",payload:{sessionId:W.id}}),X(K,V,G);break}case"load_session":{V.loadSession(H.payload.sessionId),X(K,V,G);break}case"delete_session":{V.deleteSessionById(H.payload.sessionId),J(K,{type:"sessions_updated",payload:V.getSessions()});break}case"update_settings":{Object.assign(G,H.payload),X(K,V,G);break}}}function J(K,V){K.send(JSON.stringify(V))}function X(K,V,G){let H=V.getSessions(),W=H.find((N)=>N.isActive)||null,U=V.getMessages(),q={currentSession:W,sessions:H,messages:U,isStreaming:!1,model:"claude-sonnet-4-20250514",systemPrompt:$.systemPrompt,totalCostCents:U.reduce((N,C)=>N+(C.usage?.costCents||0),0),settings:G};J(K,{type:"state",payload:q})}return{app:Z,start:()=>{console.log(`
1664
- ${w("ui.running_at",{url:`http://localhost:${$.port}`})}
1665
- `);let K=new Map;return Bun.serve({port:$.port,fetch(V,G){if(V.headers.get("upgrade")==="websocket"){if(G.upgrade(V))return;return new Response("WebSocket upgrade failed",{status:400})}return Z.fetch(V,G)},websocket:{open(V){let G=`client_${Date.now()}_${Math.random().toString(36).slice(2)}`,H=Q(V,G);K.set(V,{clientId:G,client:H})},async message(V,G){let H=K.get(V);if(!H)return;try{let W=JSON.parse(G.toString());await z(V,H.client.chatService,H.client.settings,W)}catch(W){J(V,{type:"error",payload:{error:W instanceof Error?W.message:"Unknown error"}})}},close(V){let G=K.get(V);if(G)Y.delete(G.clientId),K.delete(V)}}})}}}function VL($){let Z=(Y)=>$[Y]||Y;return`<!DOCTYPE html>
1667
+ Type /ajuda for commands.`),BH(Y.dataDir))try{let D=await yz(Y.dataDir);if(D.panels.length>0){H.enterDashboardMode(D);let x=()=>{H.enterChatMode(),H.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",x)};setTimeout(()=>{if(H.getViewMode()==="dashboard")H.enterChatMode()},30000),process.stdin.once("data",()=>{if(H.getViewMode()==="dashboard")H.enterChatMode()})}else{let x=await OH();H.showSystem(x)}NH()}catch(D){o.debug("Morning briefing failed at startup",{error:D})}if(G)await M(G)}import{exec as dL}from"child_process";import{stat as kL}from"fs/promises";import{join as fL}from"path";var ZU=/^\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 vz=($,Z=IL)=>{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 TL={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"},IL=TL;var YU=(...$)=>{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 QU={br:".br",zstd:".zst",gzip:".gz"},SL=Object.keys(QU),wL="index.html",zU=($)=>{let Z=$.root??"./",Y=$.path,Q=$.join??YU;return async(z,J)=>{if(z.finalized)return J();let X;if($.path)X=$.path;else try{if(X=RY(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,wL);let V=$.getContent,G=await V(K,z);if(G instanceof Response)return z.newResponse(G.body,G);if(G){let W=$.mimes&&vz(K,$.mimes)||vz(K);if(z.header("Content-Type",W||"application/octet-stream"),$.precompressed&&(!W||ZU.test(W))){let H=new Set(z.req.header("Accept-Encoding")?.split(",").map((U)=>U.trim()));for(let U of SL){if(!H.has(U))continue;let q=await V(K+QU[U],z);if(q){G=q,z.header("Content-Encoding",U),z.header("Vary","Accept-Encoding",{append:!0});break}}}return await $.onFound?.(K,z),z.body(G)}await $.onNotFound?.(K,z),await J();return}};var xz=($)=>{return async function(Y,Q){return zU({...$,getContent:async(X)=>{let K=Bun.file(X);return await K.exists()?K:null},join:fL,isDir:async(X)=>{let K;try{K=(await kL(X)).isDirectory()}catch{}return K}})(Y,Q)}};var _z="x-hono-disable-ssg",Pm=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[_z]:"true"}})}catch{return null}})();var{write:Jp}=Bun;var vL=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 JU=($)=>{return(...Z)=>{if(typeof Z[0]==="function"){let[Y,Q]=Z;return async function(J,X){let K=await Y(J),V=await $(J,K,Q);if(V)return V;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 IZ=($)=>("server"in $.env)?$.env.server:$.env;var xL=JU(($,Z)=>{let Y=IZ($);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});function _L(){let{process:$,Deno:Z}=globalThis;return!(typeof Z?.noColor==="boolean"?Z.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}async function XU(){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}})():!_L())}var hL=($)=>{let[Z,Y]=[",","."];return $.map((z)=>z.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Z)).join(Y)},gL=($)=>{let Z=Date.now()-$;return hL([Z<1000?Z+"ms":Math.round(Z/1000)+"s"])},mL=async($)=>{if(await XU())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 KU($,Z,Y,Q,z=0,J){let X=Z==="<--"?`${Z} ${Y} ${Q}`:`${Z} ${Y} ${Q} ${await mL(z)} ${J}`;$(X)}var VU=($=console.log)=>{return async function(Y,Q){let{method:z,url:J}=Y.req,X=J.slice(J.indexOf("/",8));await KU($,"<--",z,X);let K=Date.now();await Q(),await KU($,"-->",z,X,Y.res.status,gL(K))}};X1();class hz{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),J0.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 V=z.find((W)=>W.id===K.id);if(V)V.result=K.result,V.status="complete";yield{type:"tool_result",messageId:Z,data:{id:K.id,name:K.name,result:K.result}};break;case"tool_blocked":let G=z.find((W)=>W.id===K.id);if(G)G.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 W={role:"assistant",content:Q,toolCalls:z.map((H)=>({id:H.id,name:H.name,input:H.input,result:H.result||""})),usage:{inputTokens:J,outputTokens:X,costCents:this.calculateCost(J,X)},timestamp:Date.now()};if(this.messages.push(W),this.currentSessionName)this.sessionManager.addMessageTo(this.currentSessionName,W);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 pL={theme:"system",fontSize:"medium",showToolCalls:!0,showCosts:!0,autoScroll:!0,enableSounds:!1};function gz($){let Z=new G3,Y=new Map;Z.use("*",VU()),Z.use("*",N9()),Z.use("/static/*",xz({root:"./src/ui/web"})),Z.get("/",(K)=>{return K.html(uL(TG()))}),Z.get("/map",(K)=>K.html(W3())),Z.get("/api/health",(K)=>K.json({status:"ok"})),Z.get("/api/neighborhoods",(K)=>{return K.json(Z1())}),Z.get("/api/neighborhoods/:id",(K)=>{let V=b1(K.req.param("id"));if(!V)return K.json({error:"Not found"},404);return K.json(V)}),Z.get("/api/neighborhoods/:id/geojson",(K)=>{let V=b1(K.req.param("id"));if(!V)return K.json({error:"Not found"},404);return K.json(U3(V))}),Z.get("/api/neighborhoods/all/geojson",(K)=>{return K.json(O9())});function Q(K,V){let G=new hz({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,onApprovalRequired:async(q,N,C)=>{return J(K,{type:"tool_approval_required",payload:{toolCallId:`tool_${Date.now()}`,name:q,input:N,riskLevel:C}}),!0}}),W={chatService:G,settings:{...pL}};Y.set(V,W);let H=$.sessionManager.getCurrentName(),U=G.resumeSession(H)||G.newSession();return J(K,{type:"connected",payload:{sessionId:U.id}}),X(K,G,W.settings),W}async function z(K,V,G,W){switch(W.type){case"chat":{let H=`msg_${Date.now()}`;J(K,{type:"message_start",payload:{messageId:H}});for await(let U of V.chat(W.payload))switch(U.type){case"text":J(K,{type:"text_delta",payload:{messageId:H,text:U.data}});break;case"tool_call":let q=U.data;J(K,{type:"tool_call",payload:{messageId:H,id:q.id,name:q.name,input:q.input,status:"running"}});break;case"tool_result":let N=U.data;J(K,{type:"tool_result",payload:{messageId:H,toolCallId:N.id,result:N.result}});break;case"tool_blocked":let C=U.data;J(K,{type:"tool_blocked",payload:{messageId:H,toolCallId:C.id,reason:C.reason}});break;case"usage":let M=U.data;J(K,{type:"usage",payload:{messageId:H,...M}});break;case"done":J(K,{type:"message_complete",payload:{messageId:H}});break;case"error":J(K,{type:"error",payload:{error:U.data}});break}break}case"new_session":{let H=V.newSession(W.payload?.name);J(K,{type:"connected",payload:{sessionId:H.id}}),X(K,V,G);break}case"load_session":{V.loadSession(W.payload.sessionId),X(K,V,G);break}case"delete_session":{V.deleteSessionById(W.payload.sessionId),J(K,{type:"sessions_updated",payload:V.getSessions()});break}case"update_settings":{Object.assign(G,W.payload),X(K,V,G);break}}}function J(K,V){K.send(JSON.stringify(V))}function X(K,V,G){let W=V.getSessions(),H=W.find((N)=>N.isActive)||null,U=V.getMessages(),q={currentSession:H,sessions:W,messages:U,isStreaming:!1,model:"claude-sonnet-4-20250514",systemPrompt:$.systemPrompt,totalCostCents:U.reduce((N,C)=>N+(C.usage?.costCents||0),0),settings:G};J(K,{type:"state",payload:q})}return{app:Z,start:()=>{console.log(`
1668
+ ${S("ui.running_at",{url:`http://localhost:${$.port}`})}
1669
+ `);let K=new Map;return Bun.serve({port:$.port,fetch(V,G){if(V.headers.get("upgrade")==="websocket"){if(G.upgrade(V))return;return new Response("WebSocket upgrade failed",{status:400})}return Z.fetch(V,G)},websocket:{open(V){let G=`client_${Date.now()}_${Math.random().toString(36).slice(2)}`,W=Q(V,G);K.set(V,{clientId:G,client:W})},async message(V,G){let W=K.get(V);if(!W)return;try{let H=JSON.parse(G.toString());await z(V,W.client.chatService,W.client.settings,H)}catch(H){J(V,{type:"error",payload:{error:H instanceof Error?H.message:"Unknown error"}})}},close(V){let G=K.get(V);if(G)Y.delete(G.clientId),K.delete(V)}}})}}}function uL($){let Z=(Y)=>$[Y]||Y;return`<!DOCTYPE html>
1666
1670
  <html lang="en">
1667
1671
  <head>
1668
1672
  <meta charset="UTF-8">
@@ -2773,6 +2777,6 @@ Type /ajuda for commands.`),YW(Y.dataDir))try{let D=await Rz(Y.dataDir);if(D.pan
2773
2777
  document.getElementById('input').addEventListener('input', updateSendButton);
2774
2778
  </script>
2775
2779
  </body>
2776
- </html>`}function HL($){let Z=process.platform==="win32"?`start "" "${$}"`:process.platform==="darwin"?`open "${$}"`:`xdg-open "${$}"`;GL(Z,(Y)=>{if(Y)console.error(`Failed to open browser: ${$}`,Y.message)})}async function oW($){let Z=$.port||3847;console.log(`
2777
- ${w("ui.starting_web")}
2778
- `),Tz({port:Z,provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager}).start();let Q=`http://localhost:${Z}`;HL(Q),await new Promise(()=>{})}async function WL(){let $=wz(process.argv.slice(2));if($.help)Sz(),process.exit(0);if($.version)console.log(`smolerclaw v${c5()}`),process.exit(0);let Z=QJ();if(BG(Z.language),$.model)Z.model=L8($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=gZ()}catch(U){console.error("smolerclaw:",U instanceof Error?U.message:U),process.exit(1)}let Q={auth:Y},z=XH(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:J,skills:X,systemPrompt:K,activeSystemPrompt:V,enableTools:G,plugins:H}=await CH(Z,$.session,$.noTools);if(Lz(Z.dataDir,J),$.uiMode==="web"){await oW({provider:z,systemPrompt:K,enableTools:G,sessionManager:J,port:$.port});return}let W=!process.stdin.isTTY;if($.print||W)await MH(z,J,K,G,$.prompt,W),process.exit(0);await _W(z,J,Z,Q,X,K,V,G,H,$.prompt)}WL().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
2780
+ </html>`}function cL($){let Z=process.platform==="win32"?`start "" "${$}"`:process.platform==="darwin"?`open "${$}"`:`xdg-open "${$}"`;dL(Z,(Y)=>{if(Y)console.error(`Failed to open browser: ${$}`,Y.message)})}async function GU($){let Z=$.port||3847;console.log(`
2781
+ ${S("ui.starting_web")}
2782
+ `),gz({port:Z,provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager}).start();let Q=`http://localhost:${Z}`;cL(Q),await new Promise(()=>{})}async function lL(){let $=pz(process.argv.slice(2));if($.help)uz(),process.exit(0);if($.version)console.log(`smolerclaw v${o5()}`),process.exit(0);let Z=NJ();if(DG(Z.language),$.model)Z.model=A8($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=cZ()}catch(U){console.error("smolerclaw:",U instanceof Error?U.message:U),process.exit(1)}let Q={auth:Y},z=MW(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:J,skills:X,systemPrompt:K,activeSystemPrompt:V,enableTools:G,plugins:W}=await SW(Z,$.session,$.noTools);if(bz(Z.dataDir,J),$.uiMode==="web"){await GU({provider:z,systemPrompt:K,enableTools:G,sessionManager:J,port:$.port});return}let H=!process.stdin.isTTY;if($.print||H)await wW(z,J,K,G,$.prompt,H),process.exit(0);await $U(z,J,Z,Q,X,K,V,G,W,$.prompt)}lL().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});