smolerclaw 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +517 -378
- package/package.json +6 -1
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`:`[${
|
|
5
|
-
`;try{
|
|
6
|
-
${$}`;try{
|
|
7
|
-
... (truncated, ${
|
|
8
|
-
--- Arquivos ---`);for(let
|
|
9
|
-
`)}async function
|
|
10
|
-
`);if(
|
|
11
|
-
...(truncated, ${
|
|
12
|
-
... (truncado)`:X.content;
|
|
13
|
-
`)}function
|
|
14
|
-
${
|
|
15
|
-
`)}`}function
|
|
16
|
-
Evidencias: ${$.evidence.length}`);for(let
|
|
17
|
-
Conclusoes: ${$.findings.length}`);for(let
|
|
18
|
-
Resumo: ${$.summary}`);if($.recommendations)
|
|
19
|
-
`)}function
|
|
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)}
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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(`
|
|
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}):
|
|
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(`
|
|
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(`
|
|
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)+`
|
|
20
20
|
... (truncado)`:$.content].join(`
|
|
21
|
-
`)}function
|
|
22
|
-
`)}async function
|
|
23
|
-
`);try{let
|
|
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(`
|
|
24
24
|
try {
|
|
25
25
|
Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction Stop
|
|
26
26
|
|
|
@@ -88,7 +88,8 @@ try {
|
|
|
88
88
|
Write-Error $_.Exception.Message
|
|
89
89
|
exit 1
|
|
90
90
|
}
|
|
91
|
-
`,{timeout:30000,sta:!0});if(
|
|
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
|
|
92
93
|
|
|
93
94
|
Usage:
|
|
94
95
|
smolerclaw [command] [options] [prompt]
|
|
@@ -123,16 +124,16 @@ Commands (inside TUI):
|
|
|
123
124
|
/briefing Daily briefing /news News radar
|
|
124
125
|
/task Create task /tasks List tasks
|
|
125
126
|
/open Open Windows app /calendar Outlook calendar
|
|
126
|
-
/export Export markdown /exit Quit`)}function
|
|
127
|
-
`)}function L($,
|
|
128
|
-
`)}}
|
|
129
|
-
`,"\r"]);
|
|
130
|
-
`);
|
|
131
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],
|
|
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:
|
|
132
133
|
${J.map((U)=>U.error).join(`
|
|
133
134
|
`)}
|
|
134
135
|
${X}
|
|
135
|
-
${W}`)}return X},r=iH(fZ);class S$ extends n{list($={},z){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/files",d0,{query:Y,...z,headers:D([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},z?.headers])})}delete($,z={},Z){let{betas:Y}=z??{};return this._client.delete(r`/v1/files/${$}`,{...Z,headers:D([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}download($,z={},Z){let{betas:Y}=z??{};return this._client.get(r`/v1/files/${$}/content`,{...Z,headers:D([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}retrieveMetadata($,z={},Z){let{betas:Y}=z??{};return this._client.get(r`/v1/files/${$}`,{...Z,headers:D([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}upload($,z){let{betas:Z,...Y}=$;return this._client.post("/v1/files",k2({body:Y,...z,headers:D([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},SZ(Y.file),z?.headers])},this._client))}}class k$ extends n{retrieve($,z={},Z){let{betas:Y}=z??{};return this._client.get(r`/v1/models/${$}?beta=true`,{...Z,headers:D([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}list($={},z){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/models?beta=true",d0,{query:Y,...z,headers:D([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},z?.headers])})}}var T4={"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 bZ($){return $?.output_format??$?.output_config?.format}function x7($,z,Z){let Y=bZ(z);if(!z||!("parse"in(Y??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text"){let J=Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(J,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Q}),parsed_output:null};return v7($,z,Z)}function v7($,z,Z){let Y=null,Q=$.content.map((J)=>{if(J.type==="text"){let X=aH(z,J.text);if(Y===null)Y=X;let K=Object.defineProperty({...J},"parsed_output",{value:X,enumerable:!1});return Object.defineProperty(K,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),X},enumerable:!1})}return J});return{...$,content:Q,parsed_output:Y}}function aH($,z){let Z=bZ($);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse(z);return JSON.parse(z)}catch(Y){throw new j(`Failed to parse structured output: ${Y}`)}}var sH=($)=>{let z=0,Z=[];while(z<$.length){let Y=$[z];if(Y==="\\"){z++;continue}if(Y==="{"){Z.push({type:"brace",value:"{"}),z++;continue}if(Y==="}"){Z.push({type:"brace",value:"}"}),z++;continue}if(Y==="["){Z.push({type:"paren",value:"["}),z++;continue}if(Y==="]"){Z.push({type:"paren",value:"]"}),z++;continue}if(Y===":"){Z.push({type:"separator",value:":"}),z++;continue}if(Y===","){Z.push({type:"delimiter",value:","}),z++;continue}if(Y==='"'){let K="",V=!1;Y=$[++z];while(Y!=='"'){if(z===$.length){V=!0;break}if(Y==="\\"){if(z++,z===$.length){V=!0;break}K+=Y+$[z],Y=$[++z]}else K+=Y,Y=$[++z]}if(Y=$[++z],!V)Z.push({type:"string",value:K});continue}if(Y&&/\s/.test(Y)){z++;continue}let J=/[0-9]/;if(Y&&J.test(Y)||Y==="-"||Y==="."){let K="";if(Y==="-")K+=Y,Y=$[++z];while(Y&&J.test(Y)||Y===".")K+=Y,Y=$[++z];Z.push({type:"number",value:K});continue}let X=/[a-z]/i;if(Y&&X.test(Y)){let K="";while(Y&&X.test(Y)){if(z===$.length)break;K+=Y,Y=$[++z]}if(K=="true"||K=="false"||K==="null")Z.push({type:"name",value:K});else{z++;continue}continue}z++}return Z},f2=($)=>{if($.length===0)return $;let z=$[$.length-1];switch(z.type){case"separator":return $=$.slice(0,$.length-1),f2($);break;case"number":let Z=z.value[z.value.length-1];if(Z==="."||Z==="-")return $=$.slice(0,$.length-1),f2($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),f2($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),f2($);break;case"delimiter":return $=$.slice(0,$.length-1),f2($);break}return $},tH=($)=>{let z=[];if($.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")z.push("}");else z.splice(z.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")z.push("]");else z.splice(z.lastIndexOf("]"),1)}),z.length>0)z.reverse().map((Z)=>{if(Z==="}")$.push({type:"brace",value:"}"});else if(Z==="]")$.push({type:"paren",value:"]"})});return $},eH=($)=>{let z="";return $.map((Z)=>{switch(Z.type){case"string":z+='"'+Z.value+'"';break;default:z+=Z.value;break}}),z},D4=($)=>JSON.parse(eH(tH(f2(sH($)))));var v0,S1,b2,f$,I4,b$,y$,w4,x$,K1,v$,S4,k4,z2,f4,b4,_$,_7,yZ,y4,h7,g7,m7,xZ,vZ="__json_buf";function _Z($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class h${constructor($,z){v0.add(this),this.messages=[],this.receivedMessages=[],S1.set(this,void 0),b2.set(this,null),this.controller=new AbortController,f$.set(this,void 0),I4.set(this,()=>{}),b$.set(this,()=>{}),y$.set(this,void 0),w4.set(this,()=>{}),x$.set(this,()=>{}),K1.set(this,{}),v$.set(this,!1),S4.set(this,!1),k4.set(this,!1),z2.set(this,!1),f4.set(this,void 0),b4.set(this,void 0),_$.set(this,void 0),y4.set(this,(Z)=>{if(L(this,S4,!0,"f"),J1(Z))Z=new C0;if(Z instanceof C0)return L(this,k4,!0,"f"),this._emit("abort",Z);if(Z instanceof j)return this._emit("error",Z);if(Z instanceof Error){let Y=new j(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new j(String(Z)))}),L(this,f$,new Promise((Z,Y)=>{L(this,I4,Z,"f"),L(this,b$,Y,"f")}),"f"),L(this,y$,new Promise((Z,Y)=>{L(this,w4,Z,"f"),L(this,x$,Y,"f")}),"f"),O(this,f$,"f").catch(()=>{}),O(this,y$,"f").catch(()=>{}),L(this,b2,$,"f"),L(this,_$,z?.logger??console,"f")}get response(){return O(this,f4,"f")}get request_id(){return O(this,b4,"f")}async withResponse(){L(this,z2,!0,"f");let $=await O(this,f$,"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 h$(null);return z._run(()=>z._fromReadableStream($)),z}static createMessage($,z,Z,{logger:Y}={}){let Q=new h$(z,{logger:Y});for(let J of z.messages)Q._addMessageParam(J);return L(Q,b2,{...z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...z,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},O(this,y4,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,z=!0){if(this.receivedMessages.push($),z)this._emit("message",$)}async _createMessage($,z,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,v0,"m",h7).call(this);let{response:J,data:X}=await $.create({...z,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(J);for await(let K of X)O(this,v0,"m",g7).call(this,K);if(X.controller.signal?.aborted)throw new C0;O(this,v0,"m",m7).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,f4,$,"f"),L(this,b4,$?.headers.get("request-id"),"f"),O(this,I4,"f").call(this,$),this._emit("connect")}get ended(){return O(this,v$,"f")}get errored(){return O(this,S4,"f")}get aborted(){return O(this,k4,"f")}abort(){this.controller.abort()}on($,z){return(O(this,K1,"f")[$]||(O(this,K1,"f")[$]=[])).push({listener:z}),this}off($,z){let Z=O(this,K1,"f")[$];if(!Z)return this;let Y=Z.findIndex((Q)=>Q.listener===z);if(Y>=0)Z.splice(Y,1);return this}once($,z){return(O(this,K1,"f")[$]||(O(this,K1,"f")[$]=[])).push({listener:z,once:!0}),this}emitted($){return new Promise((z,Z)=>{if(L(this,z2,!0,"f"),$!=="error")this.once("error",Z);this.once($,z)})}async done(){L(this,z2,!0,"f"),await O(this,y$,"f")}get currentMessage(){return O(this,S1,"f")}async finalMessage(){return await this.done(),O(this,v0,"m",_7).call(this)}async finalText(){return await this.done(),O(this,v0,"m",yZ).call(this)}_emit($,...z){if(O(this,v$,"f"))return;if($==="end")L(this,v$,!0,"f"),O(this,w4,"f").call(this);let Z=O(this,K1,"f")[$];if(Z)O(this,K1,"f")[$]=Z.filter((Y)=>!Y.once),Z.forEach(({listener:Y})=>Y(...z));if($==="abort"){let Y=z[0];if(!O(this,z2,"f")&&!Z?.length)Promise.reject(Y);O(this,b$,"f").call(this,Y),O(this,x$,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=z[0];if(!O(this,z2,"f")&&!Z?.length)Promise.reject(Y);O(this,b$,"f").call(this,Y),O(this,x$,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,v0,"m",_7).call(this))}async _fromReadableStream($,z){let Z=z?.signal,Y;if(Z){if(Z.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Z.addEventListener("abort",Y)}try{O(this,v0,"m",h7).call(this),this._connected(null);let Q=k0.fromReadableStream($,this.controller);for await(let J of Q)O(this,v0,"m",g7).call(this,J);if(Q.controller.signal?.aborted)throw new C0;O(this,v0,"m",m7).call(this)}finally{if(Z&&Y)Z.removeEventListener("abort",Y)}}[(S1=new WeakMap,b2=new WeakMap,f$=new WeakMap,I4=new WeakMap,b$=new WeakMap,y$=new WeakMap,w4=new WeakMap,x$=new WeakMap,K1=new WeakMap,v$=new WeakMap,S4=new WeakMap,k4=new WeakMap,z2=new WeakMap,f4=new WeakMap,b4=new WeakMap,_$=new WeakMap,y4=new WeakMap,v0=new WeakSet,_7=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},yZ=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((Z)=>Z.type==="text").map((Z)=>Z.text);if(z.length===0)throw new j("stream ended without producing a content block with type=text");return z.join(" ")},h7=function(){if(this.ended)return;L(this,S1,void 0,"f")},g7=function(z){if(this.ended)return;let Z=O(this,v0,"m",xZ).call(this,z);switch(this._emit("streamEvent",z,Z),z.type){case"content_block_delta":{let Y=Z.content.at(-1);switch(z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(_Z(Y)&&Y.input)this._emit("inputJson",z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}case"compaction_delta":{if(Y.type==="compaction"&&Y.content)this._emit("compaction",Y.content);break}default:hZ(z.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(x7(Z,O(this,b2,"f"),{logger:O(this,_$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{L(this,S1,Z,"f");break}case"content_block_start":case"message_delta":break}},m7=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let z=O(this,S1,"f");if(!z)throw new j("request ended without sending any chunks");return L(this,S1,void 0,"f"),x7(z,O(this,b2,"f"),{logger:O(this,_$,"f")})},xZ=function(z){let Z=O(this,S1,"f");if(z.type==="message_start"){if(Z)throw new j(`Unexpected event order, got ${z.type} before receiving "message_stop"`);return z.message}if(!Z)throw new j(`Unexpected event order, got ${z.type} before "message_start"`);switch(z.type){case"message_stop":return Z;case"message_delta":if(Z.container=z.delta.container,Z.stop_reason=z.delta.stop_reason,Z.stop_sequence=z.delta.stop_sequence,Z.usage.output_tokens=z.usage.output_tokens,Z.context_management=z.context_management,z.usage.input_tokens!=null)Z.usage.input_tokens=z.usage.input_tokens;if(z.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=z.usage.cache_creation_input_tokens;if(z.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=z.usage.cache_read_input_tokens;if(z.usage.server_tool_use!=null)Z.usage.server_tool_use=z.usage.server_tool_use;if(z.usage.iterations!=null)Z.usage.iterations=z.usage.iterations;return Z;case"content_block_start":return Z.content.push(z.content_block),Z;case"content_block_delta":{let Y=Z.content.at(z.index);switch(z.delta.type){case"text_delta":{if(Y?.type==="text")Z.content[z.index]={...Y,text:(Y.text||"")+z.delta.text};break}case"citations_delta":{if(Y?.type==="text")Z.content[z.index]={...Y,citations:[...Y.citations??[],z.delta.citation]};break}case"input_json_delta":{if(Y&&_Z(Y)){let Q=Y[vZ]||"";Q+=z.delta.partial_json;let J={...Y};if(Object.defineProperty(J,vZ,{value:Q,enumerable:!1,writable:!0}),Q)try{J.input=D4(Q)}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: ${Q}`);O(this,y4,"f").call(this,K)}Z.content[z.index]=J}break}case"thinking_delta":{if(Y?.type==="thinking")Z.content[z.index]={...Y,thinking:Y.thinking+z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Z.content[z.index]={...Y,signature:z.delta.signature};break}case"compaction_delta":{if(Y?.type==="compaction")Z.content[z.index]={...Y,content:(Y.content||"")+z.delta.content};break}default:hZ(z.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],z=[],Z=!1;return this.on("streamEvent",(Y)=>{let Q=z.shift();if(Q)Q.resolve(Y);else $.push(Y)}),this.on("end",()=>{Z=!0;for(let Y of z)Y.resolve(void 0);z.length=0}),this.on("abort",(Y)=>{Z=!0;for(let Q of z)Q.reject(Y);z.length=0}),this.on("error",(Y)=>{Z=!0;for(let Q of z)Q.reject(Y);z.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((Q,J)=>z.push({resolve:Q,reject:J})).then((Q)=>Q?{value:Q,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 k0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function hZ($){}class y2 extends Error{constructor($){let z=typeof $==="string"?$:$.map((Z)=>{if(Z.type==="text")return Z.text;return`[${Z.type}]`}).join(" ");super(z);this.name="ToolError",this.content=$}}var gZ=1e5,mZ=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
136
|
+
${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:
|
|
136
137
|
1. Task Overview
|
|
137
138
|
The user's core request and success criteria
|
|
138
139
|
Any clarifications or constraints they specified
|
|
@@ -154,55 +155,55 @@ User preferences or style requirements
|
|
|
154
155
|
Domain-specific details that aren't obvious
|
|
155
156
|
Any promises made to the user
|
|
156
157
|
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
157
|
-
Wrap your summary in <summary></summary> tags.`;var
|
|
158
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Q.model in ZW&&Q.thinking&&Q.thinking.type==="enabled")console.warn(`Using Claude with ${Q.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(!Q.stream&&J==null){let K=T4[Q.model]??void 0;J=this._client.calculateNonstreamingTimeout(Q.max_tokens,K)}let X=A4(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:J??600000,...z,headers:D([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},X,z?.headers]),stream:Z.stream??!1})}parse($,z){return z={...z,headers:D([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},z?.headers])},this.create($,z).then((Z)=>v7(Z,$,{logger:this._client.logger??console}))}stream($,z){return h$.createMessage(this,$,z)}countTokens($,z){let Z=cZ($),{betas:Y,...Q}=Z;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...z,headers:D([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},z?.headers])})}toolRunner($,z){return new p$(this._client,$,z)}}function cZ($){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,...Z}=$;return{...Z,output_config:{...$.output_config,format:z}}}f1.Batches=d$;f1.BetaToolRunner=p$;f1.ToolError=y2;class c$ extends n{create($,z={},Z){let{betas:Y,...Q}=z??{};return this._client.post(r`/v1/skills/${$}/versions?beta=true`,k2({body:Q,...Z,headers:D([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client))}retrieve($,z,Z){let{skill_id:Y,betas:Q}=z;return this._client.get(r`/v1/skills/${Y}/versions/${$}?beta=true`,{...Z,headers:D([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Z?.headers])})}list($,z={},Z){let{betas:Y,...Q}=z??{};return this._client.getAPIList(r`/v1/skills/${$}/versions?beta=true`,D$,{query:Q,...Z,headers:D([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,z,Z){let{skill_id:Y,betas:Q}=z;return this._client.delete(r`/v1/skills/${Y}/versions/${$}?beta=true`,{...Z,headers:D([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Z?.headers])})}}class _2 extends n{constructor(){super(...arguments);this.versions=new c$(this._client)}create($={},z){let{betas:Z,...Y}=$??{};return this._client.post("/v1/skills?beta=true",k2({body:Y,...z,headers:D([{"anthropic-beta":[...Z??[],"skills-2025-10-02"].toString()},z?.headers])},this._client,!1))}retrieve($,z={},Z){let{betas:Y}=z??{};return this._client.get(r`/v1/skills/${$}?beta=true`,{...Z,headers:D([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}list($={},z){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",D$,{query:Y,...z,headers:D([{"anthropic-beta":[...Z??[],"skills-2025-10-02"].toString()},z?.headers])})}delete($,z={},Z){let{betas:Y}=z??{};return this._client.delete(r`/v1/skills/${$}?beta=true`,{...Z,headers:D([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}}_2.Versions=c$;class n0 extends n{constructor(){super(...arguments);this.models=new k$(this._client),this.messages=new f1(this._client),this.files=new S$(this._client),this.skills=new _2(this._client)}}n0.Models=k$;n0.Messages=f1;n0.Files=S$;n0.Skills=_2;class h2 extends n{create($,z){let{betas:Z,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...z,headers:D([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},z?.headers]),stream:$.stream??!1})}}function lZ($){return $?.output_config?.format}function p7($,z,Z){let Y=lZ(z);if(!z||!("parse"in(Y??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text")return Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Q}),parsed_output:null};return d7($,z,Z)}function d7($,z,Z){let Y=null,Q=$.content.map((J)=>{if(J.type==="text"){let X=XW(z,J.text);if(Y===null)Y=X;return Object.defineProperty({...J},"parsed_output",{value:X,enumerable:!1})}return J});return{...$,content:Q,parsed_output:Y}}function XW($,z){let Z=lZ($);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse(z);return JSON.parse(z)}catch(Y){throw new j(`Failed to parse structured output: ${Y}`)}}var _0,b1,g2,l$,x4,o$,i$,v4,r$,G1,n$,_4,h4,Y2,g4,m4,a$,c7,oZ,l7,o7,i7,r7,iZ,rZ="__json_buf";function nZ($){return $.type==="tool_use"||$.type==="server_tool_use"}class s${constructor($,z){_0.add(this),this.messages=[],this.receivedMessages=[],b1.set(this,void 0),g2.set(this,null),this.controller=new AbortController,l$.set(this,void 0),x4.set(this,()=>{}),o$.set(this,()=>{}),i$.set(this,void 0),v4.set(this,()=>{}),r$.set(this,()=>{}),G1.set(this,{}),n$.set(this,!1),_4.set(this,!1),h4.set(this,!1),Y2.set(this,!1),g4.set(this,void 0),m4.set(this,void 0),a$.set(this,void 0),l7.set(this,(Z)=>{if(L(this,_4,!0,"f"),J1(Z))Z=new C0;if(Z instanceof C0)return L(this,h4,!0,"f"),this._emit("abort",Z);if(Z instanceof j)return this._emit("error",Z);if(Z instanceof Error){let Y=new j(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new j(String(Z)))}),L(this,l$,new Promise((Z,Y)=>{L(this,x4,Z,"f"),L(this,o$,Y,"f")}),"f"),L(this,i$,new Promise((Z,Y)=>{L(this,v4,Z,"f"),L(this,r$,Y,"f")}),"f"),O(this,l$,"f").catch(()=>{}),O(this,i$,"f").catch(()=>{}),L(this,g2,$,"f"),L(this,a$,z?.logger??console,"f")}get response(){return O(this,g4,"f")}get request_id(){return O(this,m4,"f")}async withResponse(){L(this,Y2,!0,"f");let $=await O(this,l$,"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 s$(null);return z._run(()=>z._fromReadableStream($)),z}static createMessage($,z,Z,{logger:Y}={}){let Q=new s$(z,{logger:Y});for(let J of z.messages)Q._addMessageParam(J);return L(Q,g2,{...z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...z,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},O(this,l7,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,z=!0){if(this.receivedMessages.push($),z)this._emit("message",$)}async _createMessage($,z,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{O(this,_0,"m",o7).call(this);let{response:J,data:X}=await $.create({...z,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(J);for await(let K of X)O(this,_0,"m",i7).call(this,K);if(X.controller.signal?.aborted)throw new C0;O(this,_0,"m",r7).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,g4,$,"f"),L(this,m4,$?.headers.get("request-id"),"f"),O(this,x4,"f").call(this,$),this._emit("connect")}get ended(){return O(this,n$,"f")}get errored(){return O(this,_4,"f")}get aborted(){return O(this,h4,"f")}abort(){this.controller.abort()}on($,z){return(O(this,G1,"f")[$]||(O(this,G1,"f")[$]=[])).push({listener:z}),this}off($,z){let Z=O(this,G1,"f")[$];if(!Z)return this;let Y=Z.findIndex((Q)=>Q.listener===z);if(Y>=0)Z.splice(Y,1);return this}once($,z){return(O(this,G1,"f")[$]||(O(this,G1,"f")[$]=[])).push({listener:z,once:!0}),this}emitted($){return new Promise((z,Z)=>{if(L(this,Y2,!0,"f"),$!=="error")this.once("error",Z);this.once($,z)})}async done(){L(this,Y2,!0,"f"),await O(this,i$,"f")}get currentMessage(){return O(this,b1,"f")}async finalMessage(){return await this.done(),O(this,_0,"m",c7).call(this)}async finalText(){return await this.done(),O(this,_0,"m",oZ).call(this)}_emit($,...z){if(O(this,n$,"f"))return;if($==="end")L(this,n$,!0,"f"),O(this,v4,"f").call(this);let Z=O(this,G1,"f")[$];if(Z)O(this,G1,"f")[$]=Z.filter((Y)=>!Y.once),Z.forEach(({listener:Y})=>Y(...z));if($==="abort"){let Y=z[0];if(!O(this,Y2,"f")&&!Z?.length)Promise.reject(Y);O(this,o$,"f").call(this,Y),O(this,r$,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=z[0];if(!O(this,Y2,"f")&&!Z?.length)Promise.reject(Y);O(this,o$,"f").call(this,Y),O(this,r$,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",O(this,_0,"m",c7).call(this))}async _fromReadableStream($,z){let Z=z?.signal,Y;if(Z){if(Z.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Z.addEventListener("abort",Y)}try{O(this,_0,"m",o7).call(this),this._connected(null);let Q=k0.fromReadableStream($,this.controller);for await(let J of Q)O(this,_0,"m",i7).call(this,J);if(Q.controller.signal?.aborted)throw new C0;O(this,_0,"m",r7).call(this)}finally{if(Z&&Y)Z.removeEventListener("abort",Y)}}[(b1=new WeakMap,g2=new WeakMap,l$=new WeakMap,x4=new WeakMap,o$=new WeakMap,i$=new WeakMap,v4=new WeakMap,r$=new WeakMap,G1=new WeakMap,n$=new WeakMap,_4=new WeakMap,h4=new WeakMap,Y2=new WeakMap,g4=new WeakMap,m4=new WeakMap,a$=new WeakMap,l7=new WeakMap,_0=new WeakSet,c7=function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},oZ=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((Z)=>Z.type==="text").map((Z)=>Z.text);if(z.length===0)throw new j("stream ended without producing a content block with type=text");return z.join(" ")},o7=function(){if(this.ended)return;L(this,b1,void 0,"f")},i7=function(z){if(this.ended)return;let Z=O(this,_0,"m",iZ).call(this,z);switch(this._emit("streamEvent",z,Z),z.type){case"content_block_delta":{let Y=Z.content.at(-1);switch(z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(nZ(Y)&&Y.input)this._emit("inputJson",z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:aZ(z.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(p7(Z,O(this,g2,"f"),{logger:O(this,a$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{L(this,b1,Z,"f");break}case"content_block_start":case"message_delta":break}},r7=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");let z=O(this,b1,"f");if(!z)throw new j("request ended without sending any chunks");return L(this,b1,void 0,"f"),p7(z,O(this,g2,"f"),{logger:O(this,a$,"f")})},iZ=function(z){let Z=O(this,b1,"f");if(z.type==="message_start"){if(Z)throw new j(`Unexpected event order, got ${z.type} before receiving "message_stop"`);return z.message}if(!Z)throw new j(`Unexpected event order, got ${z.type} before "message_start"`);switch(z.type){case"message_stop":return Z;case"message_delta":if(Z.stop_reason=z.delta.stop_reason,Z.stop_sequence=z.delta.stop_sequence,Z.usage.output_tokens=z.usage.output_tokens,z.usage.input_tokens!=null)Z.usage.input_tokens=z.usage.input_tokens;if(z.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=z.usage.cache_creation_input_tokens;if(z.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=z.usage.cache_read_input_tokens;if(z.usage.server_tool_use!=null)Z.usage.server_tool_use=z.usage.server_tool_use;return Z;case"content_block_start":return Z.content.push({...z.content_block}),Z;case"content_block_delta":{let Y=Z.content.at(z.index);switch(z.delta.type){case"text_delta":{if(Y?.type==="text")Z.content[z.index]={...Y,text:(Y.text||"")+z.delta.text};break}case"citations_delta":{if(Y?.type==="text")Z.content[z.index]={...Y,citations:[...Y.citations??[],z.delta.citation]};break}case"input_json_delta":{if(Y&&nZ(Y)){let Q=Y[rZ]||"";Q+=z.delta.partial_json;let J={...Y};if(Object.defineProperty(J,rZ,{value:Q,enumerable:!1,writable:!0}),Q)J.input=D4(Q);Z.content[z.index]=J}break}case"thinking_delta":{if(Y?.type==="thinking")Z.content[z.index]={...Y,thinking:Y.thinking+z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Z.content[z.index]={...Y,signature:z.delta.signature};break}default:aZ(z.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],z=[],Z=!1;return this.on("streamEvent",(Y)=>{let Q=z.shift();if(Q)Q.resolve(Y);else $.push(Y)}),this.on("end",()=>{Z=!0;for(let Y of z)Y.resolve(void 0);z.length=0}),this.on("abort",(Y)=>{Z=!0;for(let Q of z)Q.reject(Y);z.length=0}),this.on("error",(Y)=>{Z=!0;for(let Q of z)Q.reject(Y);z.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((Q,J)=>z.push({resolve:Q,reject:J})).then((Q)=>Q?{value:Q,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 k0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function aZ($){}class t$ extends n{create($,z){return this._client.post("/v1/messages/batches",{body:$,...z})}retrieve($,z){return this._client.get(r`/v1/messages/batches/${$}`,z)}list($={},z){return this._client.getAPIList("/v1/messages/batches",d0,{query:$,...z})}delete($,z){return this._client.delete(r`/v1/messages/batches/${$}`,z)}cancel($,z){return this._client.post(r`/v1/messages/batches/${$}/cancel`,z)}async results($,z){let Z=await this.retrieve($);if(!Z.results_url)throw new j(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...z,headers:D([{Accept:"application/binary"},z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,Q)=>v2.fromResponse(Q.response,Q.controller))}}class Q2 extends n{constructor(){super(...arguments);this.batches=new t$(this._client)}create($,z){if($.model in sZ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${sZ[$.model]}
|
|
159
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in
|
|
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.
|
|
160
161
|
|
|
161
162
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
162
163
|
If you understand the risks and have appropriate mitigations in place,
|
|
163
164
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
164
165
|
|
|
165
166
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
166
|
-
`);this.baseURL=Q.baseURL,this.timeout=Q.timeout??a7.DEFAULT_TIMEOUT,this.logger=Q.logger??console;let J="warn";this.logLevel=J,this.logLevel=D7(Q.logLevel,"ClientOptions.logLevel",this)??D7(e$("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??NZ(),L(this,u4,EZ,"f"),this._options=Q,this.apiKey=typeof z==="string"?z:null,this.authToken=Z}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return D([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return D([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return D([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return RZ($)}getUserAgent(){return`${this.constructor.name}/JS ${I1}`}defaultIdempotencyKey(){return`stainless-node-retry-${L7()}`}makeStatusError($,z,Z,Y){return Y0.generate($,z,Z,Y)}buildURL($,z,Z){let Y=!O(this,n7,"m",tZ).call(this)&&Z||this.baseURL,Q=VZ($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),X=Object.fromEntries(Q.searchParams);if(!P7(J)||!P7(X))z={...X,...J,...z};if(typeof z==="object"&&z&&!Array.isArray(z))Q.search=this.stringifyQuery(z);return Q.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:Z}){}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,Z){return this.request(Promise.resolve(Z).then((Y)=>{return{method:$,path:z,...Y}}))}request($,z=null){return new e1(this,this.makeRequest($,z,void 0))}async makeRequest($,z,Z){let Y=await $,Q=Y.maxRetries??this.maxRetries;if(z==null)z=Q;await this.prepareOptions(Y);let{req:J,url:X,timeout:K}=await this.buildRequest(Y,{retryCount:Q-z});await this.prepareRequest(J,{url:X,options:Y});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),G=Z===void 0?"":`, retryOf: ${Z}`,H=Date.now();if(K0(this).debug(`[${V}] sending request`,X1({retryOfRequestLogID:Z,method:Y.method,url:X,options:Y,headers:J.headers})),Y.signal?.aborted)throw new C0;let W=new AbortController,U=await this.fetchWithTimeout(X,J,K,W).catch(U$),B=Date.now();if(U instanceof globalThis.Error){let M=`retrying, ${z} attempts remaining`;if(Y.signal?.aborted)throw new C0;let R=J1(U)||/timed? ?out/i.test(String(U)+("cause"in U?String(U.cause):""));if(z)return K0(this).info(`[${V}] connection ${R?"timed out":"failed"} - ${M}`),K0(this).debug(`[${V}] connection ${R?"timed out":"failed"} (${M})`,X1({retryOfRequestLogID:Z,url:X,durationMs:B-H,message:U.message})),this.retryRequest(Y,z,Z??V);if(K0(this).info(`[${V}] connection ${R?"timed out":"failed"} - error; no more retries left`),K0(this).debug(`[${V}] connection ${R?"timed out":"failed"} (error; no more retries left)`,X1({retryOfRequestLogID:Z,url:X,durationMs:B-H,message:U.message})),R)throw new q$;throw new t1({cause:U})}let C=[...U.headers.entries()].filter(([M])=>M==="request-id").map(([M,R])=>", "+M+": "+JSON.stringify(R)).join(""),N=`[${V}${G}${C}] ${J.method} ${X} ${U.ok?"succeeded":"failed"} with status ${U.status} in ${B-H}ms`;if(!U.ok){let M=await this.shouldRetry(U);if(z&&M){let d=`retrying, ${z} attempts remaining`;return await MZ(U.body),K0(this).info(`${N} - ${d}`),K0(this).debug(`[${V}] response error (${d})`,X1({retryOfRequestLogID:Z,url:U.url,status:U.status,headers:U.headers,durationMs:B-H})),this.retryRequest(Y,z,Z??V,U.headers)}let R=M?"error; no more retries left":"error; not retryable";K0(this).info(`${N} - ${R}`);let I=await U.text().catch((d)=>U$(d).message),_=O4(I),T=_?void 0:I;throw K0(this).debug(`[${V}] response error (${R})`,X1({retryOfRequestLogID:Z,url:U.url,status:U.status,headers:U.headers,message:T,durationMs:Date.now()-H})),this.makeStatusError(U.status,_,T,U.headers)}return K0(this).info(N),K0(this).debug(`[${V}] response start`,X1({retryOfRequestLogID:Z,url:U.url,status:U.status,headers:U.headers,durationMs:B-H})),{response:U,options:Y,controller:W,requestLogID:V,retryOfRequestLogID:Z,startTime:H}}getAPIList($,z,Z){return this.requestAPIList(z,Z&&"then"in Z?Z.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...Z})}requestAPIList($,z){let Z=this.makeRequest(z,null,void 0);return new F4(this,Z,$)}async fetchWithTimeout($,z,Z,Y){let{signal:Q,method:J,...X}=z||{},K=this._makeAbort(Y);if(Q)Q.addEventListener("abort",K,{once:!0});let V=setTimeout(K,Z),G=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,H={signal:Y.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,Z,Y){let Q,J=Y?.get("retry-after-ms");if(J){let K=parseFloat(J);if(!Number.isNaN(K))Q=K}let X=Y?.get("retry-after");if(X&&!Q){let K=parseFloat(X);if(!Number.isNaN(K))Q=K*1000;else Q=Date.parse(X)-Date.now()}if(Q===void 0){let K=$.maxRetries??this.maxRetries;Q=this.calculateDefaultRetryTimeoutMillis(z,K)}return await WZ(Q),this.makeRequest($,z-1,Z)}calculateDefaultRetryTimeoutMillis($,z){let Q=z-$,J=Math.min(0.5*Math.pow(2,Q),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 Z={...$},{method:Y,path:Q,query:J,defaultBaseURL:X}=Z,K=this.buildURL(Q,J,X);if("timeout"in Z)HZ("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:V,body:G}=this.buildBody({options:Z}),H=await this.buildHeaders({options:$,method:Y,bodyHeaders:V,retryCount:z});return{req:{method:Y,headers:H,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"},...G&&{body:G},...this.fetchOptions??{},...Z.fetchOptions??{}},url:K,timeout:Z.timeout}}async buildHeaders({options:$,method:z,bodyHeaders:Z,retryCount:Y}){let Q={};if(this.idempotencyHeader&&z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Q[this.idempotencyHeader]=$.idempotencyKey}let J=D([Q,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...OZ(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(J),J.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Z=D([z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Z.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:N4($)};else if(typeof $==="object"&&Z.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,u4,"f").call(this,{body:$,headers:Z})}}a7=a,u4=new WeakMap,n7=new WeakSet,tZ=function(){return this.baseURL!=="https://api.anthropic.com"};a.Anthropic=a7;a.HUMAN_PROMPT=eZ;a.AI_PROMPT=$Y;a.DEFAULT_TIMEOUT=600000;a.AnthropicError=j;a.APIError=Y0;a.APIConnectionError=t1;a.APIConnectionTimeoutError=q$;a.APIUserAbortError=C0;a.NotFoundError=N$;a.ConflictError=M$;a.RateLimitError=R$;a.BadRequestError=B$;a.AuthenticationError=C$;a.InternalServerError=L$;a.PermissionDeniedError=O$;a.UnprocessableEntityError=E$;a.toFile=j4;class a0 extends a{constructor(){super(...arguments);this.completions=new h2(this),this.messages=new Q2(this),this.models=new m2(this),this.beta=new n0(this)}}a0.Completions=h2;a0.Messages=Q2;a0.Models=m2;a0.Beta=n0;import{existsSync as HW,readFileSync as WW,writeFileSync as UW}from"fs";import{basename as s7}from"path";var zY=50;class t7{entries=[];saveState($){let z=HW($),Z=z?WW($,"utf-8"):"";if(this.entries.push({path:$,content:Z,timestamp:Date.now(),existed:z}),this.entries.length>zY)this.entries=this.entries.slice(-zY)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${s7($.path)} was a new file. Remove it manually if needed.`;UW($.path,$.content);let z=$.content.split(`
|
|
167
|
-
`).length;return`Undo: restored ${s7($.path)} (${z} lines, from ${ZY($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${s7($.path)} (${ZY($.timestamp)})`}}function ZY($){let z=Math.floor((Date.now()-$)/1000);if(z<60)return`${z}s ago`;let Z=Math.floor(z/60);if(Z<60)return`${Z}m ago`;return`${Math.floor(Z/60)}h ago`}t();var S=[{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 $5=[{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:[]}}],p4=[{name:"execute_powershell_script",description:"Execute a PowerShell script on the local machine. The script runs in a temp .ps1 file with -ExecutionPolicy Bypass (scoped). Safety guards block dangerous operations (Defender, System32, formatting). Returns stdout, stderr, exit code, and duration. Use for: automation, system queries, batch operations, registry reads, scheduled tasks.",input_schema:{type:"object",properties:{script:{type:"string",description:"The PowerShell script to execute. Multi-line supported."}},required:["script"]}},{name:"analyze_screen_context",description:"Get detailed information about the user's current screen: foreground window (what they are looking at), all visible windows with PIDs, memory usage, and titles. Use to understand the user's current context. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"read_clipboard_content",description:'Read the current clipboard content. Auto-detects text or image. For images, performs OCR using Windows.Media.Ocr to extract text. Use when the user says "le o que copiei", "o que tem no clipboard", "cola isso", etc. Read-only.',input_schema:{type:"object",properties:{},required:[]}}],d4=[{name:"send_notification",description:'Send a Windows toast notification to the user. Displays a system notification with title and message. Use when you need to alert the user about: task completions, reminders, important events, or when the user asks "me avisa quando terminar", "notifica quando...", etc.',input_schema:{type:"object",properties:{title:{type:"string",description:"Notification title (short, max ~50 chars)."},message:{type:"string",description:"Notification message/body."}},required:["title","message"]}}],c4=$5.find(($)=>$.name==="get_news");import{resolve as B6,sep as xX}from"path";import{writeFileSync as TC}from"fs";v();import{existsSync as qW,readFileSync as BW}from"fs";import{join as CW}from"path";var J2=[{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}],l4="",O0=[],b0=new Set,XY=()=>CW(l4,"news-feeds.json");function o4(){if(!l4)return;let $={custom:O0,disabled:[...b0]};P(XY(),JSON.stringify($,null,2))}function OW(){if(!l4)return;let $=XY();if(!qW($)){O0=[],b0=new Set;return}try{let z=JSON.parse(BW($,"utf-8"));O0=z.custom||[],b0=new Set(z.disabled||[])}catch{O0=[],b0=new Set}}function KY($){l4=$,OW()}function i4(){return[...J2.filter((z)=>!b0.has(z.url)),...O0]}function Q5($,z,Z){let Y=$.trim();if(!Y||Y.length>100)return"Error: nome invalido (1-100 caracteres).";let Q=Z.trim().toLowerCase();if(!Q||Q.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([...J2,...O0].some((V)=>V.url===J))return"Error: essa URL ja esta cadastrada.";let K={name:Y,url:J,category:Q};return O0=[...O0,K],o4(),K}function r4($){let z=$.toLowerCase().trim(),Z=O0.findIndex((Y)=>Y.name.toLowerCase()===z||Y.url===$.trim());if(Z===-1)return!1;return O0=[...O0.slice(0,Z),...O0.slice(Z+1)],o4(),!0}function n4($){let z=$.toLowerCase().trim(),Z=J2.find((Y)=>Y.name.toLowerCase()===z||Y.url===$.trim());if(!Z)return!1;if(b0.has(Z.url))return!1;return b0=new Set([...b0,Z.url]),o4(),!0}function a4($){let z=$.toLowerCase().trim(),Z=J2.find((Y)=>Y.name.toLowerCase()===z||Y.url===$.trim());if(!Z)return!1;if(!b0.has(Z.url))return!1;return b0=new Set([...b0].filter((Y)=>Y!==Z.url)),o4(),!0}function s4(){let $=["Fontes de noticias:"];$.push(`
|
|
168
|
-
--- Built-in ---`);for(let
|
|
169
|
-
--- Custom ---`);for(let
|
|
170
|
-
Total: ${
|
|
171
|
-
`)}var
|
|
172
|
-
Falhas: ${
|
|
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} ---
|
|
173
174
|
${H.join(`
|
|
174
|
-
`)}`)}let X=
|
|
175
|
+
`)}`)}let X=z.join(`
|
|
175
176
|
|
|
176
|
-
`);if(
|
|
177
|
+
`);if(Z.length>0)X+=`
|
|
177
178
|
|
|
178
|
-
(Fontes indisponiveis: ${
|
|
179
|
-
Uso: /news [categoria]`}var
|
|
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(`
|
|
180
181
|
|
|
181
|
-
`)}else
|
|
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(`
|
|
182
183
|
|
|
183
|
-
`)}
|
|
184
|
-
${
|
|
185
|
-
`)}`}function
|
|
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}):
|
|
185
|
+
${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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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}:
|
|
186
187
|
${J[V].map((G)=>` ${G}`).join(`
|
|
187
188
|
`)}`);return`Memos (${$.length}):
|
|
188
189
|
${K.join(`
|
|
189
190
|
|
|
190
|
-
`)}`}function
|
|
191
|
-
${$.map((
|
|
192
|
-
`)}`}function
|
|
193
|
-
`);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
|
|
194
|
-
`)}
|
|
195
|
-
${
|
|
196
|
-
`)}`}function
|
|
197
|
-
`)}function
|
|
191
|
+
`)}`}function j7(){let $=JB();if($.length===0)return"Nenhuma tag.";return`Tags:
|
|
192
|
+
${$.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
|
+
${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
|
|
198
199
|
# Job ID: ${$}
|
|
199
200
|
# Generated: ${new Date().toISOString()}
|
|
200
201
|
|
|
201
202
|
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
|
202
203
|
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
|
|
203
204
|
|
|
204
|
-
$title = '${
|
|
205
|
-
$body = '${
|
|
205
|
+
$title = '${Z.replace(/'/g,"''")}'
|
|
206
|
+
$body = '${Y.replace(/'/g,"''")}'
|
|
206
207
|
|
|
207
208
|
$template = @"
|
|
208
209
|
<toast>
|
|
@@ -220,82 +221,82 @@ $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
|
|
220
221
|
$xml.LoadXml($template)
|
|
221
222
|
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
|
222
223
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show($toast)
|
|
223
|
-
`,X=Buffer.from([239,187,191]),K=Buffer.concat([X,Buffer.from(J,"utf-8")]);return
|
|
224
|
-
`)}function
|
|
225
|
-
${
|
|
226
|
-
`)}`}function
|
|
227
|
-
`)}var
|
|
228
|
-
`)}function
|
|
229
|
-
${
|
|
230
|
-
`)}`}function
|
|
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:
|
|
226
|
+
${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
|
+
${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]} ---
|
|
231
232
|
${X.join(`
|
|
232
|
-
`)}`)}return
|
|
233
|
+
`)}`)}return Y.join(`
|
|
233
234
|
|
|
234
|
-
`)}function
|
|
235
|
-
Interacoes recentes:`);for(let
|
|
236
|
-
Tarefas delegadas:`);for(let
|
|
237
|
-
`)}function
|
|
238
|
-
${
|
|
239
|
-
`)}`}function
|
|
240
|
-
${
|
|
241
|
-
`)}`}function
|
|
242
|
-
`);let
|
|
243
|
-
!! ${
|
|
244
|
-
!! ${X.length} delegacao(oes) atrasada(s):`);for(let G of X.slice(0,5)){let H=
|
|
245
|
-
${K.length} delegacao(oes) em andamento`);let V=[...
|
|
246
|
-
Ultimas interacoes:`);for(let G of V){let H=
|
|
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}):
|
|
239
|
+
${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}):
|
|
241
|
+
${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(`
|
|
247
248
|
========================`),$.join(`
|
|
248
|
-
`)}function
|
|
249
|
-
[${
|
|
250
|
-
`)}function
|
|
251
|
-
${
|
|
252
|
-
`)}`}function
|
|
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(`
|
|
250
|
+
[${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}):
|
|
252
|
+
${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}} ---
|
|
253
254
|
Titulo: ${$.title}
|
|
254
255
|
Categoria: ${$.category}
|
|
255
256
|
|
|
256
257
|
${$.content}
|
|
257
258
|
|
|
258
|
-
${
|
|
259
|
-
${
|
|
260
|
-
${$.map((
|
|
261
|
-
`)}`}function
|
|
262
|
-
${
|
|
263
|
-
`).filter(Boolean),
|
|
264
|
-
`)){let N
|
|
265
|
-
`).filter(Boolean))U.set(
|
|
266
|
-
`)}function
|
|
267
|
-
${
|
|
268
|
-
`)}`}function
|
|
269
|
-
`)}function
|
|
270
|
-
${
|
|
271
|
-
`)}`}function
|
|
272
|
-
`)}function
|
|
273
|
-
`);
|
|
274
|
-
`)}function
|
|
275
|
-
`)}function
|
|
276
|
-
`)}function
|
|
277
|
-
`)}
|
|
278
|
-
`)}function
|
|
279
|
-
${
|
|
280
|
-
`)}function
|
|
281
|
-
${
|
|
282
|
-
`)}`}function
|
|
283
|
-
${
|
|
284
|
-
`)}`}function
|
|
285
|
-
`),$}function
|
|
286
|
-
`)});return["# Manual de Uso Otimizado","",`Baseado em ${
|
|
287
|
-
`)}var
|
|
288
|
-
`)}function
|
|
289
|
-
Tags: ${$.tags.map((
|
|
290
|
-
`)}function
|
|
259
|
+
${Q}
|
|
260
|
+
${z}`}function OX(){let $=qX();if($.length===0)return"Nenhuma categoria.";return`Categorias:
|
|
261
|
+
${$.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}):
|
|
268
|
+
${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}):
|
|
271
|
+
${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}):
|
|
282
|
+
${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}):
|
|
284
|
+
${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?`---
|
|
290
|
+
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(`
|
|
291
292
|
`)});return`Insights (${$.length}):
|
|
292
293
|
|
|
293
|
-
${
|
|
294
|
+
${Z.join(`
|
|
294
295
|
|
|
295
|
-
`)}`}function
|
|
296
|
-
`),Y
|
|
297
|
-
`).match(/Tags:\s*(.+)/);if(V){let U=V[1].match(/#[\w-]+/g);if(U)X.push(...U.map((
|
|
298
|
-
`).trim(),tags:X,source:"auto_generated",version:J,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function U2(){return rq("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function OB($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}p1();var n3=($,z,Z)=>{return(Y,Q)=>{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],Y.req.routeIndex=K;else H=K===$.length&&Q||void 0;if(H)try{V=await H(Y,()=>X(K+1))}catch(W){if(W instanceof Error&&z)Y.error=W,V=await z(W,Y),G=!0;else throw W}else if(Y.finalized===!1&&Z)V=await Z(Y);if(V&&(Y.finalized===!1||G))Y.res=V;return Y}}};var PJ=Symbol();var AJ=async($,z=Object.create(null))=>{let{all:Z=!1,dot:Y=!1}=z,J=($ instanceof n8?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return RB($,{all:Z,dot:Y});return{}};async function RB($,z){let Z=await $.formData();if(Z)return LB(Z,z);return{}}function LB($,z){let Z=Object.create(null);if($.forEach((Y,Q)=>{if(!(z.all||Q.endsWith("[]")))Z[Q]=Y;else FB(Z,Q,Y)}),z.dot)Object.entries(Z).forEach(([Y,Q])=>{if(Y.includes("."))jB(Z,Y,Q),delete Z[Y]});return Z}var FB=($,z,Z)=>{if($[z]!==void 0)if(Array.isArray($[z]))$[z].push(Z);else $[z]=[$[z],Z];else if(!z.endsWith("[]"))$[z]=Z;else $[z]=[Z]},jB=($,z,Z)=>{if(/(?:^|\.)__proto__\./.test(z))return;let Y=$,Q=z.split(".");Q.forEach((J,X)=>{if(X===Q.length-1)Y[J]=Z;else{if(!Y[J]||typeof Y[J]!=="object"||Array.isArray(Y[J])||Y[J]instanceof File)Y[J]=Object.create(null);Y=Y[J]}})};var s3=($)=>{let z=$.split("/");if(z[0]==="")z.shift();return z},TJ=($)=>{let{groups:z,path:Z}=PB($),Y=s3(Z);return AB(Y,z)},PB=($)=>{let z=[];return $=$.replace(/\{[^}]+\}/g,(Z,Y)=>{let Q=`@${Y}`;return z.push([Q,Z]),Q}),{groups:z,path:$}},AB=($,z)=>{for(let Z=z.length-1;Z>=0;Z--){let[Y]=z[Z];for(let Q=$.length-1;Q>=0;Q--)if($[Q].includes(Y)){$[Q]=$[Q].replace(Y,z[Z][1]);break}}return $},a8={},DJ=($,z)=>{if($==="*")return"*";let Z=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Z){let Y=`${$}#${z}`;if(!a8[Y])if(Z[2])a8[Y]=z&&z[0]!==":"&&z[0]!=="*"?[Y,Z[1],new RegExp(`^${Z[2]}(?=/${z})`)]:[$,Z[1],new RegExp(`^${Z[2]}$`)];else a8[Y]=[$,Z[1],!0];return a8[Y]}return null},s8=($,z)=>{try{return z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return z(Z)}catch{return Z}})}},t3=($)=>s8($,decodeURI),e3=($)=>{let z=$.url,Z=z.indexOf("/",z.indexOf(":")+4),Y=Z;for(;Y<z.length;Y++){let Q=z.charCodeAt(Y);if(Q===37){let J=z.indexOf("?",Y),X=z.indexOf("#",Y),K=J===-1?X===-1?void 0:X:X===-1?J:Math.min(J,X),V=z.slice(Z,K);return t3(V.includes("%25")?V.replace(/%25/g,"%2525"):V)}else if(Q===63||Q===35)break}return z.slice(Z,Y)};var IJ=($)=>{let z=e3($);return z.length>1&&z.at(-1)==="/"?z.slice(0,-1):z},O2=($,z,...Z)=>{if(Z.length)z=O2(z,...Z);return`${$?.[0]==="/"?"":"/"}${$}${z==="/"?"":`${$?.at(-1)==="/"?"":"/"}${z?.[0]==="/"?z.slice(1):z}`}`},t8=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let z=$.split("/"),Z=[],Y="";return z.forEach((Q)=>{if(Q!==""&&!/\:/.test(Q))Y+="/"+Q;else if(/\:/.test(Q))if(/\?/.test(Q)){if(Z.length===0&&Y==="")Z.push("/");else Z.push(Y);let J=Q.replace("?","");Y+="/"+J,Z.push(Y)}else Y+="/"+Q}),Z.filter((Q,J,X)=>X.indexOf(Q)===J)},a3=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?s8($,$9):$},wJ=($,z,Z)=>{let Y;if(!Z&&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 a3($.slice(V,G===-1?void 0:G))}else if(K==38||isNaN(K))return"";X=$.indexOf(`&${z}`,X+1)}if(Y=/[%+]/.test($),!Y)return}let Q={};Y??=/[%+]/.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(Y)V=a3(V);if(J=X,V==="")continue;let G;if(K===-1)G="";else if(G=$.slice(K+1,X===-1?void 0:X),Y)G=a3(G);if(Z){if(!(Q[V]&&Array.isArray(Q[V])))Q[V]=[];Q[V].push(G)}else Q[V]??=G}return z?Q[z]:Q},SJ=wJ,kJ=($,z)=>{return wJ($,z,!0)},$9=decodeURIComponent;var fJ=($)=>s8($,$9),n8=class{raw;#$;#z;routeIndex=0;path;bodyCache={};constructor($,z="/",Z=[[]]){this.raw=$,this.path=z,this.#z=Z,this.#$={}}param($){return $?this.#Z($):this.#J()}#Z($){let z=this.#z[0][this.routeIndex][1][$],Z=this.#Q(z);return Z&&/\%/.test(Z)?fJ(Z):Z}#J(){let $={},z=Object.keys(this.#z[0][this.routeIndex][1]);for(let Z of z){let Y=this.#Q(this.#z[0][this.routeIndex][1][Z]);if(Y!==void 0)$[Z]=/\%/.test(Y)?fJ(Y):Y}return $}#Q($){return this.#z[1]?this.#z[1][$]:$}query($){return SJ(this.url,$)}queries($){return kJ(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let z={};return this.raw.headers.forEach((Z,Y)=>{z[Y]=Z}),z}async parseBody($){return AJ(this,$)}#Y=($)=>{let{bodyCache:z,raw:Z}=this,Y=z[$];if(Y)return Y;let Q=Object.keys(z)[0];if(Q)return z[Q].then((J)=>{if(Q==="json")J=JSON.stringify(J);return new Response(J)[$]()});return z[$]=Z[$]()};json(){return this.#Y("text").then(($)=>JSON.parse($))}text(){return this.#Y("text")}arrayBuffer(){return this.#Y("arrayBuffer")}blob(){return this.#Y("blob")}formData(){return this.#Y("formData")}addValidatedData($,z){this.#$[$]=z}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[PJ](){return this.#z}get matchedRoutes(){return this.#z[0].map(([[,$]])=>$)}get routePath(){return this.#z[0].map(([[,$]])=>$)[this.routeIndex].path}};var bJ={Stringify:1,BeforeStream:2,Stream:3},yJ=($,z)=>{let Z=new String($);return Z.isEscaped=!0,Z.callbacks=z,Z};var z9=async($,z,Z,Y,Q)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let J=$.callbacks;if(!J?.length)return Promise.resolve($);if(Q)Q[0]+=$;else Q=[$];let X=Promise.all(J.map((K)=>K({phase:z,buffer:Q,context:Y}))).then((K)=>Promise.all(K.filter(Boolean).map((V)=>z9(V,z,!1,Y,Q))).then(()=>Q[0]));if(Z)return yJ(await X,J);else return X};var TB="text/plain; charset=UTF-8",Z9=($,z)=>{return{"Content-Type":$,...z}},E5=($,z)=>new Response($,z),xJ=class{#$;#z;env={};#Z;finalized=!1;error;#J;#Q;#Y;#H;#V;#G;#K;#W;#U;constructor($,z){if(this.#$=$,z)this.#Q=z.executionCtx,this.env=z.env,this.#G=z.notFoundHandler,this.#U=z.path,this.#W=z.matchResult}get req(){return this.#z??=new n8(this.#$,this.#U,this.#W),this.#z}get event(){if(this.#Q&&"respondWith"in this.#Q)return this.#Q;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#Q)return this.#Q;else throw Error("This context has no ExecutionContext")}get res(){return this.#Y||=E5(null,{headers:this.#K??=new Headers})}set res($){if(this.#Y&&$){$=E5($.body,$);for(let[z,Z]of this.#Y.headers.entries()){if(z==="content-type")continue;if(z==="set-cookie"){let Y=this.#Y.headers.getSetCookie();$.headers.delete("set-cookie");for(let Q of Y)$.headers.append("set-cookie",Q)}else $.headers.set(z,Z)}}this.#Y=$,this.finalized=!0}render=(...$)=>{return this.#V??=(z)=>this.html(z),this.#V(...$)};setLayout=($)=>this.#H=$;getLayout=()=>this.#H;setRenderer=($)=>{this.#V=$};header=($,z,Z)=>{if(this.finalized)this.#Y=E5(this.#Y.body,this.#Y);let Y=this.#Y?this.#Y.headers:this.#K??=new Headers;if(z===void 0)Y.delete($);else if(Z?.append)Y.append($,z);else Y.set($,z)};status=($)=>{this.#J=$};set=($,z)=>{this.#Z??=new Map,this.#Z.set($,z)};get=($)=>{return this.#Z?this.#Z.get($):void 0};get var(){if(!this.#Z)return{};return Object.fromEntries(this.#Z)}#X($,z,Z){let Y=this.#Y?new Headers(this.#Y.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")Y.append(X,K);else Y.set(X,K)}if(Z)for(let[J,X]of Object.entries(Z))if(typeof X==="string")Y.set(J,X);else{Y.delete(J);for(let K of X)Y.append(J,K)}let Q=typeof z==="number"?z:z?.status??this.#J;return E5($,{status:Q,headers:Y})}newResponse=(...$)=>this.#X(...$);body=($,z,Z)=>this.#X($,z,Z);text=($,z,Z)=>{return!this.#K&&!this.#J&&!z&&!Z&&!this.finalized?new Response($):this.#X($,z,Z9(TB,Z))};json=($,z,Z)=>{return this.#X(JSON.stringify($),z,Z9("application/json",Z))};html=($,z,Z)=>{let Y=(Q)=>this.#X(Q,z,Z9("text/html; charset=UTF-8",Z));return typeof $==="object"?z9($,bJ.Stringify,!1,{}).then(Y):Y($)};redirect=($,z)=>{let Z=String($);return this.header("Location",!/[^\x00-\xFF]/.test(Z)?Z:encodeURI(Z)),this.newResponse(null,z??302)};notFound=()=>{return this.#G??=()=>E5(),this.#G(this)}};var m="ALL",vJ="all",_J=["get","post","put","delete","options","patch"],e8="Can not add a route since the matcher is already built.",$6=class extends Error{};var Y9="__COMPOSED_HANDLER";var DB=($)=>{return $.text("404 Not Found",404)},hJ=($,z)=>{if("getResponse"in $){let Z=$.getResponse();return z.newResponse(Z.body,Z)}return console.error($),z.text("Internal Server Error",500)},gJ=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(z={}){[..._J,vJ].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(m,this.#$,K)}),this};let{strict:Y,...Q}=z;Object.assign(this,Q),this.getPath=Y??!0?z.getPath??e3:IJ}#z(){let z=new $({router:this.router,getPath:this.getPath});return z.errorHandler=this.errorHandler,z.#Z=this.#Z,z.routes=this.routes,z}#Z=DB;errorHandler=hJ;route(z,Z){let Y=this.basePath(z);return Z.routes.map((Q)=>{let J;if(Z.errorHandler===hJ)J=Q.handler;else J=async(X,K)=>(await n3([],Z.errorHandler)(X,()=>Q.handler(X,K))).res,J[Y9]=Q.handler;Y.#J(Q.method,Q.path,J)}),this}basePath(z){let Z=this.#z();return Z._basePath=O2(this._basePath,z),Z}onError=(z)=>{return this.errorHandler=z,this};notFound=(z)=>{return this.#Z=z,this};mount(z,Z,Y){let Q,J;if(Y)if(typeof Y==="function")J=Y;else if(J=Y.optionHandler,Y.replaceRequest===!1)Q=(V)=>V;else Q=Y.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]};Q||=(()=>{let V=O2(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 Z(Q(V.req.raw),...X(V));if(H)return H;await G()};return this.#J(m,O2(z,"*"),K),this}#J(z,Z,Y){z=z.toUpperCase(),Z=O2(this._basePath,Z);let Q={basePath:this._basePath,path:Z,method:z,handler:Y};this.router.add(z,Z,[Y,Q]),this.routes.push(Q)}#Q(z,Z){if(z instanceof Error)return this.errorHandler(z,Z);throw z}#Y(z,Z,Y,Q){if(Q==="HEAD")return(async()=>new Response(null,await this.#Y(z,Z,Y,"GET")))();let J=this.getPath(z,{env:Y}),X=this.router.match(Q,J),K=new xJ(z,{path:J,matchResult:X,env:Y,executionCtx:Z,notFoundHandler:this.#Z});if(X[0].length===1){let G;try{G=X[0][0][0][0](K,async()=>{K.res=await this.#Z(K)})}catch(H){return this.#Q(H,K)}return G instanceof Promise?G.then((H)=>H||(K.finalized?K.res:this.#Z(K))).catch((H)=>this.#Q(H,K)):G??this.#Z(K)}let V=n3(X[0],this.errorHandler,this.#Z);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.#Q(G,K)}})()}fetch=(z,...Z)=>{return this.#Y(z,Z[1],Z[0],z.method)};request=(z,Z,Y,Q)=>{if(z instanceof Request)return this.fetch(Z?new Request(z,Z):z,Y,Q);return z=z.toString(),this.fetch(new Request(/^https?:\/\//.test(z)?z:`http://localhost${O2("/",z)}`,Z),Y,Q)};fire=()=>{addEventListener("fetch",(z)=>{z.respondWith(this.#Y(z.request,z,void 0,z.request.method))})}};var R5=[];function z6($,z){let Z=this.buildAllMatchers(),Y=(Q,J)=>{let X=Z[Q]||Z[m],K=X[2][J];if(K)return K;let V=J.match(X[0]);if(!V)return[[],R5];let G=V.indexOf("",1);return[X[1][G],V]};return this.match=Y,Y($,z)}var Z6="[^/]+",L5=".*",F5="(?:|/.*)",N2=Symbol(),IB=new Set(".\\+*[^]$()");function wB($,z){if($.length===1)return z.length===1?$<z?-1:1:-1;if(z.length===1)return 1;if($===L5||$===F5)return 1;else if(z===L5||z===F5)return-1;if($===Z6)return 1;else if(z===Z6)return-1;return $.length===z.length?$<z?-1:1:z.length-$.length}var mJ=class ${#$;#z;#Z=Object.create(null);insert(z,Z,Y,Q,J){if(z.length===0){if(this.#$!==void 0)throw N2;if(J)return;this.#$=Z;return}let[X,...K]=z,V=X==="*"?K.length===0?["","",L5]:["","",Z6]:X==="/*"?["","",F5]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),G;if(V){let H=V[1],W=V[2]||Z6;if(H&&V[2]){if(W===".*")throw N2;if(W=W.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(W))throw N2}if(G=this.#Z[W],!G){if(Object.keys(this.#Z).some((U)=>U!==L5&&U!==F5))throw N2;if(J)return;if(G=this.#Z[W]=new $,H!=="")G.#z=Q.varIndex++}if(!J&&H!=="")Y.push([H,G.#z])}else if(G=this.#Z[X],!G){if(Object.keys(this.#Z).some((H)=>H.length>1&&H!==L5&&H!==F5))throw N2;if(J)return;G=this.#Z[X]=new $}G.insert(K,Z,Y,Q,J)}buildRegExpStr(){let Z=Object.keys(this.#Z).sort(wB).map((Y)=>{let Q=this.#Z[Y];return(typeof Q.#z==="number"?`(${Y})@${Q.#z}`:IB.has(Y)?`\\${Y}`:Y)+Q.buildRegExpStr()});if(typeof this.#$==="number")Z.unshift(`#${this.#$}`);if(Z.length===0)return"";if(Z.length===1)return Z[0];return"(?:"+Z.join("|")+")"}};var uJ=class{#$={varIndex:0};#z=new mJ;insert($,z,Z){let Y=[],Q=[];for(let X=0;;){let K=!1;if($=$.replace(/\{[^}]+\}/g,(V)=>{let G=`@\\${X}`;return Q[X]=[G,V],X++,K=!0,G}),!K)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let X=Q.length-1;X>=0;X--){let[K]=Q[X];for(let V=J.length-1;V>=0;V--)if(J[V].indexOf(K)!==-1){J[V]=J[V].replace(K,Q[X][1]);break}}return this.#z.insert(J,z,Y,this.#$,Z),Y}buildRegExp(){let $=this.#z.buildRegExpStr();if($==="")return[/^$/,[],[]];let z=0,Z=[],Y=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(Q,J,X)=>{if(J!==void 0)return Z[++z]=Number(J),"$()";if(X!==void 0)return Y[Number(X)]=++z,"";return""}),[new RegExp(`^${$}`),Z,Y]}};var SB=[/^$/,[],Object.create(null)],pJ=Object.create(null);function dJ($){return pJ[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(z,Z)=>Z?`\\${Z}`:"(?:|/.*)")}$`)}function kB(){pJ=Object.create(null)}function fB($){let z=new uJ,Z=[];if($.length===0)return SB;let Y=$.map((G)=>[!/\*|\/:/.test(G[0]),...G]).sort(([G,H],[W,U])=>G?1:W?-1:H.length-U.length),Q=Object.create(null);for(let G=0,H=-1,W=Y.length;G<W;G++){let[U,B,C]=Y[G];if(U)Q[B]=[C.map(([M])=>[M,Object.create(null)]),R5];else H++;let N;try{N=z.insert(B,H,U)}catch(M){throw M===N2?new $6(B):M}if(U)continue;Z[H]=C.map(([M,R])=>{let I=Object.create(null);R-=1;for(;R>=0;R--){let[_,T]=N[R];I[_]=T}return[M,I]})}let[J,X,K]=z.buildRegExp();for(let G=0,H=Z.length;G<H;G++)for(let W=0,U=Z[G].length;W<U;W++){let B=Z[G][W]?.[1];if(!B)continue;let C=Object.keys(B);for(let N=0,M=C.length;N<M;N++)B[C[N]]=K[B[C[N]]]}let V=[];for(let G in X)V[G]=Z[X[G]];return[J,V,Q]}function e2($,z){if(!$)return;for(let Z of Object.keys($).sort((Y,Q)=>Q.length-Y.length))if(dJ(Z).test(z))return[...$[Z]];return}var Y6=class{name="RegExpRouter";#$;#z;constructor(){this.#$={[m]:Object.create(null)},this.#z={[m]:Object.create(null)}}add($,z,Z){let Y=this.#$,Q=this.#z;if(!Y||!Q)throw Error(e8);if(!Y[$])[Y,Q].forEach((K)=>{K[$]=Object.create(null),Object.keys(K[m]).forEach((V)=>{K[$][V]=[...K[m][V]]})});if(z==="/*")z="*";let J=(z.match(/\/:/g)||[]).length;if(/\*$/.test(z)){let K=dJ(z);if($===m)Object.keys(Y).forEach((V)=>{Y[V][z]||=e2(Y[V],z)||e2(Y[m],z)||[]});else Y[$][z]||=e2(Y[$],z)||e2(Y[m],z)||[];Object.keys(Y).forEach((V)=>{if($===m||$===V)Object.keys(Y[V]).forEach((G)=>{K.test(G)&&Y[V][G].push([Z,J])})}),Object.keys(Q).forEach((V)=>{if($===m||$===V)Object.keys(Q[V]).forEach((G)=>K.test(G)&&Q[V][G].push([Z,J]))});return}let X=t8(z)||[z];for(let K=0,V=X.length;K<V;K++){let G=X[K];Object.keys(Q).forEach((H)=>{if($===m||$===H)Q[H][G]||=[...e2(Y[H],G)||e2(Y[m],G)||[]],Q[H][G].push([Z,J-V+K+1])})}}match=z6;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#z).concat(Object.keys(this.#$)).forEach((z)=>{$[z]||=this.#Z(z)}),this.#$=this.#z=void 0,kB(),$}#Z($){let z=[],Z=$===m;if([this.#$,this.#z].forEach((Y)=>{let Q=Y[$]?Object.keys(Y[$]).map((J)=>[J,Y[$][J]]):[];if(Q.length!==0)Z||=!0,z.push(...Q);else if($!==m)z.push(...Object.keys(Y[m]).map((J)=>[J,Y[m][J]]))}),!Z)return null;else return fB(z)}};var bB=class{name="PreparedRegExpRouter";#$;#z;constructor($,z){this.#$=$,this.#z=z}#Z($,z){let Z=this.#$[$];Z[1].forEach((Y)=>Y&&Y.push(z)),Object.values(Z[2]).forEach((Y)=>Y[0].push(z))}#J($,z,Z,Y,Q){let J=this.#$[$];if(!Q)J[2][z][0].push([Z,{}]);else Y.forEach((X)=>{if(typeof X==="number")J[1][X].push([Z,Q]);else J[2][X||z][0].push([Z,Q])})}add($,z,Z){if(!this.#$[$]){let Q=this.#$[m],J={};for(let X in Q[2])J[X]=[Q[2][X][0].slice(),R5];this.#$[$]=[Q[0],Q[1].map((X)=>Array.isArray(X)?X.slice():0),J]}if(z==="/*"||z==="*"){let Q=[Z,{}];if($===m)for(let J in this.#$)this.#Z(J,Q);else this.#Z($,Q);return}let Y=this.#z[z];if(!Y)throw Error(`Path ${z} is not registered`);for(let[Q,J]of Y)if($===m)for(let X in this.#$)this.#J(X,z,Z,Q,J);else this.#J($,z,Z,Q,J)}buildAllMatchers(){return this.#$}match=z6};var Q9=class{name="SmartRouter";#$=[];#z=[];constructor($){this.#$=$.routers}add($,z,Z){if(!this.#z)throw Error(e8);this.#z.push([$,z,Z])}match($,z){if(!this.#z)throw Error("Fatal error");let Z=this.#$,Y=this.#z,Q=Z.length,J=0,X;for(;J<Q;J++){let K=Z[J];try{for(let V=0,G=Y.length;V<G;V++)K.add(...Y[V]);X=K.match($,z)}catch(V){if(V instanceof $6)continue;throw V}this.match=K.match.bind(K),this.#$=[K],this.#z=void 0;break}if(J===Q)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 j5=Object.create(null),yB=($)=>{for(let z in $)return!0;return!1},cJ=class ${#$;#z;#Z;#J=0;#Q=j5;constructor(z,Z,Y){if(this.#z=Y||Object.create(null),this.#$=[],z&&Z){let Q=Object.create(null);Q[z]={handler:Z,possibleKeys:[],score:0},this.#$=[Q]}this.#Z=[]}insert(z,Z,Y){this.#J=++this.#J;let Q=this,J=TJ(Z),X=[];for(let K=0,V=J.length;K<V;K++){let G=J[K],H=J[K+1],W=DJ(G,H),U=Array.isArray(W)?W[0]:G;if(U in Q.#z){if(Q=Q.#z[U],W)X.push(W[1]);continue}if(Q.#z[U]=new $,W)Q.#Z.push(W),X.push(W[1]);Q=Q.#z[U]}return Q.#$.push({[z]:{handler:Y,possibleKeys:X.filter((K,V,G)=>G.indexOf(K)===V),score:this.#J}}),Q}#Y(z,Z,Y,Q,J){for(let X=0,K=Z.#$.length;X<K;X++){let V=Z.#$[X],G=V[Y]||V[m],H={};if(G!==void 0){if(G.params=Object.create(null),z.push(G),Q!==j5||J&&J!==j5)for(let W=0,U=G.possibleKeys.length;W<U;W++){let B=G.possibleKeys[W],C=H[G.score];G.params[B]=J?.[B]&&!C?J[B]:Q[B]??J?.[B],H[G.score]=!0}}}}search(z,Z){let Y=[];this.#Q=j5;let J=[this],X=s3(Z),K=[],V=X.length,G=null;for(let H=0;H<V;H++){let W=X[H],U=H===V-1,B=[];for(let N=0,M=J.length;N<M;N++){let R=J[N],I=R.#z[W];if(I)if(I.#Q=R.#Q,U){if(I.#z["*"])this.#Y(Y,I.#z["*"],z,R.#Q);this.#Y(Y,I,z,R.#Q)}else B.push(I);for(let _=0,T=R.#Z.length;_<T;_++){let y=R.#Z[_],d=R.#Q===j5?{}:{...R.#Q};if(y==="*"){let B0=R.#z["*"];if(B0)this.#Y(Y,B0,z,R.#Q),B0.#Q=d,B.push(B0);continue}let[J0,h,q0]=y;if(!W&&!(q0 instanceof RegExp))continue;let i=R.#z[J0];if(q0 instanceof RegExp){if(G===null){G=Array(V);let D0=Z[0]==="/"?1:0;for(let L0=0;L0<V;L0++)G[L0]=D0,D0+=X[L0].length+1}let B0=Z.substring(G[H]),p0=q0.exec(B0);if(p0){if(d[h]=p0[0],this.#Y(Y,i,z,R.#Q,d),yB(i.#z)){i.#Q=d;let D0=p0[0].match(/\//)?.length??0;(K[D0]||=[]).push(i)}continue}}if(q0===!0||q0.test(W))if(d[h]=W,U){if(this.#Y(Y,i,z,d,R.#Q),i.#z["*"])this.#Y(Y,i.#z["*"],z,d,R.#Q)}else i.#Q=d,B.push(i)}}let C=K.shift();J=C?B.concat(C):B}if(Y.length>1)Y.sort((H,W)=>{return H.score-W.score});return[Y.map(({handler:H,params:W})=>[H,W])]}};var J9=class{name="TrieRouter";#$;constructor(){this.#$=new cJ}add($,z,Z){let Y=t8(z);if(Y){for(let Q=0,J=Y.length;Q<J;Q++)this.#$.insert($,Y[Q],Z);return}this.#$.insert($,z,Z)}match($,z){return this.#$.search($,z)}};var P5=class extends gJ{constructor($={}){super($);this.router=$.router??new Q9({routers:[new Y6,new J9]})}};var Q6=($)=>{let Z={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...$},Y=((J)=>{if(typeof J==="string")if(J==="*"){if(Z.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})(Z.origin),Q=((J)=>{if(typeof J==="function")return J;else if(Array.isArray(J))return()=>J;else return()=>[]})(Z.allowMethods);return async function(X,K){function V(H,W){X.res.headers.set(H,W)}let G=await Y(X.req.header("origin")||"",X);if(G)V("Access-Control-Allow-Origin",G);if(Z.credentials)V("Access-Control-Allow-Credentials","true");if(Z.exposeHeaders?.length)V("Access-Control-Expose-Headers",Z.exposeHeaders.join(","));if(X.req.method==="OPTIONS"){if(Z.origin!=="*"||Z.credentials)V("Vary","Origin");if(Z.maxAge!=null)V("Access-Control-Max-Age",Z.maxAge.toString());let H=await Q(X.req.header("origin")||"",X);if(H.length)V("Access-Control-Allow-Methods",H.join(","));let W=Z.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(),Z.origin!=="*"||Z.credentials)X.header("Vary","Origin",{append:!0})}};function A5(){return`<!DOCTYPE html>
|
|
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
300
|
<html lang="pt-BR">
|
|
300
301
|
<head>
|
|
301
302
|
<meta charset="UTF-8">
|
|
@@ -1022,13 +1023,13 @@ ${z.join(`
|
|
|
1022
1023
|
})();
|
|
1023
1024
|
</script>
|
|
1024
1025
|
</body>
|
|
1025
|
-
</html>`}
|
|
1026
|
-
`)}function
|
|
1027
|
-
`)}function
|
|
1028
|
-
`)}function
|
|
1029
|
-
`);return["# Seu Perfil de Energia","",`Sessoes registradas: ${$.totalSessions}`,`Sessao media: ${$.avgSessionMin} min`,`Intervalo medio entre pausas: ${$.avgBreakInterval} min`,`Horarios de pico: ${
|
|
1030
|
-
`)}function
|
|
1031
|
-
`)}
|
|
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(`
|
|
1030
|
+
`);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(`
|
|
1032
1033
|
Add-Type -AssemblyName System.Windows.Forms
|
|
1033
1034
|
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
1034
1035
|
if (-not $img) {
|
|
@@ -1078,8 +1079,8 @@ try {
|
|
|
1078
1079
|
} finally {
|
|
1079
1080
|
if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
|
|
1080
1081
|
}
|
|
1081
|
-
`,{timeout:20000});if(
|
|
1082
|
-
${
|
|
1082
|
+
`,{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 $=`
|
|
1083
1084
|
$sig = @'
|
|
1084
1085
|
[DllImport("user32.dll")]
|
|
1085
1086
|
public static extern IntPtr GetForegroundWindow();
|
|
@@ -1112,9 +1113,9 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
|
|
|
1112
1113
|
$marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
|
|
1113
1114
|
Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
|
|
1114
1115
|
}
|
|
1115
|
-
`;try{let
|
|
1116
|
-
$notificationTitle = '${
|
|
1117
|
-
$notificationText = '${
|
|
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=`
|
|
1117
|
+
$notificationTitle = '${Y}'
|
|
1118
|
+
$notificationText = '${Q}'
|
|
1118
1119
|
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
|
|
1119
1120
|
$template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
|
|
1120
1121
|
$toastXml = [xml]$template.GetXml()
|
|
@@ -1125,64 +1126,64 @@ $xml.LoadXml($toastXml.OuterXml)
|
|
|
1125
1126
|
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
|
1126
1127
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Smolerclaw').Show($toast)
|
|
1127
1128
|
Write-Output 'OK'
|
|
1128
|
-
`;try{let J=await
|
|
1129
|
-
${
|
|
1130
|
-
`)}`}function
|
|
1131
|
-
-> ${X.url}`:"";return` ${J+1}. ${
|
|
1132
|
-
${
|
|
1133
|
-
${
|
|
1134
|
-
`)}`}function
|
|
1135
|
-
`)}var
|
|
1136
|
-
... (output truncated)`}function b5($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function E9($){let z=$.toLowerCase().trim(),Z=new Date;if(z==="hoje")return Z;if(z==="amanha"||z==="amanh\xE3"){let K=new Date(Z);return K.setDate(K.getDate()+1),K}let Y=z.match(/em\s+(\d+)\s*dias?/);if(Y){let K=new Date(Z);return K.setDate(K.getDate()+parseInt(Y[1])),K}let Q=z.match(/em\s+(\d+)\s*semanas?/);if(Q){let K=new Date(Z);return K.setDate(K.getDate()+parseInt(Q[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(Z),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):Z.getFullYear(),H=new Date(G,V,K);if(!isNaN(H.getTime()))return H}return p2(z)}var C6=[{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:[]}}],O6=[{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"]}}],N6=[{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:[]}}],M6=[{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"]}}],E6={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"]}},R6=[{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"]}}],L6=[{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:[]}}],F6=[{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"]}}],j6=[{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"]}}],P6=[{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"]}}],A6=[{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"]}}],T6=[{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"]}}],D6=[{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"]}}],I6=[{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:[]}}],w6=[{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:[]}}],R9=[{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:[]}}],S6=[{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:[]}}],k6=[{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 vX($,z,Z){switch($){case"open_application":return await O1(z.name,z.argument);case"open_file_default":return await q2(z.path);case"open_url_browser":return await t0(z.url);case"get_running_apps":return await M5();case"get_system_info":return await B2();case"get_calendar_events":return await e0();case"get_news":{let Y=z.category;return await H1(Y?[Y]:void 0)}case"create_task":{let Y=z.title;if(!Y?.trim())return"Error: title is required.";let Q=z.time,J=Q?p2(Q):void 0,X=e4(Y,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 Y=z.reference;if(!Y?.trim())return"Error: reference is required.";let Q=$8(Y);return Q?`Concluida: "${Q.title}"`:`Tarefa nao encontrada: "${Y}"`}case"list_tasks":{let Y=z.show_done||!1,Q=c0(Y);return X2(Q)}case"schedule_job":{let{name:Y,time:Q,message:J}=z;if(!Y?.trim()||!Q?.trim()||!J?.trim())return"Error: name, time, and message are required.";let X=U8(Q);if(!X)return`Error: invalid time format "${Q}". 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=B8(H)??void 0;else V=q8(H)??void 0}if(K==="once"&&!V){let H=new Date,[W,U]=X.split(":").map(Number),B=new Date(H);if(B.setHours(W,U,0,0),B<=H)B.setDate(B.getDate()+1);V=[String(B.getMonth()+1).padStart(2,"0"),String(B.getDate()).padStart(2,"0"),String(B.getFullYear())].join("/")}let G=await K8(Y,K,X,"toast",J,V);return`Agendamento criado: "${G.name}" [${G.id}] \u2014 ${G.scheduleType} \xE0s ${G.time}`}case"remove_scheduled_job":{let Y=z.reference;if(!Y?.trim())return"Error: reference is required.";return await V8(Y)?"Agendamento removido.":`Agendamento nao encontrado: "${Y}"`}case"list_scheduled_jobs":{let Y=z.include_disabled||!1,Q=K5(Y);return V5(Q)}case"enable_scheduled_job":{let Y=z.reference;if(!Y?.trim())return"Error: reference is required.";let Q=await G8(Y);return Q?`Agendamento "${Q.name}" ativado.`:`Agendamento nao encontrado: "${Y}"`}case"disable_scheduled_job":{let Y=z.reference;if(!Y?.trim())return"Error: reference is required.";let Q=await H8(Y);return Q?`Agendamento "${Q.name}" desativado.`:`Agendamento nao encontrado: "${Y}"`}case"run_scheduled_job_now":{let Y=z.reference;if(!Y?.trim())return"Error: reference is required.";return await W8(Y)}case"add_person":{let Y=z.name;if(!Y?.trim())return"Error: name is required.";let Q=z.group;if(!["equipe","familia","contato"].includes(Q))return"Error: group must be equipe, familia, or contato.";let X=P8(Y,Q,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} (${Q})${K} [${X.id}]`}case"find_person_info":{let Y=z.name_or_id;if(!Y?.trim())return"Error: name_or_id is required.";let Q=W1(Y);if(!Q)return`Pessoa nao encontrada: "${Y}"`;return I8(Q)}case"list_people":{let Y=z.group,Q=A8(Y);return D8(Q)}case"log_interaction":{let Y=z.person;if(!Y?.trim())return"Error: person is required.";let{type:Q,summary:J}=z;if(!J?.trim())return"Error: summary is required.";let X=z.follow_up,K=X?E9(X):void 0;if(!YQ(Y,Q,J,K||void 0))return`Pessoa nao encontrada: "${Y}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${Q} com ${Y}${G}`}case"delegate_to_person":{let Y=z.person;if(!Y?.trim())return"Error: person is required.";let Q=z.task;if(!Q?.trim())return"Error: task is required.";let J=z.due_date,X=J?E9(J):void 0,K=T8(Y,Q,X||void 0);if(!K)return`Pessoa nao encontrada: "${Y}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Y}: "${Q}"${V} [${K.id}]`}case"update_delegation_status":{let Y=z.delegation_id;if(!Y?.trim())return"Error: delegation_id is required.";let Q=z.status,J=QQ(Y,Q,z.notes);if(!J)return`Delegacao nao encontrada: "${Y}"`;return`Delegacao atualizada: "${J.task}" -> ${Q}`}case"get_people_dashboard":return XQ();case"save_memo":{let Y=z.content;if(!Y?.trim())return"Error: content is required.";let Q=z.tags||[],J=J5(Y,Q);return`Memo salvo${J.tags.length>0?` [${J.tags.map((K)=>"#"+K).join(" ")}]`:""} {${J.id}}`}case"search_memos":{let Y=z.query;if(!Y?.trim())return K2(X5());let Q=z8(Y);return K2(Q)}case"record_transaction":{let{type:Y,amount:Q,category:J,description:X}=z;if(!Y||!Q||!J||!X)return"Error: all fields required.";let K=H5(Y,Q,J,X);if(!K.allowed)return`Error: ${K.blocked}`;let V=G5(Y,Q,J,X);W5(Y,Q,J);let G=V.type==="entrada"?"+":"-",H=U5(K);return`${G} R$ ${V.amount.toFixed(2)} (${V.category}) \u2014 ${V.description} [${V.id}]${H?`
|
|
1137
|
-
`+H:""}`}case"financial_summary":return
|
|
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}):
|
|
1130
|
+
${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}
|
|
1133
|
+
${z.reason}${V} {${X.id}}`});return`${Y}
|
|
1134
|
+
${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
1139
|
|
|
1139
|
-
${V}`}case"save_material":{let
|
|
1140
|
-
Esse tipo de operacao nao e permitido.`;if(!
|
|
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:
|
|
1141
1142
|
${J.stdout.trim()}`);if(J.stderr.trim())X.push(`stderr:
|
|
1142
1143
|
${J.stderr.trim()}`);return X.push(`exit: ${J.exitCode} (${J.duration}ms)`),X.join(`
|
|
1143
1144
|
|
|
1144
|
-
`)}case"analyze_screen_context":return await
|
|
1145
|
-
${
|
|
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}
|
|
1146
1147
|
|
|
1147
|
-
${V.markdown}`;return V.markdown}case"manage_work_session":{let
|
|
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.
|
|
1148
1149
|
|
|
1149
|
-
${G.markdown}`}return
|
|
1150
|
-
`+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let H=K?
|
|
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":""})
|
|
1151
1152
|
Duracao: ${W.toFixed(2)}ms
|
|
1152
1153
|
Memoria: ${(H.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
|
|
1153
|
-
CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return
|
|
1154
|
-
${
|
|
1155
|
-
`)}`}case"evaluate_architecture_tradeoffs":{let
|
|
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}):
|
|
1155
|
+
${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}}
|
|
1156
1157
|
Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
|
|
1157
|
-
Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let
|
|
1158
|
-
Arquivo: ${K.path}`}case"explain_optimal_usage":{let
|
|
1159
|
-
\uD83D\uDDFA\uFE0F Abra ${
|
|
1160
|
-
`)}case"get_neighborhood":{let
|
|
1161
|
-
`)}case"add_poi":{let{neighborhood:
|
|
1162
|
-
`);return
|
|
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+`
|
|
1163
1164
|
|
|
1164
|
-
\uD83D\uDCDD Relatorio salvo como memo (tags: lokaliza, ${
|
|
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(`
|
|
1165
1166
|
|
|
1166
|
-
`)}case"check_energy":{
|
|
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}%)
|
|
1167
1168
|
${X}`});return`Resultados da memoria (${$.length}):
|
|
1168
1169
|
|
|
1169
|
-
${
|
|
1170
|
+
${Z.join(`
|
|
1170
1171
|
|
|
1171
|
-
`)}`}function
|
|
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}
|
|
1172
1173
|
${V}
|
|
1173
|
-
${K.content}${G}`}}catch{}let
|
|
1174
|
-
`)}}catch{}let
|
|
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(`
|
|
1175
1176
|
---
|
|
1176
|
-
`);if(G.length>0)$[`session:${V.id}`]=G}catch{}}}catch{}return $}function
|
|
1177
|
-
`)[0];return
|
|
1178
|
-
`)[0];return
|
|
1179
|
-
Chunks: ${
|
|
1180
|
-
Fontes: ${
|
|
1181
|
-
Ultima indexacao: ${
|
|
1182
|
-
`):" (nenhuma)",
|
|
1183
|
-
`):" (nenhum identificado)";return[`**Objetivo:** ${$.objective}`,"",`**Complexidade:** ${$.complexity}`,"","**Estrat\xE9gia T\xE9cnica:**",...
|
|
1184
|
-
`)}function
|
|
1185
|
-
`)}function $
|
|
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(`
|
|
1178
|
+
`)[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:
|
|
1180
|
+
Chunks: ${Y.chunks}
|
|
1181
|
+
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(`
|
|
1183
|
+
`):" (nenhuma)",Q=$.risks.length>0?$.risks.map((z)=>` - ${z}`).join(`
|
|
1184
|
+
`):" (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`
|
|
1186
1187
|
## Protocolo de Alta Ag\xEAncia
|
|
1187
1188
|
|
|
1188
1189
|
Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
|
|
@@ -1224,54 +1225,186 @@ Ao usar \`propose_plan\`, estruture assim:
|
|
|
1224
1225
|
- **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
|
|
1225
1226
|
- **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
|
|
1226
1227
|
- **Bloqueio**: Sempre termine com "Posso prosseguir com este plano?"
|
|
1227
|
-
`.trim()}var
|
|
1228
|
-
|
|
1229
|
-
${
|
|
1230
|
-
|
|
1231
|
-
Execu\xE7\xE3o: ${
|
|
1232
|
-
Motivo: ${
|
|
1233
|
-
`)}case"complete_plan_step":{if(!
|
|
1234
|
-
Pr\xF3ximo passo: ${
|
|
1235
|
-
Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${
|
|
1236
|
-
${J}${X}`}case"get_current_plan":{if(!
|
|
1237
|
-
`)}default:return null}}
|
|
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.
|
|
1229
|
+
|
|
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)}
|
|
1231
|
+
|
|
1232
|
+
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?`
|
|
1235
|
+
Pr\xF3ximo passo: ${Q.nextStep.action} \u2192 ${Q.nextStep.target}`:`
|
|
1236
|
+
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(`
|
|
1239
|
+
`);if(V.includes("invalid_grant")||V.includes("AADSTS"))return`Login failed: ${V.split(`
|
|
1240
|
+
`)[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(`
|
|
1242
|
+
`)}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.
|
|
1256
|
+
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:
|
|
1258
|
+
|
|
1259
|
+
`+z+`
|
|
1260
|
+
|
|
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
|
|
1262
|
+
${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=`
|
|
1265
|
+
=== Microsoft 365 Commands ===
|
|
1266
|
+
|
|
1267
|
+
Auth:
|
|
1268
|
+
/m365 login [appId] Connect (device code flow)
|
|
1269
|
+
/m365 consent Grant API permissions
|
|
1270
|
+
/m365 status Connection status
|
|
1271
|
+
/m365 logout Disconnect
|
|
1272
|
+
/m365 refresh Clear cache
|
|
1273
|
+
|
|
1274
|
+
Email:
|
|
1275
|
+
/m365 emails List inbox emails
|
|
1276
|
+
/m365 email read <id> Read specific email
|
|
1277
|
+
/m365 email send --to <email> --subject <text> --body <text>
|
|
1278
|
+
|
|
1279
|
+
Calendar:
|
|
1280
|
+
/m365 calendar List events
|
|
1281
|
+
/m365 calendar add --subject <text> --start <dt> --end <dt>
|
|
1282
|
+
|
|
1283
|
+
Contacts:
|
|
1284
|
+
/m365 contacts List contacts
|
|
1285
|
+
|
|
1286
|
+
To Do:
|
|
1287
|
+
/m365 todo List tasks
|
|
1288
|
+
/m365 todo add <title> Create task
|
|
1289
|
+
/m365 todo done <id> Complete task
|
|
1290
|
+
/m365 todo lists List task lists
|
|
1291
|
+
|
|
1292
|
+
OneDrive:
|
|
1293
|
+
/m365 onedrive [folder] List files
|
|
1294
|
+
/m365 onedrive get <path>
|
|
1295
|
+
|
|
1296
|
+
OneNote:
|
|
1297
|
+
/m365 onenote List notebooks
|
|
1298
|
+
/m365 onenote pages <nb> List pages
|
|
1299
|
+
|
|
1300
|
+
Composite:
|
|
1301
|
+
/m365 briefing Emails + calendar + todos
|
|
1302
|
+
/m365 digest Weekly activity summary
|
|
1303
|
+
/m365 search <query> Search across services
|
|
1304
|
+
|
|
1305
|
+
Flags: --fresh (skip cache)
|
|
1306
|
+
===============================
|
|
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 $?.(`
|
|
1308
|
+
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(`
|
|
1311
|
+
`);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(`
|
|
1313
|
+
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
|
+
`);return Z(`
|
|
1315
|
+
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(`
|
|
1318
|
+
Opening browser for authentication...`),Y(`(URL: ${V.slice(0,60)}...)
|
|
1319
|
+
`);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(`
|
|
1322
|
+
`)}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.
|
|
1330
|
+
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}
|
|
1332
|
+
Credentials will be injected automatically.
|
|
1333
|
+
Run /gws login to authenticate.`);else Z.showError(`\u2717 client_secret.json not found.
|
|
1334
|
+
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
|
|
1336
|
+
${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=`
|
|
1339
|
+
=== Google Workspace Commands ===
|
|
1340
|
+
|
|
1341
|
+
Auth:
|
|
1342
|
+
/gws setup First-time setup (auto, falls back to guided)
|
|
1343
|
+
/gws setup-guide Guided setup: enable APIs via gcloud + OAuth instructions
|
|
1344
|
+
/gws check Check if client_secret.json is in place
|
|
1345
|
+
/gws login [scopes] Connect (e.g. gmail,calendar,drive)
|
|
1346
|
+
/gws status Connection status
|
|
1347
|
+
/gws logout Disconnect
|
|
1348
|
+
/gws refresh Clear cache
|
|
1349
|
+
|
|
1350
|
+
Gmail:
|
|
1351
|
+
/gws emails List inbox emails
|
|
1352
|
+
/gws gmail read <id> Read specific email
|
|
1353
|
+
/gws gmail send --to <email> --subject <text> --body <text>
|
|
1354
|
+
|
|
1355
|
+
Calendar:
|
|
1356
|
+
/gws calendar List today's events
|
|
1357
|
+
/gws calendar add --summary <text> --start <dt> --end <dt>
|
|
1358
|
+
|
|
1359
|
+
Drive:
|
|
1360
|
+
/gws drive [folderId] List files
|
|
1361
|
+
/gws drive search <query>
|
|
1362
|
+
|
|
1363
|
+
Composite:
|
|
1364
|
+
/gws briefing Gmail + Calendar + Drive summary
|
|
1365
|
+
/gws dashboard Multi-panel overview
|
|
1366
|
+
/gws search <query> Search across Gmail and Drive
|
|
1367
|
+
|
|
1368
|
+
Flags: --fresh (skip cache), --top N (limit)
|
|
1369
|
+
=================================
|
|
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?`
|
|
1238
1371
|
`:"")+K.trim();if(V!==0)G+=(G?`
|
|
1239
|
-
`:"")+`Exit code: ${V}`;return G||"(no output)"}function
|
|
1240
|
-
`)[0]||`exit code ${
|
|
1241
|
-
export { default } from '${
|
|
1242
|
-
`;Bun.write(W,M)}else{let
|
|
1243
|
-
`)}async function
|
|
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}
|
|
1374
|
+
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,`
|
|
1244
1377
|
`).replace(/<(br|hr)[^>]*\/?>/gi,`
|
|
1245
1378
|
`).replace(/<[^>]+>/g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
1246
1379
|
|
|
1247
|
-
`).trim()}function
|
|
1248
|
-
`),K=Math.max(1,$.offset||1),V=Math.min(2000,$.limit||500),W=X.slice(K-1,K-1+V).map((
|
|
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(`
|
|
1249
1382
|
`),U=X.length-(K-1+V);if(U>0)W+=`
|
|
1250
|
-
... (${U} more lines, total ${X.length})`;return
|
|
1251
|
-
`).length;return`${X?"Updated":"Created"}: ${
|
|
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(`
|
|
1252
1385
|
`).length,W=K.split(`
|
|
1253
|
-
`).length;return`Edited: ${
|
|
1254
|
-
`);for(let
|
|
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(`
|
|
1255
1388
|
`);if(X.length>100)G+=`
|
|
1256
|
-
... (showing first 100 matches)`;return
|
|
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(`
|
|
1257
1390
|
`);if(X.length>=200)K+=`
|
|
1258
|
-
... (showing first 200 files)`;return K}function
|
|
1259
|
-
`)}function
|
|
1260
|
-
`).map((G)=>{if(G.startsWith(
|
|
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(`
|
|
1393
|
+
`).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(`
|
|
1261
1394
|
`);if(K>100)V+=`
|
|
1262
|
-
... (${K-100} more matches)`;return
|
|
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?`
|
|
1263
1396
|
`:"")+`STDERR:
|
|
1264
1397
|
`+V.trim();if(G!==0)H+=(H?`
|
|
1265
|
-
`:"")+`Exit code: ${G}`;return
|
|
1266
|
-
(Use fetch_url on the redirect target if needed)`}let G=`${V.status} ${V.statusText}`,H=V.headers.get("content-type")||"";if(
|
|
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(`
|
|
1267
1400
|
`);return`Status: ${G}
|
|
1268
|
-
${
|
|
1401
|
+
${q}`}let W=V.headers.get("content-length");if(W&&Number(W)>N3*2)return`Status: ${G}
|
|
1269
1402
|
|
|
1270
|
-
Error: response body too large (${W} bytes). Max is ${
|
|
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}
|
|
1271
1404
|
|
|
1272
|
-
${
|
|
1405
|
+
${q}`)}return H1(`Status: ${G}
|
|
1273
1406
|
|
|
1274
|
-
${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
|
|
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:
|
|
1275
1408
|
1. Key decisions made
|
|
1276
1409
|
2. Files created or modified
|
|
1277
1410
|
3. Important context the user shared
|
|
@@ -1280,35 +1413,35 @@ ${U}`)}catch(X){if(X instanceof Error&&X.name==="AbortError")return"Error: Reque
|
|
|
1280
1413
|
Be brief but preserve actionable information. Output ONLY the summary.
|
|
1281
1414
|
|
|
1282
1415
|
---
|
|
1283
|
-
${$.map((
|
|
1284
|
-
Tools used: ${
|
|
1416
|
+
${$.map((Y)=>{let Q=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)Q+=`
|
|
1417
|
+
Tools used: ${Y.toolCalls.map((z)=>z.name).join(", ")}`;return Q}).join(`
|
|
1285
1418
|
|
|
1286
|
-
`)}`}function
|
|
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(`
|
|
1287
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(`
|
|
1288
|
-
`);return{...
|
|
1289
|
-
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${
|
|
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.
|
|
1290
1423
|
Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
|
|
1291
|
-
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 Y
|
|
1292
|
-
`)[0]||"",
|
|
1293
|
-
`).length;return`PowerShell (${
|
|
1294
|
-
`),
|
|
1295
|
-
`),J=[],X=
|
|
1296
|
-
${await this.generateSummary(V.toSummarize)}`,timestamp:Date.now()};
|
|
1297
|
-
`);K=U.pop()||"";for(let
|
|
1298
|
-
`)}function
|
|
1299
|
-
`)}function
|
|
1300
|
-
`)}try{let
|
|
1301
|
-
`),J=
|
|
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(`
|
|
1425
|
+
`)[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(`
|
|
1427
|
+
`),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(`
|
|
1434
|
+
`),J=z.slice(0,15);if(z.length>15)J.push(`... and ${z.length-15} more files`);Z.push(`Uncommitted changes:
|
|
1302
1435
|
`+J.join(`
|
|
1303
|
-
`))}}}catch(
|
|
1304
|
-
`).slice(0,10);
|
|
1305
|
-
`+
|
|
1306
|
-
`))}}}catch(
|
|
1307
|
-
`):null}function
|
|
1308
|
-
`+$.map((
|
|
1309
|
-
`)}function
|
|
1310
|
-
ALWAYS respond in ${J}. This is a hard requirement.`)}if(
|
|
1311
|
-
`+
|
|
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(`
|
|
1437
|
+
`).slice(0,10);Z.push(`Staged:
|
|
1438
|
+
`+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:
|
|
1441
|
+
`+$.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(`---
|
|
1312
1445
|
## Meta-Learning & Self-Awareness
|
|
1313
1446
|
You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
|
|
1314
1447
|
|
|
@@ -1324,109 +1457,115 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
|
|
|
1324
1457
|
|
|
1325
1458
|
**Self-Reflection:**
|
|
1326
1459
|
- At session end or when explicitly asked, run self-reflection to generate insights.
|
|
1327
|
-
- Share relevant insights proactively when they might help the current task.`),
|
|
1460
|
+
- Share relevant insights proactively when they might help the current task.`),Q.push(`---
|
|
1328
1461
|
## Environment
|
|
1329
1462
|
The user's current working directory and project info. Use this context when they ask about code or files.
|
|
1330
1463
|
|
|
1331
|
-
`+
|
|
1332
|
-
`+$);return
|
|
1464
|
+
`+WH()),$)Q.push(`## User Instructions
|
|
1465
|
+
`+$);return Q.join(`
|
|
1333
1466
|
|
|
1334
|
-
`)}async function
|
|
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}
|
|
1335
1468
|
|
|
1336
|
-
${U}`:X;return{sessions:
|
|
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}
|
|
1337
1470
|
|
|
1338
|
-
${H}`:H}if(!X.trim())console.error("smolerclaw: no input provided"),process.exit(1);let K={role:"user",content:X.trim(),timestamp:Date.now()};
|
|
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(`
|
|
1339
1472
|
smolerclaw error: ${H.error}`);if(V&&!V.endsWith(`
|
|
1340
1473
|
`))process.stdout.write(`
|
|
1341
|
-
`);let G={role:"assistant",content:V,timestamp:Date.now()};
|
|
1342
|
-
`)){if(
|
|
1343
|
-
`),
|
|
1344
|
-
`).filter(Boolean).slice(
|
|
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(`
|
|
1345
1478
|
`)+`
|
|
1346
|
-
`)}catch{}}}import{join as VN}from"path";var iO=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],rO=" ";function zz($,z={}){let{width:Z=$.length,min:Y=Math.min(...$),max:Q=Math.max(...$),color:J="",showBounds:X=!1}=z;if($.length===0)return"";let K=JN($,Z),V=Q-Y||1,H=K.map((U)=>{if(U===0&&Y===0)return rO;let B=(U-Y)/V,C=Math.min(7,Math.floor(B*8));return iO[C]}).join(""),W=J?`${J}${H}${q.reset}`:H;if(X)return`${q.dim}${Y.toFixed(0)}${q.reset}${W}${q.dim}${Q.toFixed(0)}${q.reset}`;return W}var nO="\u2588",aO="\u2589",sO="\u258A",tO="\u258B",eO="\u258C",$N="\u258D",zN="\u258E",ZN="\u258F",YN="\u2591",QN=[" ",ZN,zN,$N,eO,tO,sO,aO];function Zz($,z={}){let{width:Z=20,maxValue:Y=100,showValue:Q=!0,color:J=q.fg(75),label:X=""}=z,K=Math.min(1,Math.max(0,$/Y)),V=Math.floor(K*Z),G=K*Z-V,H=Math.floor(G*8),W=nO.repeat(V);if(H>0&&V<Z)W+=QN[H];let U=Z-E0(W);W+=YN.repeat(Math.max(0,U));let B=J?`${J}${W}${q.reset}`:W,C=[];if(X)C.push(`${q.dim}${X.padEnd(12)}${q.reset}`);if(C.push(B),Q)C.push(` ${q.dim}${$.toFixed(1)}%${q.reset}`);return C.join("")}function d5($,z){let Z=[];if(Z.push(`${w.ai}${$.model}${q.reset}`),$.project)Z.push(`${w.heading}${$.project}${q.reset}`);if($.tokens){let{input:X,output:K}=$.tokens;Z.push(`${q.dim}${WV(X)}/${WV(K)} tok${q.reset}`)}if($.sessionCost)Z.push(`${q.dim}${$.sessionCost}${q.reset}`);if($.vaultStatus){let X=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",K=$.vaultStatus==="ok"?q.fg(114):$.vaultStatus==="warn"?q.fg(220):q.fg(196);Z.push(`${K}${X}${q.reset}`)}if($.customItems)for(let X of $.customItems){let K=X.color||"";Z.push(`${q.dim}${X.label}:${q.reset}${K}${X.value}${q.reset}`)}let Y=Z.join(` ${q.dim}\u2502${q.reset} `),Q=E0(Y),J=Math.max(0,z-Q-2);return`${q.inv} ${Y}${" ".repeat(J)} ${q.reset}`}function Yz($,z=40){let Z=[];Z.push(`${q.dim}${"\u2500".repeat(z)}${q.reset}`),Z.push(`${w.heading}${q.bold} System${q.reset}`);let Y=zz($.cpu,{width:15,color:q.fg(75)}),Q=Zz($.currentCpu,{width:10,showValue:!1,color:q.fg(75)});Z.push(` ${q.dim}CPU:${q.reset} ${Y} ${Q} ${$.currentCpu.toFixed(0)}%`);let J=zz($.memory,{width:15,color:q.fg(114)}),X=Zz($.currentMem,{width:10,showValue:!1,color:q.fg(114)});return Z.push(` ${q.dim}MEM:${q.reset} ${J} ${X} ${$.currentMem.toFixed(0)}%`),Z.push(`${q.dim}${"\u2500".repeat(z)}${q.reset}`),Z}function JN($,z){if($.length<=z){let Q=[...$];while(Q.length<z)Q.unshift(0);return Q}let Z=$.length/z,Y=[];for(let Q=0;Q<z;Q++){let J=Math.floor(Q*Z),X=Math.floor((Q+1)*Z),K=$.slice(J,X),V=K.reduce((G,H)=>G+H,0)/K.length;Y.push(V)}return Y}function WV($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function c5($,z,Z={}){let{title:Y="",padding:Q=1,borderColor:J=q.dim,titleColor:X=w.heading}=Z,K=z-2-Q*2,V=[];if(Y){let H=E0(Y),W=2,U=Math.max(1,z-H-2-4);V.push(`${J}\u250C${"\u2500".repeat(2)}${q.reset}${X}${q.bold} ${Y} ${q.reset}${J}${"\u2500".repeat(U)}\u2510${q.reset}`)}else V.push(`${J}\u250C${"\u2500".repeat(z-2)}\u2510${q.reset}`);let G=" ".repeat(Q);for(let H of $){let W=E0(H)>K?i1(H,K):[H];for(let U of W){let B=E0(U),C=Math.max(0,K-B);V.push(`${J}\u2502${q.reset}${G}${U}${" ".repeat(C)}${G}${J}\u2502${q.reset}`)}}return V.push(`${J}\u2514${"\u2500".repeat(z-2)}\u2518${q.reset}`),V}function Qz($,z,Z,Y,Q={}){let J=c5($,Y,Q);for(let X=0;X<J.length;X++)E(q.to(z+X,Z)),E(J[X])}var s6={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},XN={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function Jz($,z={}){let{width:Z=60,showActions:Y=!0,compact:Q=!1}=z,J=[],X=XN[$.category]||"\uD83D\uDCA1",K=s6.dimYellow+s6.italic;if(Q){let H=$.title.length>Z-10?$.title.slice(0,Z-13)+"...":$.title;return J.push(` ${K}${X} ${H}${q.reset}`),J}J.push(` ${K}${X} ${$.title}${q.reset}`);let V=Z-6,G=i1($.explanation,V);for(let H of G)J.push(` ${K} ${o1(H)}${q.reset}`);if($.suggestedAction)J.push(` ${s6.dimCyan} \u2192 ${$.suggestedAction.label}${q.reset}`);if(Y)J.push(` ${q.dim} [Y] Aceitar [N] Ignorar${q.reset}`);return J}function UV($,z=40){let Z=[],Y=[...$].sort((Q,J)=>J.frequency-Q.frequency).slice(0,3);if(Y.length===0)return Z.push(`${q.dim} Nenhuma dica disponivel ainda.${q.reset}`),Z.push(`${q.dim} Continue usando para gerar insights.${q.reset}`),Z;for(let Q=0;Q<Y.length;Q++){let J=Y[Q],X=Q+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;Z.push(`${K} ${s6.dimYellow}${G}${q.reset}`);let H=z-4,W=J.description.length>H?J.description.slice(0,H-3)+"...":J.description;Z.push(` ${q.dim}${W}${q.reset}`);let U=J.frequency===1?"vez":"vezes";if(Z.push(` ${q.dim}Detectado ${J.frequency}x${q.reset}`),Q<Y.length-1)Z.push("")}return Z}function t6($,z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:UV($,z)}}class l5{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(q.to($,1)),E(d5(this.statusConfig,this.width))}clearScreen(){E(q.clear),E(q.to(1,1))}clearContentArea(){let $=this.getViewState();for(let z=$.contentStartRow;z<=$.contentEndRow;z++)E(q.to(z,1)),E(q.clearLine)}updateDimensions($,z){this.width=$,this.height=z;for(let Z of this.resizeCallbacks)Z()}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:Z=1}=this.dashboardLayout,Y=this.getViewState(),Q=Y.contentEndRow-Y.contentStartRow,J=Math.floor((this.width-Z*(z+1))/z),X=Y.contentStartRow,K=1+Z;for(let V=0;V<$.length;V++){let G=$[V],H=G.row??X,W=G.col??K,U=G.width??J,B=G.height??Math.floor(Q/Math.ceil($.length/z));if(this.drawDashboardPanel(G,H,W,U,B),(V+1)%z===0)X+=B+Z,K=1+Z;else K+=U+Z}this.renderStatusBar()}drawDashboardPanel($,z,Z,Y,Q){let J=Q-2,X=$.content.slice(0,J);Qz(X,z,Z,Y,{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:Yz($,35)}],columns:1,gap:1}}}function e6($,z){E(`\x1B[${$};${z}r`)}function $7(){E("\x1B[r")}var KN=new l5;r0();class Xz{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=s9("productivity");timeContext=null;commands=["/help","/clear","/commit","/persona","/copy","/fork","/new","/load","/sessions","/delete","/model","/export","/cost","/retry","/undo","/search","/lang","/config","/exit","/briefing","/news","/open","/openfile","/openurl","/apps","/sysinfo","/calendar","/ask","/budget","/plugins","/task","/tasks","/done","/rmtask","/people","/team","/family","/person","/addperson","/delegate","/delegations","/followups","/dashboard","/contacts","/investigar","/investigate","/investigacoes","/monitor","/vigiar","/workflow","/fluxo","/macro","/macros","/atalho","/atalhos","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/index","/indexar","/reindex","/memory","/memoria","/clipboard","/area","/tela","/screen","/ps1","/refresh","/renovar","/vault","/backup","/feeds","/fontes","/addfeed","/novafonte","/rmfeed","/rmfonte","/disablefeed","/desativarfonte","/enablefeed","/ativarfonte","/projeto","/project","/projetos","/projects","/sessao","/session","/relatorio","/report","/oportunidades","/opportunities","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];subcommands={"/model":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/modelo":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/news":["business","tech","finance","brazil","world","security"],"/noticias":["business","tech","finance","brazil","world","security"],"/open":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/abrir":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/sessao":["start","stop","status"],"/session":["start","stop","status"],"/relatorio":["today","week","month"],"/report":["today","week","month"],"/projeto":["auto"],"/project":["auto"],"/oportunidades":["nova","em_analise","aceita","recusada","concluida"],"/opportunities":["nova","em_analise","aceita","recusada","concluida"],"/persona":["default","business"],"/modo":["default","business"],"/people":["equipe","familia","contato"],"/pessoas":["equipe","familia","contato"],"/investigar":["bug","feature","test","audit","incident"],"/investigate":["bug","feature","test","audit","incident"],"/entrada":[],"/saida":[],"/lang":["pt","en","auto"],"/idioma":["pt","en","auto"],"/pomodoro":["start","stop","status"],"/foco":["start","stop","status"],"/monitor":["start","stop","list"],"/vigiar":["start","stop","list"],"/vault":["status","backup","sync","init"],"/workflow":["list","run","info","create","delete","enable","disable"],"/fluxo":["list","run","info","create","delete","ativar","desativar"],"/macro":["list","all","info","create","delete","enable","disable"],"/macros":["list","all","info","create","delete","enable","disable"],"/atalho":["list","all","info","criar","deletar","ativar","desativar"],"/atalhos":["list","all","info","criar","deletar","ativar","desativar"]};onSubmit=null;onCancel=null;onExit=null;pickerActive=!1;lastCtrlCTime=0;eventUnsubscribers=[];statusBarContext="";activeInsight=null;insightSnippetLines=0;insightDisplayed=!1;metaLearningEntries=[];constructor($,z,Z="",Y){this.model=$;this.sessionName=z;this.authInfo=Z;this.dataDir=Y;this.viewManager=new l5}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 $z(VN(this.dataDir,"history"));this.setupEventListeners(),E(q.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"?w.err:$.level==="warning"?w.prompt:$.level==="success"?w.sys:q.dim;if(this.lines.push({text:` ${z}[${$.source}]${q.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z0.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${w.prompt}\u26A0 ${$.message}${q.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${w.err}\u26A0 Rate limit: ${$.message}${q.reset}`});else this.lines.push({text:` ${q.dim}[telemetry] ${$.message}${q.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z0.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${q.dim}[backup] ${$.message||"Backup concluido"}${q.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${w.sys}[pomodoro] ${$.message}${q.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${w.err}[${$.taskType}] ${$.message}${q.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(q.show),E(q.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=a6(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=a6(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 Z=z,Y;switch($){case"read_file":if(Y=String(Z.path||""),Z.offset)Y+=`:${Z.offset}`;break;case"write_file":case"edit_file":Y=String(Z.path||"");break;case"search_files":if(Y=`/${Z.pattern||""}/`,Z.include)Y+=` (${Z.include})`;break;case"find_files":Y=String(Z.pattern||"");break;case"list_directory":Y=String(Z.path||".");break;case"run_command":if(Y=String(Z.command||""),Y.length>80)Y=Y.slice(0,77)+"...";break;default:{let Q=JSON.stringify(Z);Y=Q.length>80?Q.slice(0,77)+"...":Q}}this.lines.push({text:` ${w.tool}\u2699 ${$}${q.reset} ${q.dim}${Y}${q.reset}`}),this.renderMessages()}showToolResult($,z){let Z=z.split(`
|
|
1347
|
-
`),
|
|
1348
|
-
`)process.stdin.removeListener("data",
|
|
1349
|
-
`){if(W.length>0&&
|
|
1350
|
-
`||
|
|
1351
|
-
`){if(
|
|
1352
|
-
`))
|
|
1353
|
-
`){
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
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}
|
|
1488
|
+
${U.join(`
|
|
1489
|
+
`)}${q}`}}let C=this.subcommands[H];return{value:H+(C?.length?" ":" "),options:`${N}${W?" "+W:""}
|
|
1490
|
+
${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===`
|
|
1492
|
+
`){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}
|
|
1494
|
+
Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${Y}
|
|
1495
|
+
\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(`
|
|
1497
|
+
--- 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
|
+
--- 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
|
+
--- 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`
|
|
1362
1501
|
--- Fim de Semana Livre ---
|
|
1363
1502
|
|
|
1364
1503
|
[A] Amolar o Machado
|
|
1365
1504
|
Estudo de arquitetura, refatoracao, melhoria do CLI
|
|
1366
1505
|
|
|
1367
1506
|
[B] Descompressao Criativa
|
|
1368
|
-
Projetos paralelos sem prazo, foco pessoal/familia`}function
|
|
1507
|
+
Projetos paralelos sem prazo, foco pessoal/familia`}function FF($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
|
|
1369
1508
|
--- Sugestao: Timebox ---
|
|
1370
|
-
Liquidar pendencias em ${Math.min(90,
|
|
1371
|
-
Depois: descanso merecido.`}async function
|
|
1509
|
+
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(`
|
|
1372
1511
|
--- Agenda ---
|
|
1373
|
-
${J}`)}catch{
|
|
1512
|
+
${J}`)}catch{Z.push(`
|
|
1374
1513
|
--- Agenda ---
|
|
1375
|
-
Outlook nao disponivel.`)}if(
|
|
1514
|
+
Outlook nao disponivel.`)}if(R)try{let J=await m2();Z.push(`
|
|
1376
1515
|
--- Sistema ---
|
|
1377
|
-
${J}`)}catch(J){
|
|
1378
|
-
${J}`)}catch{
|
|
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(`
|
|
1517
|
+
${J}`)}catch{Z.push(`
|
|
1379
1518
|
--- Noticias ---
|
|
1380
|
-
Falha ao carregar noticias.`)}return
|
|
1381
|
-
======================`),
|
|
1382
|
-
`)}
|
|
1519
|
+
Falha ao carregar noticias.`)}return Z.push(`
|
|
1520
|
+
======================`),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}):
|
|
1383
1522
|
${$.join(`
|
|
1384
|
-
`)}`}function
|
|
1385
|
-
`)}function
|
|
1386
|
-
`);let
|
|
1387
|
-
--- Tarefas do dia ---`),$.push(
|
|
1388
|
-
--- Follow-ups pendentes ---`),$.push(
|
|
1389
|
-
--- Delegacoes atrasadas ---`),$.push(
|
|
1390
|
-
${G}`);if(
|
|
1391
|
-
--- Agenda ---`),$.push(U)}catch{}try{let U=await
|
|
1392
|
-
`+U)}catch{}let H=
|
|
1393
|
-
--- Lokaliza ---`);let U=H.reduce((C
|
|
1394
|
-
${W.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);try{let U=
|
|
1395
|
-
--- Energia ---`),$.push(
|
|
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(`
|
|
1396
1535
|
${U.blockedToday} notificacao(oes) filtrada(s) hoje pelo modo foco.`)}catch{}return $.push(`
|
|
1397
1536
|
==============================`),$.join(`
|
|
1398
|
-
`)}
|
|
1399
|
-
${" ".repeat(4)}${X} {${
|
|
1400
|
-
${
|
|
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}
|
|
1538
|
+
${" ".repeat(4)}${X} {${Q.id}}`});return`Workflows (${Z.length}):
|
|
1539
|
+
${Y.join(`
|
|
1401
1540
|
|
|
1402
|
-
`)}`}function
|
|
1403
|
-
`)}function
|
|
1404
|
-
`)}function
|
|
1405
|
-
[${X}]`);for(let K of
|
|
1406
|
-
[outros]`);for(let X of
|
|
1407
|
-
Uso: /macro <nome> para executar`),
|
|
1408
|
-
`)}function
|
|
1409
|
-
`)}function
|
|
1410
|
-
*** ${
|
|
1411
|
-
`)),
|
|
1412
|
-
*** Meta-Insight: ${
|
|
1413
|
-
${
|
|
1414
|
-
`)}),
|
|
1415
|
-
*** ${
|
|
1416
|
-
`)),
|
|
1417
|
-
*** ${
|
|
1418
|
-
`)),
|
|
1419
|
-
*** LEMBRETE: ${
|
|
1420
|
-
`)})}function
|
|
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
|
+
[${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
|
+
[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
|
+
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(`
|
|
1549
|
+
*** ${Q} ***
|
|
1550
|
+
`)),BK($,(Q)=>{Z.showSystem(`
|
|
1551
|
+
*** Meta-Insight: ${Q.title} ***
|
|
1552
|
+
${Q.recommendation}
|
|
1553
|
+
`)}),lH((Q)=>Z.showSystem(`
|
|
1554
|
+
*** ${Q} ***
|
|
1555
|
+
`)),w7($,(Q)=>Z.showSystem(`
|
|
1556
|
+
*** ${Q} ***
|
|
1557
|
+
`)),R4($,(Q)=>{Z.showSystem(`
|
|
1558
|
+
*** 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(`
|
|
1421
1560
|
`).slice(0,5).join(`
|
|
1422
|
-
`);if(G.trim()){
|
|
1423
|
-
`))
|
|
1424
|
-
`)}function
|
|
1425
|
-
`+$.stdout);if(
|
|
1426
|
-
`+
|
|
1427
|
-
`+
|
|
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
|
+
`+$.stdout);if(Z.stdout)Q.push(`=== UNSTAGED ===
|
|
1565
|
+
`+Z.stdout);if(Y.stdout)Q.push(`=== UNTRACKED ===
|
|
1566
|
+
`+Y.stdout);return Q.join(`
|
|
1428
1567
|
|
|
1429
|
-
`)||"(no changes)"}async function
|
|
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.
|
|
1430
1569
|
|
|
1431
1570
|
Behavior:
|
|
1432
1571
|
- Write clean, production-grade code. No shortcuts.
|
|
@@ -1457,73 +1596,73 @@ Behavior:
|
|
|
1457
1596
|
- Be specific. Show the line, explain the problem, suggest the fix.
|
|
1458
1597
|
- Check for: error handling, input validation, edge cases, naming, complexity.
|
|
1459
1598
|
- Don't nitpick formatting unless it affects readability.
|
|
1460
|
-
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function
|
|
1461
|
-
`)}
|
|
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}):
|
|
1462
1601
|
${X.join(`
|
|
1463
|
-
`)}`);break}case"model":case"modelo":{let J=
|
|
1602
|
+
`)}`);break}case"model":case"modelo":{let J=z[0];if(!J){Z.tui.showSystem(KJ(Z.config.model)+`
|
|
1464
1603
|
|
|
1465
|
-
`+
|
|
1466
|
-
Expires: ${new Date(
|
|
1467
|
-
`));break;case"commit":case"commitar":{if(!await
|
|
1468
|
-
`+J),
|
|
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
|
+
`+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.
|
|
1469
1608
|
|
|
1470
1609
|
Diff:
|
|
1471
|
-
${(await
|
|
1472
|
-
`))}}else if(J==="info"){let X=
|
|
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})
|
|
1473
1612
|
${K.description}
|
|
1474
1613
|
Status: ${K.enabled?"ativo":"desabilitado"}
|
|
1475
1614
|
Source: ${K.source}
|
|
1476
|
-
Tools: ${K.tools.map((V)=>V.name).join(", ")||"nenhuma"}`);else
|
|
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":""}:
|
|
1477
1616
|
${X.join(`
|
|
1478
|
-
`)}`:`No matches for "${J}".`);break}case"lang":case"language":case"idioma":{let J=
|
|
1479
|
-
Falhas: ${K.join(", ")}`:"Nenhuma noticia encontrada."),
|
|
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:
|
|
1480
1619
|
|
|
1481
1620
|
${`Noticia: ${H.title}
|
|
1482
1621
|
Fonte: ${G.link}
|
|
1483
1622
|
|
|
1484
|
-
${H.content}`}`;
|
|
1485
|
-
Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let J=
|
|
1486
|
-
Uso: /open <app> ou /open <app> <arquivo>`);break}let X=
|
|
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}
|
|
1487
1626
|
|
|
1488
1627
|
--- Agenda ---
|
|
1489
|
-
${X}`)}catch(J){
|
|
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]
|
|
1490
1629
|
Acoes: open_app, open_url, open_file, run_command
|
|
1491
1630
|
Exemplos:
|
|
1492
1631
|
/macro create mysite open_url https://example.com "Meu site"
|
|
1493
1632
|
/macro create docs open_file C:\\Users\\Docs "Pasta de documentos"
|
|
1494
|
-
/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)){
|
|
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]
|
|
1495
1634
|
Exemplos:
|
|
1496
1635
|
/agendar "Reuniao" "14:00"
|
|
1497
1636
|
/agendar "Standup" "09:00" daily
|
|
1498
1637
|
/agendar "Review" "15:00" weekly sexta
|
|
1499
|
-
/agendar "Dentista" "10:00" once 15/04/2026`);break}let V=K[0].slice(1,-1),G=K[1].slice(1,-1),H=
|
|
1500
|
-
`).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(
|
|
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()+`
|
|
1501
1640
|
|
|
1502
|
-
`+
|
|
1503
|
-
Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let X=
|
|
1504
|
-
Use | para separar assunto do corpo.`);break}let G=K.slice(0,V).trim(),H=K.slice(V+1).trim();if(!G||!H){
|
|
1505
|
-
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){
|
|
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>
|
|
1642
|
+
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:
|
|
1506
1645
|
Chunks: ${X.chunks}
|
|
1507
1646
|
Fontes: ${X.sources}
|
|
1508
|
-
Ultima indexacao: ${K}`)}break}case"vault":{let J=
|
|
1509
|
-
${J.text}`);break;case"image":
|
|
1510
|
-
`));break}case"projeto":case"project":{let J=
|
|
1511
|
-
Ex: /addperson equipe Joao dev frontend`);break}let K=
|
|
1512
|
-
Ex: /delegate Joao revisar relatorio`);break}let X=
|
|
1513
|
-
`).filter((
|
|
1514
|
-
`).filter((U)=>U.trim()).slice(0,5);
|
|
1515
|
-
`).filter((
|
|
1516
|
-
${
|
|
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}
|
|
1517
1656
|
</file>`).join(`
|
|
1518
1657
|
|
|
1519
1658
|
`)}
|
|
1520
1659
|
|
|
1521
|
-
${
|
|
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.
|
|
1522
1661
|
Criado por Aldeia Viva - Impactando Vida (aldeia-viva.com.br)
|
|
1523
|
-
${
|
|
1524
|
-
Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.panels.length>0){W.enterDashboardMode(T);let y=()=>{W.enterChatMode(),W.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",y)};setTimeout(()=>{if(W.getViewMode()==="dashboard")W.enterChatMode()},30000),process.stdin.once("data",()=>{if(W.getViewMode()==="dashboard")W.enterChatMode()})}else{let y=await aV();W.showSystem(y)}nV()}catch(T){c.debug("Morning briefing failed at startup",{error:T})}if(G)await M(G)}import{exec as OM}from"child_process";import{stat as QM}from"fs/promises";import{join as JM}from"path";var SG=/^\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 Fz=($,z=zM)=>{let Z=/\.([a-zA-Z0-9]+?)$/,Y=$.match(Z);if(!Y)return;let Q=z[Y[1].toLowerCase()];if(Q&&Q.startsWith("text"))Q+="; charset=utf-8";return Q};var $M={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"},zM=$M;var kG=(...$)=>{let z=$.filter((Q)=>Q!=="").join("/");z=z.replace(/(?<=\/)\/+/g,"");let Z=z.split("/"),Y=[];for(let Q of Z)if(Q===".."&&Y.length>0&&Y.at(-1)!=="..")Y.pop();else if(Q!==".")Y.push(Q);return Y.join("/")||"."};var fG={br:".br",zstd:".zst",gzip:".gz"},ZM=Object.keys(fG),YM="index.html",bG=($)=>{let z=$.root??"./",Z=$.path,Y=$.join??kG;return async(Q,J)=>{if(Q.finalized)return J();let X;if($.path)X=$.path;else try{if(X=t3(Q.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(X))throw Error()}catch{return await $.onNotFound?.(Q.req.path,Q),J()}let K=Y(z,!Z&&$.rewriteRequestPath?$.rewriteRequestPath(X):X);if($.isDir&&await $.isDir(K))K=Y(K,YM);let V=$.getContent,G=await V(K,Q);if(G instanceof Response)return Q.newResponse(G.body,G);if(G){let H=$.mimes&&Fz(K,$.mimes)||Fz(K);if(Q.header("Content-Type",H||"application/octet-stream"),$.precompressed&&(!H||SG.test(H))){let W=new Set(Q.req.header("Accept-Encoding")?.split(",").map((U)=>U.trim()));for(let U of ZM){if(!W.has(U))continue;let B=await V(K+fG[U],Q);if(B){G=B,Q.header("Content-Encoding",U),Q.header("Vary","Accept-Encoding",{append:!0});break}}}return await $.onFound?.(K,Q),Q.body(G)}await $.onNotFound?.(K,Q),await J();return}};var jz=($)=>{return async function(Z,Y){return bG({...$,getContent:async(X)=>{let K=Bun.file(X);return await K.exists()?K:null},join:JM,isDir:async(X)=>{let K;try{K=(await QM(X)).isDirectory()}catch{}return K}})(Z,Y)}};var Pz="x-hono-disable-ssg",by=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Pz]:"true"}})}catch{return null}})();var{write:Bx}=Bun;var VM=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 yG=($)=>{return(...z)=>{if(typeof z[0]==="function"){let[Z,Y]=z;return async function(J,X){let K=await Z(J),V=await $(J,K,Y);if(V)return V;await X()}}else{let[Z,Y,Q]=z;return(async()=>{let J=await $(Z,Y,Q);if(!J)throw Error("Failed to upgrade WebSocket");return J})()}}};var Q7=($)=>("server"in $.env)?$.env.server:$.env;var GM=yG(($,z)=>{let Z=Q7($);if(!Z)throw TypeError("env has to include the 2nd argument of fetch.");if(Z.upgrade($.req.raw,{data:{events:z,url:new URL($.req.url),protocol:$.req.url}}))return new Response(null);return});function HM(){let{process:$,Deno:z}=globalThis;return!(typeof z?.noColor==="boolean"?z.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}async function xG(){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}})():!HM())}var WM=($)=>{let[z,Z]=[",","."];return $.map((Q)=>Q.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+z)).join(Z)},UM=($)=>{let z=Date.now()-$;return WM([z<1000?z+"ms":Math.round(z/1000)+"s"])},qM=async($)=>{if(await xG())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 vG($,z,Z,Y,Q=0,J){let X=z==="<--"?`${z} ${Z} ${Y}`:`${z} ${Z} ${Y} ${await qM(Q)} ${J}`;$(X)}var _G=($=console.log)=>{return async function(Z,Y){let{method:Q,url:J}=Z.req,X=J.slice(J.indexOf("/",8));await vG($,"<--",Q,X);let K=Date.now();await Y(),await vG($,"-->",Q,X,Z.res.status,UM(K))}};r0();class Az{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((Z)=>this.toUIMessage(Z))}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()}`,Z=this.currentSessionName;this.currentSessionName=z,this.messages=[];let Y=this.sessionManager.createSession(z);return this.sessionManager.switchTo(z),z0.emit("session:changed",{previousSession:Z||void 0,currentSession:z,timestamp:Date.now()}),{id:Y.name,name:Y.name,messageCount:Y.messages.length,created:Y.created,updated:Y.updated,isActive:!0}}deleteSessionById($){if(this.sessionManager.delete($),this.currentSessionName===$)this.currentSessionName=null,this.messages=[]}async*chat($){let z=`msg_${Date.now()}`,Z={role:"user",content:$.message,images:$.images,timestamp:Date.now()};if(this.messages.push(Z),this.currentSessionName)this.sessionManager.addMessageTo(this.currentSessionName,Z);yield{type:"message_start",messageId:z};let Y="",Q=[],J=0,X=0;try{for await(let K of this.provider.chat(this.messages,this.systemPrompt,this.enableTools))switch(K.type){case"text":Y+=K.text,yield{type:"text",messageId:z,data:K.text};break;case"tool_call":Q.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=Q.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=Q.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:Y,toolCalls:Q.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 Z=$/1e6*300,Y=z/1e6*1500;return Math.round((Z+Y)*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 BM={theme:"system",fontSize:"medium",showToolCalls:!0,showCosts:!0,autoScroll:!0,enableSounds:!1};function Tz($){let z=new P5,Z=new Map;z.use("*",_G()),z.use("*",Q6()),z.use("/static/*",jz({root:"./src/ui/web"})),z.get("/",(K)=>{return K.html(CM(KK()))}),z.get("/map",(K)=>K.html(A5())),z.get("/api/health",(K)=>K.json({status:"ok"})),z.get("/api/neighborhoods",(K)=>{return K.json(l0())}),z.get("/api/neighborhoods/:id",(K)=>{let V=N1(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=N1(K.req.param("id"));if(!V)return K.json({error:"Not found"},404);return K.json(D5(V))}),z.get("/api/neighborhoods/all/geojson",(K)=>{return K.json(J6())});function Y(K,V){let G=new Az({provider:$.provider,systemPrompt:$.systemPrompt,enableTools:$.enableTools,sessionManager:$.sessionManager,onApprovalRequired:async(B,C,N)=>{return J(K,{type:"tool_approval_required",payload:{toolCallId:`tool_${Date.now()}`,name:B,input:C,riskLevel:N}}),!0}}),H={chatService:G,settings:{...BM}};Z.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 Q(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 B=U.data;J(K,{type:"tool_call",payload:{messageId:W,id:B.id,name:B.name,input:B.input,status:"running"}});break;case"tool_result":let C=U.data;J(K,{type:"tool_result",payload:{messageId:W,toolCallId:C.id,result:C.result}});break;case"tool_blocked":let N=U.data;J(K,{type:"tool_blocked",payload:{messageId:W,toolCallId:N.id,reason:N.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((C)=>C.isActive)||null,U=V.getMessages(),B={currentSession:W,sessions:H,messages:U,isStreaming:!1,model:"claude-sonnet-4-20250514",systemPrompt:$.systemPrompt,totalCostCents:U.reduce((C,N)=>C+(N.usage?.costCents||0),0),settings:G};J(K,{type:"state",payload:B})}return{app:z,start:()=>{console.log(`
|
|
1525
|
-
${
|
|
1526
|
-
`);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
|
|
1662
|
+
${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>
|
|
1527
1666
|
<html lang="en">
|
|
1528
1667
|
<head>
|
|
1529
1668
|
<meta charset="UTF-8">
|
|
@@ -2131,17 +2270,17 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2131
2270
|
<span>smolerclaw</span>
|
|
2132
2271
|
</div>
|
|
2133
2272
|
<button class="new-chat-btn" onclick="newSession()">
|
|
2134
|
-
${
|
|
2273
|
+
${Z("web.new_chat")}
|
|
2135
2274
|
</button>
|
|
2136
2275
|
</div>
|
|
2137
2276
|
|
|
2138
2277
|
<div class="sessions-list" id="sessions-list">
|
|
2139
|
-
<div class="empty-sessions">${
|
|
2278
|
+
<div class="empty-sessions">${Z("web.no_sessions")}</div>
|
|
2140
2279
|
</div>
|
|
2141
2280
|
|
|
2142
2281
|
<div class="sidebar-footer">
|
|
2143
2282
|
<div class="cost-display">
|
|
2144
|
-
<span>${
|
|
2283
|
+
<span>${Z("web.total_cost")}</span>
|
|
2145
2284
|
<span class="cost-value" id="total-cost">$0.00</span>
|
|
2146
2285
|
</div>
|
|
2147
2286
|
</div>
|
|
@@ -2155,13 +2294,13 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2155
2294
|
<span id="model-name">claude-sonnet-4</span>
|
|
2156
2295
|
</div>
|
|
2157
2296
|
<div class="header-actions">
|
|
2158
|
-
<button class="icon-btn" onclick="toggleTheme()" title="${
|
|
2297
|
+
<button class="icon-btn" onclick="toggleTheme()" title="${Z("web.toggle_theme")}">
|
|
2159
2298
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2160
2299
|
<circle cx="12" cy="12" r="5"/>
|
|
2161
2300
|
<path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/>
|
|
2162
2301
|
</svg>
|
|
2163
2302
|
</button>
|
|
2164
|
-
<button class="icon-btn" onclick="clearChat()" title="${
|
|
2303
|
+
<button class="icon-btn" onclick="clearChat()" title="${Z("web.clear_chat")}">
|
|
2165
2304
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2166
2305
|
<path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2"/>
|
|
2167
2306
|
</svg>
|
|
@@ -2172,24 +2311,24 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2172
2311
|
<div class="messages-container" id="messages-container">
|
|
2173
2312
|
<div class="welcome">
|
|
2174
2313
|
<div class="welcome-icon">S</div>
|
|
2175
|
-
<h1>${
|
|
2176
|
-
<p>${
|
|
2314
|
+
<h1>${Z("web.welcome_title")}</h1>
|
|
2315
|
+
<p>${Z("web.welcome_desc")}</p>
|
|
2177
2316
|
<div class="suggestions">
|
|
2178
2317
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_start_prompt'])">
|
|
2179
|
-
<div class="suggestion-title">${
|
|
2180
|
-
<div class="suggestion-desc">${
|
|
2318
|
+
<div class="suggestion-title">${Z("web.suggestion_start_title")}</div>
|
|
2319
|
+
<div class="suggestion-desc">${Z("web.suggestion_start_desc")}</div>
|
|
2181
2320
|
</div>
|
|
2182
2321
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_tasks_prompt'])">
|
|
2183
|
-
<div class="suggestion-title">${
|
|
2184
|
-
<div class="suggestion-desc">${
|
|
2322
|
+
<div class="suggestion-title">${Z("web.suggestion_tasks_title")}</div>
|
|
2323
|
+
<div class="suggestion-desc">${Z("web.suggestion_tasks_desc")}</div>
|
|
2185
2324
|
</div>
|
|
2186
2325
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_system_prompt'])">
|
|
2187
|
-
<div class="suggestion-title">${
|
|
2188
|
-
<div class="suggestion-desc">${
|
|
2326
|
+
<div class="suggestion-title">${Z("web.suggestion_system_title")}</div>
|
|
2327
|
+
<div class="suggestion-desc">${Z("web.suggestion_system_desc")}</div>
|
|
2189
2328
|
</div>
|
|
2190
2329
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_briefing_prompt'])">
|
|
2191
|
-
<div class="suggestion-title">${
|
|
2192
|
-
<div class="suggestion-desc">${
|
|
2330
|
+
<div class="suggestion-title">${Z("web.suggestion_briefing_title")}</div>
|
|
2331
|
+
<div class="suggestion-desc">${Z("web.suggestion_briefing_desc")}</div>
|
|
2193
2332
|
</div>
|
|
2194
2333
|
</div>
|
|
2195
2334
|
</div>
|
|
@@ -2200,7 +2339,7 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2200
2339
|
<div class="input-box">
|
|
2201
2340
|
<textarea
|
|
2202
2341
|
id="input"
|
|
2203
|
-
placeholder="${
|
|
2342
|
+
placeholder="${Z("web.placeholder")}"
|
|
2204
2343
|
rows="1"
|
|
2205
2344
|
onkeydown="handleKeyDown(event)"
|
|
2206
2345
|
oninput="autoResize(this)"
|
|
@@ -2211,7 +2350,7 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2211
2350
|
</svg>
|
|
2212
2351
|
</button>
|
|
2213
2352
|
</div>
|
|
2214
|
-
<div class="input-hint">${
|
|
2353
|
+
<div class="input-hint">${Z("web.input_hint")}</div>
|
|
2215
2354
|
</div>
|
|
2216
2355
|
</div>
|
|
2217
2356
|
</main>
|
|
@@ -2219,7 +2358,7 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2219
2358
|
|
|
2220
2359
|
<script>
|
|
2221
2360
|
// i18n translations injected from server
|
|
2222
|
-
window.__i18n = ${JSON.stringify(Object.fromEntries(Object.entries($).filter(([
|
|
2361
|
+
window.__i18n = ${JSON.stringify(Object.fromEntries(Object.entries($).filter(([Y])=>Y.startsWith("web."))))};
|
|
2223
2362
|
const __t = (key) => window.__i18n[key] || key;
|
|
2224
2363
|
|
|
2225
2364
|
// State
|
|
@@ -2605,24 +2744,24 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2605
2744
|
return \`
|
|
2606
2745
|
<div class="welcome">
|
|
2607
2746
|
<div class="welcome-icon">S</div>
|
|
2608
|
-
<h1>${
|
|
2609
|
-
<p>${
|
|
2747
|
+
<h1>${Z("web.welcome_title")}</h1>
|
|
2748
|
+
<p>${Z("web.welcome_desc")}</p>
|
|
2610
2749
|
<div class="suggestions">
|
|
2611
2750
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_start_prompt'])">
|
|
2612
|
-
<div class="suggestion-title">${
|
|
2613
|
-
<div class="suggestion-desc">${
|
|
2751
|
+
<div class="suggestion-title">${Z("web.suggestion_start_title")}</div>
|
|
2752
|
+
<div class="suggestion-desc">${Z("web.suggestion_start_desc")}</div>
|
|
2614
2753
|
</div>
|
|
2615
2754
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_tasks_prompt'])">
|
|
2616
|
-
<div class="suggestion-title">${
|
|
2617
|
-
<div class="suggestion-desc">${
|
|
2755
|
+
<div class="suggestion-title">${Z("web.suggestion_tasks_title")}</div>
|
|
2756
|
+
<div class="suggestion-desc">${Z("web.suggestion_tasks_desc")}</div>
|
|
2618
2757
|
</div>
|
|
2619
2758
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_system_prompt'])">
|
|
2620
|
-
<div class="suggestion-title">${
|
|
2621
|
-
<div class="suggestion-desc">${
|
|
2759
|
+
<div class="suggestion-title">${Z("web.suggestion_system_title")}</div>
|
|
2760
|
+
<div class="suggestion-desc">${Z("web.suggestion_system_desc")}</div>
|
|
2622
2761
|
</div>
|
|
2623
2762
|
<div class="suggestion" onclick="sendSuggestion(window.__i18n['web.suggestion_briefing_prompt'])">
|
|
2624
|
-
<div class="suggestion-title">${
|
|
2625
|
-
<div class="suggestion-desc">${
|
|
2763
|
+
<div class="suggestion-title">${Z("web.suggestion_briefing_title")}</div>
|
|
2764
|
+
<div class="suggestion-desc">${Z("web.suggestion_briefing_desc")}</div>
|
|
2626
2765
|
</div>
|
|
2627
2766
|
</div>
|
|
2628
2767
|
</div>
|
|
@@ -2634,6 +2773,6 @@ Type /ajuda for commands.`),rV(Z.dataDir))try{let T=await Lz(Z.dataDir);if(T.pan
|
|
|
2634
2773
|
document.getElementById('input').addEventListener('input', updateSendButton);
|
|
2635
2774
|
</script>
|
|
2636
2775
|
</body>
|
|
2637
|
-
</html>`}function
|
|
2638
|
-
${
|
|
2639
|
-
`),Tz({port:
|
|
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)});
|