smolerclaw 1.3.4 → 1.3.5
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 +317 -257
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
3
|
+
var gJ=Object.defineProperty;var mJ=($)=>$;function pJ($,Z){this[$]=mJ.bind(null,Z)}var cZ=($,Z)=>{for(var Q in Z)gJ($,Q,{get:Z[Q],enumerable:!0,configurable:!0,set:pJ.bind(Z,Q)})};var Z8=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as lJ,appendFileSync as oJ,mkdirSync as XU}from"fs";import{join as aZ}from"path";import{homedir as aJ}from"os";function k8($,Z,Q){if(!N5)return;let Y=new Date().toISOString(),J=Q?`[${Y}] [${$}] ${Z} ${JSON.stringify(Q)}
|
|
4
4
|
`:`[${Y}] [${$}] ${Z}
|
|
5
|
-
`;try{
|
|
6
|
-
... (truncated, ${Z.length} total chars)`;return Z}function
|
|
7
|
-
--- Arquivos ---`);for(let Y of $.files){if(!Y.exists){Z.push(` ${Y.file.padEnd(30)} (nao existe)`);continue}let
|
|
8
|
-
`)}async function
|
|
9
|
-
`);if(
|
|
10
|
-
`)}async function
|
|
11
|
-
`);try{let Z=await
|
|
12
|
-
...(truncated, ${Y.length} total chars)`;let V={id:
|
|
13
|
-
... (truncado)`:K.content;
|
|
14
|
-
`)}function
|
|
5
|
+
`;try{oJ(iJ,J)}catch{}}function rZ($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function iZ($){let Z=$.replace(/\//g,"\\");return rZ(Z)}async function K0($){let Z=J0.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(lJ($)){let Y={exists:!0,path:$};return J0.set($.toLowerCase(),Y),Y}return{exists:!1,error:`File not found: ${$}`}}let Q=`(Get-Command '${$}' -ErrorAction SilentlyContinue).Source`;try{let Y=await U$(Q,{timeout:5000});if(Y.exitCode===0&&Y.stdout.trim()){let X={exists:!0,path:Y.stdout.trim()};return J0.set($.toLowerCase(),X),X}let J={exists:!1,error:`'${$}' not found in PATH`};return J0.set($.toLowerCase(),J),J}catch(Y){return{exists:!1,error:Y instanceof Error?Y.message:String(Y)}}}async function U$($,Z={}){let{timeout:Q=nZ,cwd:Y,debug:J=N5,sta:X=!1}=Z,K=performance.now(),V=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,G=["powershell",...sJ];if(X)G.push("-STA");if(G.push("-Command",V),J)k8("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:Q,cwd:Y,sta:X});let H;try{H=Bun.spawn(G,{stdout:"pipe",stderr:"pipe",cwd:Y})}catch(W){let N={stdout:"",stderr:`Failed to spawn PowerShell: ${W instanceof Error?W.message:String(W)}`,exitCode:1,duration:Math.round(performance.now()-K),timedOut:!1};if(J)k8("ERROR","Failed to spawn process",{error:N.stderr});return N}let z=!1,B=setTimeout(()=>{z=!0;try{H.kill()}catch{}},Q);try{let[W,N]=await Promise.all([H.stdout instanceof ReadableStream?new Response(H.stdout).text():"",H.stderr instanceof ReadableStream?new Response(H.stderr).text():""]),O=await H.exited;clearTimeout(B);let j=Math.round(performance.now()-K),P={stdout:X0(W),stderr:X0(N),exitCode:z?-1:O,duration:j,timedOut:z};if(J)k8(P.exitCode===0?"INFO":"WARN","Command completed",{exitCode:P.exitCode,duration:j,timedOut:z,stdoutLength:P.stdout.length,stderrLength:P.stderr.length});return P}catch(W){clearTimeout(B);let N={stdout:"",stderr:`Execution error: ${W instanceof Error?W.message:String(W)}`,exitCode:1,duration:Math.round(performance.now()-K),timedOut:z};if(J)k8("ERROR","Execution failed",{error:N.stderr,timedOut:z});return N}}async function sZ($,Z={}){let Y=`& ${iZ($)}`;return U$(Y,Z)}async function M5($,Z={}){let{timeout:Q=nZ,cwd:Y,debug:J=N5}=Z,X=performance.now();if(J)k8("INFO","Executing command",{args:$,timeout:Q,cwd:Y});let K;try{K=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Y})}catch(H){return{stdout:"",stderr:`Failed to spawn: ${H instanceof Error?H.message:String(H)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:!1}}let V=!1,G=setTimeout(()=>{V=!0;try{K.kill()}catch{}},Q);try{let[H,z]=await Promise.all([K.stdout instanceof ReadableStream?new Response(K.stdout).text():"",K.stderr instanceof ReadableStream?new Response(K.stderr).text():""]),B=await K.exited;return clearTimeout(G),{stdout:X0(H),stderr:X0(z),exitCode:V?-1:B,duration:Math.round(performance.now()-X),timedOut:V}}catch(H){return clearTimeout(G),{stdout:"",stderr:`Execution error: ${H instanceof Error?H.message:String(H)}`,exitCode:1,duration:Math.round(performance.now()-X),timedOut:V}}}async function F5($,Z={}){return U$($,{...Z,sta:!0})}async function u$($,Z,Q=[],Y={}){let J=["schtasks",`/${$}`,"/TN",Z,...Q],X=Y.timeout??1e4;return M5(J,{...Y,timeout:X})}async function O5($,Z,Q={}){let Y=rZ($),J=Z?`Start-Process ${Y} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Y}`;return U$(J,Q)}async function tZ($,Z={}){let Q=iZ($);return U$(`Invoke-Item ${Q}`,Z)}async function H4($,Z,Q={}){let Y=oZ($),J=oZ(Z),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",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("smolerclaw").Show($toast)'].join("; "),K=Q.timeout??1e4;return U$(X,{...Q,timeout:K})}async function z0($,Z={}){let Y=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await U$(Y,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function eZ($=15,Z={}){let Q=`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 U$(Q,Z)}function X0($){let Z=$.replace(nJ,"");if(Z.length>lZ)return Z.slice(0,lZ)+`
|
|
6
|
+
... (truncated, ${Z.length} total chars)`;return Z}function oZ($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function $2($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var nZ=15000,lZ=1e5,nJ,rJ,iJ,sJ,N5=!1,J0;var d$=Z8(()=>{nJ=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,rJ=aZ(aJ(),".smolerclaw","logs"),iJ=aZ(rJ,"windows-executor.log"),sJ=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];J0=new Map});import{existsSync as tJ}from"fs";function Q8(){if(A)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&tJ($))return[$,"-c"];return["bash","-c"]}function Q2(){if(A)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function eJ($){if(A)return(await K0($)).exists;try{return(await M5(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function Y2(){if(V0!==null)return V0;return V0=await eJ("rg"),V0}function R5($){let Z=$.replace(/\\/g,"/");return y8.some((Q)=>Z.includes(`/${Q}/`)||Z.startsWith(`${Q}/`))}var A,Z2,WU,V0=null,y8;var Z$=Z8(()=>{d$();A=process.platform==="win32",Z2=process.platform==="darwin",WU=process.platform==="linux";y8=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as $X}from"events";class J2{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new $X,this.emitter.setMaxListeners($.maxListeners??20),this.debug=$.debug??!!process.env.DEBUG}on($,Z,Q={}){let Y={listener:Z,once:!1,async:Q.async??!1},J=this.listeners.get($)??[];if(J.push(Y),this.listeners.set($,J),this.debug)console.log(`[event-bus] Registered listener for '${$}'`);return()=>this.off($,Z)}once($,Z,Q={}){let Y={listener:Z,once:!0,async:Q.async??!1},J=this.listeners.get($)??[];if(J.push(Y),this.listeners.set($,J),this.debug)console.log(`[event-bus] Registered once listener for '${$}'`);return()=>this.off($,Z)}off($,Z){let Q=this.listeners.get($);if(!Q)return;let Y=Q.filter((J)=>J.listener!==Z);if(Y.length===0)this.listeners.delete($);else this.listeners.set($,Y);if(this.debug)console.log(`[event-bus] Removed listener from '${$}'`)}emit($,Z){let Q=this.listeners.get($);if(!Q||Q.length===0){if(this.debug)console.log(`[event-bus] No listeners for '${$}'`);return}if(this.debug)console.log(`[event-bus] Emitting '${$}' to ${Q.length} listener(s)`);let Y=[];for(let J of Q)try{let X=J.listener(Z);if(J.async&&X instanceof Promise)X.catch((K)=>{this.handleError(K,$,Z)});if(J.once)Y.push(J)}catch(X){this.handleError(X instanceof Error?X:Error(String(X)),$,Z)}if(Y.length>0){let J=Q.filter((X)=>!Y.includes(X));if(J.length===0)this.listeners.delete($);else this.listeners.set($,J)}}async emitAsync($,Z){let Q=this.listeners.get($);if(!Q||Q.length===0)return;if(this.debug)console.log(`[event-bus] Emitting async '${$}' to ${Q.length} listener(s)`);let Y=[],J=[];for(let X of Q)try{let K=X.listener(Z);if(K instanceof Promise)J.push(K.catch((V)=>{this.handleError(V instanceof Error?V:Error(String(V)),$,Z)}));if(X.once)Y.push(X)}catch(K){this.handleError(K instanceof Error?K:Error(String(K)),$,Z)}if(await Promise.all(J),Y.length>0){let X=Q.filter((K)=>!Y.includes(K));if(X.length===0)this.listeners.delete($);else this.listeners.set($,X)}}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,Q){if(this.debug||process.env.DEBUG)console.error(`[event-bus] Error in '${Z}' listener:`,$.message);for(let Y of this.errorHandlers)try{Y($,Z,Q)}catch{}}}function q4($){if(!E5)E5=new J2($);return E5}var E5=null,W$;var b8=Z8(()=>{W$=q4()});import{existsSync as l$,mkdirSync as L5,readFileSync as H0,writeFileSync as _8,renameSync as X2,statSync as ZX}from"fs";import{join as M$,dirname as K2,relative as QX}from"path";import{createHash as YX,randomUUID as z2}from"crypto";function U2($,Z){if(o$=$,q2=Z,J$=M$($,".backup"),XX(),D5=!0,k4=l$(M$(J$,".git")),k4)j5=VX()}function v8(){return D5}function S($,Z){let Q=K2($);if(!l$(Q))L5(Q,{recursive:!0});let Y=M$(Q,`.smolerclaw-${z2().slice(0,8)}.tmp`);_8(Y,Z),X2(Y,$);let J=!1;if(D5){let K=zX($);if(K&&q0.includes(K))JX(K,Z),J=!0}let X={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:J,timestamp:Date.now()};W$.emit("file:saved",X)}function W2($){return YX("sha256").update($).digest("hex")}function JX($,Z){let Q=W2(Z),Y=new Date().toISOString(),J=Buffer.byteLength(Z,"utf-8");U4=[...U4.filter((X)=>X.file!==$),{file:$,sha256:Q,size:J,updatedAt:Y}],KX()}function XX(){let $=M$(o$,G2);if(!l$($)){U4=[];return}try{let Z=JSON.parse(H0($,"utf-8"));if(Z.version!==V2){U4=[];return}U4=Z.checksums||[]}catch{U4=[]}}function KX(){if(!o$)return;let $=M$(o$,G2),Z={checksums:U4,version:V2},Q=M$(o$,`.vault-${z2().slice(0,8)}.tmp`);_8(Q,JSON.stringify(Z,null,2)),X2(Q,$)}function zX($){try{let Z=QX(o$,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function U0(){let $=[],Z=0;for(let Q of q0){let Y=M$(o$,Q),J=l$(Y);if(!J){$.push({file:Q,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let X=0,K="";try{let H=ZX(Y);X=H.size,K=H.mtime.toISOString()}catch{}let V=U4.find((H)=>H.file===Q),G=null;if(V)try{let H=H0(Y,"utf-8");if(G=W2(H)===V.sha256,!G)Z++}catch{G=!1,Z++}$.push({file:Q,exists:J,checksumValid:G,size:X,lastModified:K})}return{files:$,lastBackup:j5,backupEnabled:k4,totalFiles:$.filter((Q)=>Q.exists).length,corruptFiles:Z}}function W0($){let Z=["=== Vault Status ==="],Q=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Q}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${q0.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
|
|
7
|
+
--- Arquivos ---`);for(let Y of $.files){if(!Y.exists){Z.push(` ${Y.file.padEnd(30)} (nao existe)`);continue}let J=(Y.size/1024).toFixed(1),X=Y.checksumValid===null?"?":Y.checksumValid?"OK":"CORROMPIDO",K=Y.lastModified?new Date(Y.lastModified).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${Y.file.padEnd(30)} ${J.padStart(8)} KB [${X}] ${K}`)}return Z.join(`
|
|
8
|
+
`)}async function B0(){if(!o$)return"Error: vault not initialized.";if(!l$(J$))L5(J$,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
|
|
9
|
+
`);if(_8(M$(J$,".gitignore"),$),!l$(M$(J$,".git"))){let Z=await W4(["git","init","-b",H2],J$);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await W4(["git","config","user.email","vault@smolerclaw.local"],J$),await W4(["git","config","user.name","smolerclaw-vault"],J$)}return k4=!0,"Shadow backup inicializado."}async function Y8($){if(!k4)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let V of q0){let G=M$(o$,V);if(!l$(G))continue;let H=M$(J$,V),z=K2(H);if(!l$(z))L5(z,{recursive:!0});_8(H,H0(G,"utf-8"))}let Q=M$(q2,"config.json");if(l$(Q))_8(M$(J$,"config.json"),H0(Q,"utf-8"));if(await W4(["git","add","-A"],J$),!(await W4(["git","status","--porcelain"],J$)).stdout.trim()){let V={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:"Nenhuma mudanca para backup",duration:Date.now()-Z,timestamp:Date.now()};return W$.emit("task:completed",V),"Nenhuma mudanca para backup."}let J=$||`backup ${new Date().toISOString().slice(0,19)}`,X=await W4(["git","commit","-m",J],J$);if(!X.ok){let V={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Commit falhou: ${X.stderr}`,duration:Date.now()-Z,timestamp:Date.now()};return W$.emit("task:completed",V),`Backup commit falhou: ${X.stderr}`}j5=new Date().toISOString();let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:`Backup concluido: ${J}`,duration:Date.now()-Z,timestamp:Date.now()};return W$.emit("task:completed",K),`Backup concluido: ${J}`}catch(Q){let Y=Q instanceof Error?Q.message:String(Q),J={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Backup falhou: ${Y}`,duration:Date.now()-Z,timestamp:Date.now()};return W$.emit("task:completed",J),`Backup falhou: ${Y}`}}async function C0(){if(!k4)return"Backup nao ativado.";if(!(await W4(["git","remote","-v"],J$)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await W4(["git","push","-u","origin",H2],J$);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function VX(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:J$,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function W4($,Z){let Q=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Y,J]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),X=await Q.exited;return{stdout:Y.trim(),stderr:J.trim(),ok:X===0}}function B2($=30){if(P5(),!k4)return;G0=setInterval(()=>{Y8("auto-backup").catch(()=>{})},$*60*1000)}function P5(){if(G0)clearInterval(G0),G0=null}var V2=1,G2="vault-checksums.json",H2="smolerclaw-backup",q0,o$="",q2="",U4,J$="",k4=!1,j5=null,D5=!1,G0=null;var n=Z8(()=>{b8();q0=["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"],U4=[]});var R6={};cZ(R6,{openUrl:()=>p4,openFile:()=>A1,openApp:()=>m4,getSystemInfo:()=>c4,getRunningApps:()=>I1,getOutlookEvents:()=>h$,getKnownApps:()=>q9,getDateTimeInfo:()=>u4});function H9($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(VK.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function m4($,Z){let Q=$.toLowerCase().replace(/\s+/g,""),Y=G9[Q];if(!Y){let J=Object.keys(G9).join(", ");return`Unknown app: "${$}". Available: ${J}`}if(Z){let J=H9(Z,"argument");if(J)return J}if(!A)return"Error: this command is only available on Windows.";if(!Y.includes(":")){let J=await K0(Y);if(!J.exists)return`Error: ${Y} not found. ${J.error||""}`}try{let J=await O5(Y,Z);if(J.exitCode!==0&&J.stderr.trim())return`Error opening ${$}: ${J.stderr.trim()}`;if(J.timedOut)return`Error opening ${$}: timeout (application may have opened but response was delayed)`;return`Opened: ${$}`}catch(J){return`Error opening ${$}: ${J instanceof Error?J.message:String(J)}`}}async function p4($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=H9($,"URL");if(Z)return Z;if(!A)return"Error: this command is only available on Windows.";try{let Q=await O5($);if(Q.exitCode!==0&&Q.stderr.trim())return`Error: ${Q.stderr.trim()}`;if(Q.timedOut)return"Error: timeout opening URL (browser may have opened but response was delayed)";return`Opened in browser: ${$}`}catch(Q){return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}async function A1($){let Z=H9($,"file path");if(Z)return Z;if(!A)return"Error: this command is only available on Windows.";try{let Q=await tZ($);if(Q.exitCode!==0&&Q.stderr.trim())return`Error: ${Q.stderr.trim()}`;if(Q.timedOut)return"Error: timeout opening file (application may have opened but response was delayed)";return`Opened: ${$}`}catch(Q){return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}async function I1(){if(!A)return"Error: this command is only available on Windows.";try{let $=await eZ(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 c4(){if(!A)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 U$($.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 u4(){let $=new Date,Z=[],Q=$.toLocaleDateString("pt-BR",{weekday:"long"}),Y=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),J=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Q}, ${Y} \u2014 ${J}`);let X=new Date($.valueOf());X.setDate(X.getDate()+3-(X.getDay()+6)%7);let K=new Date(X.getFullYear(),0,4),V=1+Math.round(((X.getTime()-K.getTime())/86400000-3+(K.getDay()+6)%7)/7);Z.push(`Semana ${V} do ano`);let G=$.getHours();if(G>=8&&G<18)Z.push("Status: horario comercial");else if(G>=18&&G<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
|
|
10
|
+
`)}async function h$(){if(!A)return"Outlook integration only available on Windows.";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",` $filter = "[Start] >= '$($today.ToString('g'))' AND [Start] < '$($tomorrow.ToString('g'))'"`," $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) { "Nenhum evento hoje." }'," else { $results -join [char]10 }","} catch {",' "Outlook nao disponivel ou sem eventos."',"}"].join(`
|
|
11
|
+
`);try{let Z=await U$($,{timeout:30000});if(Z.timedOut)return"Outlook timeout - pode estar em processo de inicializacao.";return Z.stdout.trim()||"Outlook nao disponivel."}catch{return"Outlook nao disponivel."}}function q9(){return Object.keys(G9)}var VK,G9;var d4=Z8(()=>{Z$();d$();VK=/[";`$\n\r|&<>{}()]/;G9={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"}});var y9={};cZ(y9,{searchInvestigations:()=>x9,openInvestigation:()=>j9,listInvestigations:()=>I9,initInvestigations:()=>L9,getInvestigation:()=>A9,generateReport:()=>S9,formatInvestigationList:()=>E7,formatInvestigationDetail:()=>w9,formatEvidenceDetail:()=>Az,collectEvidence:()=>D9,closeInvestigation:()=>T9,addFinding:()=>P9});import{existsSync as G3,mkdirSync as Lz,readFileSync as jz}from"fs";import{join as Dz}from"path";import{randomUUID as Pz}from"crypto";function R7(){S(q3(),JSON.stringify(V$,null,2))}function Tz(){let $=q3();if(!G3($)){V$=[];return}try{V$=JSON.parse(jz($,"utf-8"))}catch{V$=[]}}function L9($){if(H3=$,!G3($))Lz($,{recursive:!0});Tz()}function j9($,Z,Q,Y=[]){let J=new Date().toISOString(),X={id:k9(),title:$.trim(),type:Z,status:"aberta",hypothesis:Q?.trim(),tags:Y.map((K)=>K.toLowerCase()),evidence:[],findings:[],created:J,updated:J};return V$=[...V$,X],R7(),X}function D9($,Z,Q,Y,J){let X=f1($);if(!X)return null;let K=Y.trim();if(K.length>V3)K=K.slice(0,V3)+`
|
|
12
|
+
...(truncated, ${Y.length} total chars)`;let V={id:k9(),source:Z,label:Q.trim(),content:K,path:J?.trim(),timestamp:new Date().toISOString()},G={...X,evidence:[...X.evidence,V],status:X.status==="aberta"?"em_andamento":X.status,updated:new Date().toISOString()};return V$=V$.map((H)=>H.id===X.id?G:H),R7(),V}function P9($,Z,Q,Y,J=[]){let X=f1($);if(!X)return null;let K=J.filter((H)=>X.evidence.some((z)=>z.id===H)),V={id:k9(),severity:Z,title:Q.trim(),description:Y.trim(),evidence_ids:K,timestamp:new Date().toISOString()},G={...X,findings:[...X.findings,V],updated:new Date().toISOString()};return V$=V$.map((H)=>H.id===X.id?G:H),R7(),V}function T9($,Z,Q){let Y=f1($);if(!Y)return null;let J={...Y,status:"concluida",summary:Z.trim(),recommendations:Q?.trim(),updated:new Date().toISOString()};return V$=V$.map((X)=>X.id===Y.id?J:X),R7(),J}function A9($){return f1($)}function I9($,Z,Q=20){let Y=[...V$];if($)Y=Y.filter((J)=>J.status===$);if(Z)Y=Y.filter((J)=>J.type===Z);return Y.sort((J,X)=>new Date(X.updated).getTime()-new Date(J.updated).getTime()).slice(0,Q)}function x9($){let Z=$.toLowerCase();return V$.filter((Q)=>Q.title.toLowerCase().includes(Z)||Q.hypothesis?.toLowerCase().includes(Z)||Q.tags.some((Y)=>Y.includes(Z))||Q.findings.some((Y)=>Y.title.toLowerCase().includes(Z))||Q.summary?.toLowerCase().includes(Z)).sort((Q,Y)=>new Date(Y.updated).getTime()-new Date(Q.updated).getTime())}function S9($){let Z=f1($);if(!Z)return null;let Q=[],Y=(K)=>new Date(K).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),J={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},X={critical:0,high:1,medium:2,low:3,info:4};if(Q.push(`# Investigacao: ${Z.title}`),Q.push(""),Q.push(`**Tipo:** ${J[Z.type]}`),Q.push(`**Status:** ${Z.status}`),Q.push(`**Abertura:** ${Y(Z.created)}`),Q.push(`**Ultima atualizacao:** ${Y(Z.updated)}`),Z.tags.length)Q.push(`**Tags:** ${Z.tags.join(", ")}`);if(Q.push(`**ID:** ${Z.id}`),Z.hypothesis)Q.push(""),Q.push("## Hipotese"),Q.push(Z.hypothesis);if(Z.evidence.length>0){Q.push(""),Q.push(`## Evidencias (${Z.evidence.length})`);for(let K of Z.evidence){let V=Y(K.timestamp);Q.push(""),Q.push(`### [${K.id}] ${K.label}`),Q.push(`- Fonte: ${K.source}${K.path?` (${K.path})`:""}`),Q.push(`- Coletada: ${V}`);let G=K.content.length>2000?K.content.slice(0,2000)+`
|
|
13
|
+
... (truncado)`:K.content;Q.push("```"),Q.push(G),Q.push("```")}}if(Z.findings.length>0){let K=[...Z.findings].sort((V,G)=>(X[V.severity]??4)-(X[G.severity]??4));Q.push(""),Q.push(`## Conclusoes (${Z.findings.length})`);for(let V of K){let G=W3(V.severity);if(Q.push(""),Q.push(`### ${G} ${V.title}`),Q.push(V.description),V.evidence_ids.length>0)Q.push(`- Evidencias: ${V.evidence_ids.join(", ")}`)}}if(Z.summary)Q.push(""),Q.push("## Resumo"),Q.push(Z.summary);if(Z.recommendations)Q.push(""),Q.push("## Recomendacoes"),Q.push(Z.recommendations);return Q.join(`
|
|
14
|
+
`)}function E7($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Q)=>{let Y=new Date(Q.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=U3(Q.status),X=Q.evidence.length,K=Q.findings.length,V=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"";return` ${J} [${Y}] ${Q.title} (${Q.type}) \u2014 ${X} ev, ${K} concl${V} {${Q.id}}`});return`Investigacoes (${$.length}):
|
|
15
15
|
${Z.join(`
|
|
16
|
-
`)}`}function
|
|
17
|
-
Evidencias: ${$.evidence.length}`);for(let
|
|
18
|
-
Conclusoes: ${$.findings.length}`);for(let
|
|
16
|
+
`)}`}function w9($){let Z=(J)=>new Date(J).toLocaleDateString("pt-BR"),Q=U3($.status),Y=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Q}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)Y.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)Y.push(`Tags: ${$.tags.join(", ")}`);Y.push(`
|
|
17
|
+
Evidencias: ${$.evidence.length}`);for(let J of $.evidence.slice(-5)){let X=J.content.slice(0,80).replace(/\n/g," ");Y.push(` [${J.id}] ${J.source}: ${J.label} \u2014 "${X}..."`)}if($.evidence.length>5)Y.push(` ... (${$.evidence.length-5} mais)`);Y.push(`
|
|
18
|
+
Conclusoes: ${$.findings.length}`);for(let J of $.findings)Y.push(` ${W3(J.severity)} ${J.title}`);if($.summary)Y.push(`
|
|
19
19
|
Resumo: ${$.summary}`);if($.recommendations)Y.push(`Recomendacoes: ${$.recommendations}`);return Y.join(`
|
|
20
|
-
`)}function
|
|
20
|
+
`)}function Az($){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)+`
|
|
21
21
|
... (truncado)`:$.content].join(`
|
|
22
|
-
`)}function
|
|
22
|
+
`)}function f1($){let Z=$.toLowerCase().trim(),Q=V$.find((J)=>J.id===Z);if(Q)return Q;return V$.filter((J)=>J.title.toLowerCase().includes(Z)).sort((J,X)=>new Date(X.updated).getTime()-new Date(J.updated).getTime())[0]||null}function U3($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function W3($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function k9(){return Pz().slice(0,8)}var H3="",V$,q3=()=>Dz(H3,"investigations.json"),V3=50000;var h1=Z8(()=>{n();V$=[]});import{readFileSync as cJ}from"fs";import{join as uJ,dirname as dJ}from"path";function uZ($){let Z={help:!1,version:!1,noTools:!1,print:!1},Q=[],Y=0;while(Y<$.length){let J=$[Y];switch(J){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++Y],!Z.model)Q0("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Y],!Z.session)Q0("--session requires a value");break;case"--max-tokens":let X=Number($[++Y]);if(!X||X<=0)Q0("--max-tokens requires a positive number");Z.maxTokens=X;break;case"--no-tools":Z.noTools=!0;break;case"-p":case"--print":Z.print=!0;break;default:if(J.startsWith("-"))Q0(`Unknown option: ${J}. Try --help`);Q.push(J)}Y++}if(Q.length>0)Z.prompt=Q.join(" ");return Z}function Y0(){return"1.3.5"}function dZ(){let $=Y0();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
|
|
23
23
|
|
|
24
24
|
Usage:
|
|
25
25
|
smolerclaw [options] [prompt]
|
|
@@ -47,15 +47,15 @@ Commands (inside TUI):
|
|
|
47
47
|
/briefing Daily briefing /news News radar
|
|
48
48
|
/task Create task /tasks List tasks
|
|
49
49
|
/open Open Windows app /calendar Outlook calendar
|
|
50
|
-
/export Export markdown /exit Quit`)}function l1($){console.error(`smolerclaw: ${$}`),process.exit(2)}$$();r();import{existsSync as K0,mkdirSync as xQ,readFileSync as aZ}from"fs";import{homedir as SQ}from"os";import{join as g$}from"path";var w8=SQ(),z0=I?g$(process.env.APPDATA||g$(w8,"AppData","Roaming"),"smolerclaw"):g$(w8,".config","smolerclaw"),K5=I?g$(process.env.LOCALAPPDATA||g$(w8,"AppData","Local"),"smolerclaw"):g$(w8,".local","share","smolerclaw"),z4=g$(z0,"config.json"),s4={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:K5,toolApproval:"auto",language:"auto",maxSessionCost:0};function S8($){if(!K0($))xQ($,{recursive:!0})}function rZ(){if(S8(z0),S8(K5),S8(g$(K5,"sessions")),I)kQ();if(!K0(z4))return x(z4,JSON.stringify(s4,null,2)),{...s4};let $;try{$=JSON.parse(aZ(z4,"utf-8"))}catch{return x(z4,JSON.stringify(s4,null,2)),{...s4}}return wQ({...s4,...$})}function wQ($){let Z={...s4};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 J=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&J.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function V0($){S8(z0),x(z4,JSON.stringify($,null,2))}function z5(){return z4}function kQ(){let $=g$(w8,".config","smolerclaw","config.json");if(K0($)&&!K0(z4))try{let Z=aZ($,"utf-8");S8(z0),x(z4,Z)}catch{}}import{existsSync as bQ,readFileSync as yQ}from"fs";import{homedir as _Q}from"os";import{join as vQ}from"path";var iZ=vQ(_Q(),".claude",".credentials.json");function V5(){let $=fQ();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 fQ(){if(!bQ(iZ))return null;try{let Z=JSON.parse(yQ(iZ,"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 G5(){try{return V5()}catch{return null}}function nZ($){return`sub:${$.subscriptionType||"pro"}`}function D($,Z,J,Y,Q){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!Q)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!Q:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?Q.call($,J):Q?Q.value=J:Z.set($,J),J}function C($,Z,J,Y){if(J==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?Y:J==="a"?Y.call($):Y?Y.value:Z.get($)}var H5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return H5=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),J=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^J()&15>>+Y/4).toString(16))};function m$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var k8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class P extends Error{}class i extends P{constructor($,Z,J,Y){super(`${i.makeMessage($,Z,J)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=Z}static makeMessage($,Z,J){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):J;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,J,Y){if(!$||!Y)return new P4({message:J,cause:k8(Z)});let Q=Z;if($===400)return new y8($,Q,J,Y);if($===401)return new _8($,Q,J,Y);if($===403)return new v8($,Q,J,Y);if($===404)return new f8($,Q,J,Y);if($===409)return new h8($,Q,J,Y);if($===422)return new g8($,Q,J,Y);if($===429)return new m8($,Q,J,Y);if($>=500)return new c8($,Q,J,Y);return new i($,Q,J,Y)}}class Q$ extends i{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class P4 extends i{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class b8 extends P4{constructor({message:$}={}){super({message:$??"Request timed out."})}}class y8 extends i{}class _8 extends i{}class v8 extends i{}class f8 extends i{}class h8 extends i{}class g8 extends i{}class m8 extends i{}class c8 extends i{}var gQ=/^[a-z][a-z0-9+.-]*:/i,sZ=($)=>{return gQ.test($)},q5=($)=>(q5=Array.isArray,q5($)),W5=q5;function G0($){if(typeof $!=="object")return{};return $??{}}function U5($){if(!$)return!0;for(let Z in $)return!1;return!0}function tZ($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var eZ=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new P(`${$} must be an integer`);if(Z<0)throw new P(`${$} must be a positive integer`);return Z};var H0=($)=>{try{return JSON.parse($)}catch(Z){return}};var $2=($)=>new Promise((Z)=>setTimeout(Z,$));var V4="0.80.0";var Q2=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function mQ(){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 cQ=()=>{let $=mQ();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V4,"X-Stainless-OS":J2(Deno.build.os),"X-Stainless-Arch":Z2(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":V4,"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":V4,"X-Stainless-OS":J2(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Z2(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=pQ();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":V4,"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":V4,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function pQ(){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:J}of $){let Y=J.exec(navigator.userAgent);if(Y){let Q=Y[1]||0,X=Y[2]||0,K=Y[3]||0;return{browser:Z,version:`${Q}.${X}.${K}`}}}return null}var Z2=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},J2=($)=>{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"},Y2,X2=()=>{return Y2??(Y2=cQ())};function K2(){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 B5(...$){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 q0($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return B5({start(){},async pull(J){let{done:Y,value:Q}=await Z.next();if(Y)J.close();else J.enqueue(Q)},async cancel(){await Z.return?.()}})}function p8($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let J=await Z.read();if(J?.done)Z.releaseLock();return J}catch(J){throw Z.releaseLock(),J}},async return(){let J=Z.cancel();return Z.releaseLock(),await J,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function z2($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),J=Z.cancel();Z.releaseLock(),await J}var V2=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function G2($){return Object.entries($).filter(([Z,J])=>typeof J<"u").map(([Z,J])=>{if(typeof J==="string"||typeof J==="number"||typeof J==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(J)}`;if(J===null)return`${encodeURIComponent(Z)}=`;throw new P(`Cannot stringify type ${typeof J}; 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 W2($){let Z=0;for(let Q of $)Z+=Q.length;let J=new Uint8Array(Z),Y=0;for(let Q of $)J.set(Q,Y),Y+=Q.length;return J}var H2;function u8($){let Z;return(H2??(Z=new globalThis.TextEncoder,H2=Z.encode.bind(Z)))($)}var q2;function N5($){let Z;return(q2??(Z=new globalThis.TextDecoder,q2=Z.decode.bind(Z)))($)}var N$,M$;class G4{constructor(){N$.set(this,void 0),M$.set(this,void 0),D(this,N$,new Uint8Array,"f"),D(this,M$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?u8($):$;D(this,N$,W2([C(this,N$,"f"),Z]),"f");let J=[],Y;while((Y=lQ(C(this,N$,"f"),C(this,M$,"f")))!=null){if(Y.carriage&&C(this,M$,"f")==null){D(this,M$,Y.index,"f");continue}if(C(this,M$,"f")!=null&&(Y.index!==C(this,M$,"f")+1||Y.carriage)){J.push(N5(C(this,N$,"f").subarray(0,C(this,M$,"f")-1))),D(this,N$,C(this,N$,"f").subarray(C(this,M$,"f")),"f"),D(this,M$,null,"f");continue}let Q=C(this,M$,"f")!==null?Y.preceding-1:Y.preceding,X=N5(C(this,N$,"f").subarray(0,Q));J.push(X),D(this,N$,C(this,N$,"f").subarray(Y.index),"f"),D(this,M$,null,"f")}return J}flush(){if(!C(this,N$,"f").length)return[];return this.decode(`
|
|
51
|
-
`)}}
|
|
52
|
-
`,"\r"]);
|
|
53
|
-
`);
|
|
54
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],
|
|
55
|
-
${X.map((
|
|
50
|
+
/export Export markdown /exit Quit`)}function Q0($){console.error(`smolerclaw: ${$}`),process.exit(2)}Z$();n();import{existsSync as N0,mkdirSync as GX,readFileSync as C2}from"fs";import{homedir as HX}from"os";import{join as a$}from"path";var h8=HX(),M0=A?a$(process.env.APPDATA||a$(h8,"AppData","Roaming"),"smolerclaw"):a$(h8,".config","smolerclaw"),T5=A?a$(process.env.LOCALAPPDATA||a$(h8,"AppData","Local"),"smolerclaw"):a$(h8,".local","share","smolerclaw"),B4=a$(M0,"config.json"),J8={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:T5,toolApproval:"auto",language:"auto",maxSessionCost:0};function f8($){if(!N0($))GX($,{recursive:!0})}function N2(){if(f8(M0),f8(T5),f8(a$(T5,"sessions")),A)UX();if(!N0(B4))return S(B4,JSON.stringify(J8,null,2)),{...J8};let $;try{$=JSON.parse(C2(B4,"utf-8"))}catch{return S(B4,JSON.stringify(J8,null,2)),{...J8}}return qX({...J8,...$})}function qX($){let Z={...J8};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 Q=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&Q.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function F0($){f8(M0),S(B4,JSON.stringify($,null,2))}function A5(){return B4}function UX(){let $=a$(h8,".config","smolerclaw","config.json");if(N0($)&&!N0(B4))try{let Z=C2($,"utf-8");f8(M0),S(B4,Z)}catch{}}import{existsSync as WX,readFileSync as BX}from"fs";import{homedir as CX}from"os";import{join as NX}from"path";var M2=NX(CX(),".claude",".credentials.json");function I5(){let $=MX();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 MX(){if(!WX(M2))return null;try{let Z=JSON.parse(BX(M2,"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 x5(){try{return I5()}catch{return null}}function F2($){return`sub:${$.subscriptionType||"pro"}`}function D($,Z,Q,Y,J){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call($,Q):J?J.value=Q:Z.set($,Q),Q}function M($,Z,Q,Y){if(Q==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Q==="m"?Y:Q==="a"?Y.call($):Y?Y.value:Z.get($)}var S5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return S5=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),Q=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^Q()&15>>+Y/4).toString(16))};function n$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var g8=($)=>{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 T extends Error{}class t extends T{constructor($,Z,Q,Y){super(`${t.makeMessage($,Z,Q)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=Z}static makeMessage($,Z,Q){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Q;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,Q,Y){if(!$||!Y)return new y4({message:Q,cause:g8(Z)});let J=Z;if($===400)return new p8($,J,Q,Y);if($===401)return new c8($,J,Q,Y);if($===403)return new u8($,J,Q,Y);if($===404)return new d8($,J,Q,Y);if($===409)return new l8($,J,Q,Y);if($===422)return new o8($,J,Q,Y);if($===429)return new a8($,J,Q,Y);if($>=500)return new n8($,J,Q,Y);return new t($,J,Q,Y)}}class z$ extends t{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class y4 extends t{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class m8 extends y4{constructor({message:$}={}){super({message:$??"Request timed out."})}}class p8 extends t{}class c8 extends t{}class u8 extends t{}class d8 extends t{}class l8 extends t{}class o8 extends t{}class a8 extends t{}class n8 extends t{}var OX=/^[a-z][a-z0-9+.-]*:/i,O2=($)=>{return OX.test($)},w5=($)=>(w5=Array.isArray,w5($)),k5=w5;function O0($){if(typeof $!=="object")return{};return $??{}}function y5($){if(!$)return!0;for(let Z in $)return!1;return!0}function R2($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var E2=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new T(`${$} must be an integer`);if(Z<0)throw new T(`${$} must be a positive integer`);return Z};var R0=($)=>{try{return JSON.parse($)}catch(Z){return}};var L2=($)=>new Promise((Z)=>setTimeout(Z,$));var C4="0.80.0";var T2=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function RX(){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 EX=()=>{let $=RX();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"X-Stainless-OS":D2(Deno.build.os),"X-Stainless-Arch":j2(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":C4,"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":C4,"X-Stainless-OS":D2(globalThis.process.platform??"unknown"),"X-Stainless-Arch":j2(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=LX();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"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":C4,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function LX(){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:Q}of $){let Y=Q.exec(navigator.userAgent);if(Y){let J=Y[1]||0,X=Y[2]||0,K=Y[3]||0;return{browser:Z,version:`${J}.${X}.${K}`}}}return null}var j2=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},D2=($)=>{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"},P2,A2=()=>{return P2??(P2=EX())};function I2(){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 b5(...$){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 E0($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return b5({start(){},async pull(Q){let{done:Y,value:J}=await Z.next();if(Y)Q.close();else Q.enqueue(J)},async cancel(){await Z.return?.()}})}function r8($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let Q=await Z.read();if(Q?.done)Z.releaseLock();return Q}catch(Q){throw Z.releaseLock(),Q}},async return(){let Q=Z.cancel();return Z.releaseLock(),await Q,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function x2($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Q=Z.cancel();Z.releaseLock(),await Q}var S2=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function w2($){return Object.entries($).filter(([Z,Q])=>typeof Q<"u").map(([Z,Q])=>{if(typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(Q)}`;if(Q===null)return`${encodeURIComponent(Z)}=`;throw new T(`Cannot stringify type ${typeof Q}; 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 b2($){let Z=0;for(let J of $)Z+=J.length;let Q=new Uint8Array(Z),Y=0;for(let J of $)Q.set(J,Y),Y+=J.length;return Q}var k2;function i8($){let Z;return(k2??(Z=new globalThis.TextEncoder,k2=Z.encode.bind(Z)))($)}var y2;function _5($){let Z;return(y2??(Z=new globalThis.TextDecoder,y2=Z.decode.bind(Z)))($)}var F$,O$;class N4{constructor(){F$.set(this,void 0),O$.set(this,void 0),D(this,F$,new Uint8Array,"f"),D(this,O$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?i8($):$;D(this,F$,b2([M(this,F$,"f"),Z]),"f");let Q=[],Y;while((Y=PX(M(this,F$,"f"),M(this,O$,"f")))!=null){if(Y.carriage&&M(this,O$,"f")==null){D(this,O$,Y.index,"f");continue}if(M(this,O$,"f")!=null&&(Y.index!==M(this,O$,"f")+1||Y.carriage)){Q.push(_5(M(this,F$,"f").subarray(0,M(this,O$,"f")-1))),D(this,F$,M(this,F$,"f").subarray(M(this,O$,"f")),"f"),D(this,O$,null,"f");continue}let J=M(this,O$,"f")!==null?Y.preceding-1:Y.preceding,X=_5(M(this,F$,"f").subarray(0,J));Q.push(X),D(this,F$,M(this,F$,"f").subarray(Y.index),"f"),D(this,O$,null,"f")}return Q}flush(){if(!M(this,F$,"f").length)return[];return this.decode(`
|
|
51
|
+
`)}}F$=new WeakMap,O$=new WeakMap;N4.NEWLINE_CHARS=new Set([`
|
|
52
|
+
`,"\r"]);N4.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function PX($,Z){for(let J=Z??0;J<$.length;J++){if($[J]===10)return{preceding:J,index:J+1,carriage:!1};if($[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function _2($){for(let Y=0;Y<$.length-1;Y++){if($[Y]===10&&$[Y+1]===10)return Y+2;if($[Y]===13&&$[Y+1]===13)return Y+2;if($[Y]===13&&$[Y+1]===10&&Y+3<$.length&&$[Y+2]===13&&$[Y+3]===10)return Y+4}return-1}var j0={off:0,error:200,warn:300,info:400,debug:500},v5=($,Z,Q)=>{if(!$)return;if(R2(j0,$))return $;Q$(Q).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(j0))}`);return};function s8(){}function L0($,Z,Q){if(!Z||j0[$]>j0[Q])return s8;else return Z[$].bind(Z)}var TX={error:s8,warn:s8,info:s8,debug:s8},v2=new WeakMap;function Q$($){let Z=$.logger,Q=$.logLevel??"off";if(!Z)return TX;let Y=v2.get(Z);if(Y&&Y[0]===Q)return Y[1];let J={error:L0("error",Z,Q),warn:L0("warn",Z,Q),info:L0("info",Z,Q),debug:L0("debug",Z,Q)};return v2.set(Z,[Q,J]),J}var r$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,Q])=>[Z,Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":Q]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var t8;class R${constructor($,Z,Q){this.iterator=$,t8.set(this,void 0),this.controller=Z,D(this,t8,Q,"f")}static fromSSEResponse($,Z,Q){let Y=!1,J=Q?Q$(Q):console;async function*X(){if(Y)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let K=!1;try{for await(let V of AX($,Z)){if(V.event==="completion")try{yield JSON.parse(V.data)}catch(G){throw J.error("Could not parse message into JSON:",V.data),J.error("From chunk:",V.raw),G}if(V.event==="message_start"||V.event==="message_delta"||V.event==="message_stop"||V.event==="content_block_start"||V.event==="content_block_delta"||V.event==="content_block_stop")try{yield JSON.parse(V.data)}catch(G){throw J.error("Could not parse message into JSON:",V.data),J.error("From chunk:",V.raw),G}if(V.event==="ping")continue;if(V.event==="error")throw new t(void 0,R0(V.data)??V.data,void 0,$.headers)}K=!0}catch(V){if(n$(V))return;throw V}finally{if(!K)Z.abort()}}return new R$(X,Z,Q)}static fromReadableStream($,Z,Q){let Y=!1;async function*J(){let K=new N4,V=r8($);for await(let G of V)for(let H of K.decode(G))yield H;for(let G of K.flush())yield G}async function*X(){if(Y)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let K=!1;try{for await(let V of J()){if(K)continue;if(V)yield JSON.parse(V)}K=!0}catch(V){if(n$(V))return;throw V}finally{if(!K)Z.abort()}}return new R$(X,Z,Q)}[(t8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Q=this.iterator(),Y=(J)=>{return{next:()=>{if(J.length===0){let X=Q.next();$.push(X),Z.push(X)}return J.shift()}}};return[new R$(()=>Y($),this.controller,M(this,t8,"f")),new R$(()=>Y(Z),this.controller,M(this,t8,"f"))]}toReadableStream(){let $=this,Z;return b5({async start(){Z=$[Symbol.asyncIterator]()},async pull(Q){try{let{value:Y,done:J}=await Z.next();if(J)return Q.close();let X=i8(JSON.stringify(Y)+`
|
|
53
|
+
`);Q.enqueue(X)}catch(Y){Q.error(Y)}},async cancel(){await Z.return?.()}})}}async function*AX($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new T("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 T("Attempted to iterate over a response with no body")}let Q=new f2,Y=new N4,J=r8($.body);for await(let X of IX(J))for(let K of Y.decode(X)){let V=Q.decode(K);if(V)yield V}for(let X of Y.flush()){let K=Q.decode(X);if(K)yield K}}async function*IX($){let Z=new Uint8Array;for await(let Q of $){if(Q==null)continue;let Y=Q instanceof ArrayBuffer?new Uint8Array(Q):typeof Q==="string"?i8(Q):Q,J=new Uint8Array(Z.length+Y.length);J.set(Z),J.set(Y,Z.length),Z=J;let X;while((X=_2(Z))!==-1)yield Z.slice(0,X),Z=Z.slice(X)}if(Z.length>0)yield Z}class f2{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
|
|
54
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Q,Y]=xX($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function xX($,Z){let Q=$.indexOf(Z);if(Q!==-1)return[$.substring(0,Q),Z,$.substring(Q+Z.length)];return[$,"",""]}async function D0($,Z){let{response:Q,requestLogID:Y,retryOfRequestLogID:J,startTime:X}=Z,K=await(async()=>{if(Z.options.stream){if(Q$($).debug("response",Q.status,Q.url,Q.headers,Q.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Q,Z.controller);return R$.fromSSEResponse(Q,Z.controller)}if(Q.status===204)return null;if(Z.options.__binaryResponse)return Q;let G=Q.headers.get("content-type")?.split(";")[0]?.trim();if(G?.includes("application/json")||G?.endsWith("+json")){if(Q.headers.get("content-length")==="0")return;let W=await Q.json();return f5(W,Q)}return await Q.text()})();return Q$($).debug(`[${Y}] response parsed`,r$({retryOfRequestLogID:J,url:Q.url,status:Q.status,body:K,durationMs:Date.now()-X})),K}function f5($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var e8;class b4 extends Promise{constructor($,Z,Q=D0){super((Y)=>{Y(null)});this.responsePromise=Z,this.parseResponse=Q,e8.set(this,void 0),D(this,e8,$,"f")}_thenUnwrap($){return new b4(M(this,e8,"f"),this.responsePromise,async(Z,Q)=>f5($(await this.parseResponse(Z,Q),Q),Q.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(M(this,e8,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}e8=new WeakMap;var P0;class h5{constructor($,Z,Q,Y){P0.set(this,void 0),D(this,P0,$,"f"),this.options=Y,this.response=Z,this.body=Q}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await M(this,P0,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(P0=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class T0 extends b4{constructor($,Z,Q){super($,Z,async(Y,J)=>new Q(Y,J.response,await D0(Y,J),J.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class y$ extends h5{constructor($,Z,Q,Y){super($,Z,Q,Y);this.data=Q.data||[],this.has_more=Q.has_more||!1,this.first_id=Q.first_id||null,this.last_id=Q.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:{...O0(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...O0(this.options.query),after_id:$}}}}class $1 extends h5{constructor($,Z,Q,Y){super($,Z,Q,Y);this.data=Q.data||[],this.has_more=Q.has_more||!1,this.next_page=Q.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:{...O0(this.options.query),page:$}}}}var m5=()=>{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 _4($,Z,Q){return m5(),new File($,Z??"unknown_file",Q)}function Z1($,Z){let Q=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?Q.split(/[\\/]/).pop()||void 0:Q}var p5=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var X8=async($,Z,Q=!0)=>{return{...$,body:await kX($.body,Z,Q)}},h2=new WeakMap;function wX($){let Z=typeof $==="function"?$:$.fetch,Q=h2.get(Z);if(Q)return Q;let Y=(async()=>{try{let J="Response"in Z?Z.Response:(await Z("data:,")).constructor,X=new FormData;if(X.toString()===await new J(X).text())return!1;return!0}catch{return!0}})();return h2.set(Z,Y),Y}var kX=async($,Z,Q=!0)=>{if(!await wX(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Y=new FormData;return await Promise.all(Object.entries($||{}).map(([J,X])=>g5(Y,J,X,Q))),Y},yX=($)=>$ instanceof Blob&&("name"in $);var g5=async($,Z,Q,Y)=>{if(Q===void 0)return;if(Q==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean")$.append(Z,String(Q));else if(Q instanceof Response){let J={},X=Q.headers.get("Content-Type");if(X)J={type:X};$.append(Z,_4([await Q.blob()],Z1(Q,Y),J))}else if(p5(Q))$.append(Z,_4([await new Response(E0(Q)).blob()],Z1(Q,Y)));else if(yX(Q))$.append(Z,_4([Q],Z1(Q,Y),{type:Q.type}));else if(Array.isArray(Q))await Promise.all(Q.map((J)=>g5($,Z+"[]",J,Y)));else if(typeof Q==="object")await Promise.all(Object.entries(Q).map(([J,X])=>g5($,`${Z}[${J}]`,X,Y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Q} instead`)};var g2=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",bX=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&g2($),_X=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function A0($,Z,Q){if(m5(),$=await $,Z||(Z=Z1($,!0)),bX($)){if($ instanceof File&&Z==null&&Q==null)return $;return _4([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Q})}if(_X($)){let J=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),_4(await c5(J),Z,Q)}let Y=await c5($);if(!Q?.type){let J=Y.find((X)=>typeof X==="object"&&("type"in X)&&X.type);if(typeof J==="string")Q={...Q,type:J}}return _4(Y,Z,Q)}async function c5($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(g2($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(p5($))for await(let Q of $)Z.push(...await c5(Q));else{let Q=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Q?`; constructor: ${Q}`:""}${vX($)}`)}return Z}function vX($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Q)=>`"${Q}"`).join(", ")}]`}class l{constructor($){this._client=$}}var m2=Symbol.for("brand.privateNullableHeaders");function*hX($){if(!$)return;if(m2 in $){let{values:Y,nulls:J}=$;yield*Y.entries();for(let X of J)yield[X,null];return}let Z=!1,Q;if($ instanceof Headers)Q=$.entries();else if(k5($))Q=$;else Z=!0,Q=Object.entries($??{});for(let Y of Q){let J=Y[0];if(typeof J!=="string")throw TypeError("expected header name to be a string");let X=k5(Y[1])?Y[1]:[Y[1]],K=!1;for(let V of X){if(V===void 0)continue;if(Z&&!K)K=!0,yield[J,null];yield[J,V]}}}var k=($)=>{let Z=new Headers,Q=new Set;for(let Y of $){let J=new Set;for(let[X,K]of hX(Y)){let V=X.toLowerCase();if(!J.has(V))Z.delete(X),J.add(V);if(K===null)Z.delete(X),Q.add(V);else Z.append(X,K),Q.delete(V)}}return{[m2]:!0,values:Z,nulls:Q}};var Q1=Symbol("anthropic.sdk.stainlessHelper");function I0($){return typeof $==="object"&&$!==null&&Q1 in $}function u5($,Z){let Q=new Set;if($){for(let Y of $)if(I0(Y))Q.add(Y[Q1])}if(Z)for(let Y of Z){if(I0(Y))Q.add(Y[Q1]);if(Array.isArray(Y.content)){for(let J of Y.content)if(I0(J))Q.add(J[Q1])}}return Array.from(Q)}function x0($,Z){let Q=u5($,Z);if(Q.length===0)return{};return{"x-stainless-helper":Q.join(", ")}}function p2($){if(I0($))return{"x-stainless-helper":$[Q1]};return{}}function u2($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var c2=Object.freeze(Object.create(null)),gX=($=u2)=>function(Q,...Y){if(Q.length===1)return Q[0];let J=!1,X=[],K=Q.reduce((z,B,W)=>{if(/[?#]/.test(B))J=!0;let N=Y[W],O=(J?encodeURIComponent:$)(""+N);if(W!==Y.length&&(N==null||typeof N==="object"&&N.toString===Object.getPrototypeOf(Object.getPrototypeOf(N.hasOwnProperty??c2)??c2)?.toString))O=N+"",X.push({start:z.length+B.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(N).slice(8,-1)} is not a valid path parameter`});return z+B+(W===Y.length?"":O)},""),V=K.split(/[?#]/,1)[0],G=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,H;while((H=G.exec(V))!==null)X.push({start:H.index,length:H[0].length,error:`Value "${H[0]}" can't be safely passed as a path parameter`});if(X.sort((z,B)=>z.start-B.start),X.length>0){let z=0,B=X.reduce((W,N)=>{let O=" ".repeat(N.start-z),j="^".repeat(N.length);return z=N.start+N.length,W+O+j},"");throw new T(`Path parameters result in path with invalid segments:
|
|
55
|
+
${X.map((W)=>W.error).join(`
|
|
56
56
|
`)}
|
|
57
57
|
${K}
|
|
58
|
-
${U}`)}return K},m=XX(R2);class n8 extends p{list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/files",I$,{query:Y,...Z,headers:S([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(m`/v1/files/${$}`,{...J,headers:S([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},J?.headers])})}download($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/files/${$}/content`,{...J,headers:S([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},J?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/files/${$}`,{...J,headers:S([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},J?.headers])})}upload($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/files",t4({body:Y,...Z,headers:S([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},O2(Y.file),Z?.headers])},this._client))}}class s8 extends p{retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/models/${$}?beta=true`,{...J,headers:S([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/models?beta=true",I$,{query:Y,...Z,headers:S([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers])})}}var F0={"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 E2($){return $?.output_format??$?.output_config?.format}function D5($,Z,J){let Y=E2(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text"){let X=Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(X,"parsed",{get(){return J.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Q}),parsed_output:null};return T5($,Z,J)}function T5($,Z,J){let Y=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=VX(Z,X.text);if(Y===null)Y=K;let V=Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1});return Object.defineProperty(V,"parsed",{get(){return J.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),K},enumerable:!1})}return X});return{...$,content:Q,parsed_output:Y}}function VX($,Z){let J=E2($);if(J?.type!=="json_schema")return null;try{if("parse"in J)return J.parse(Z);return JSON.parse(Z)}catch(Y){throw new P(`Failed to parse structured output: ${Y}`)}}var GX=($)=>{let Z=0,J=[];while(Z<$.length){let Y=$[Z];if(Y==="\\"){Z++;continue}if(Y==="{"){J.push({type:"brace",value:"{"}),Z++;continue}if(Y==="}"){J.push({type:"brace",value:"}"}),Z++;continue}if(Y==="["){J.push({type:"paren",value:"["}),Z++;continue}if(Y==="]"){J.push({type:"paren",value:"]"}),Z++;continue}if(Y===":"){J.push({type:"separator",value:":"}),Z++;continue}if(Y===","){J.push({type:"delimiter",value:","}),Z++;continue}if(Y==='"'){let V="",G=!1;Y=$[++Z];while(Y!=='"'){if(Z===$.length){G=!0;break}if(Y==="\\"){if(Z++,Z===$.length){G=!0;break}V+=Y+$[Z],Y=$[++Z]}else V+=Y,Y=$[++Z]}if(Y=$[++Z],!G)J.push({type:"string",value:V});continue}if(Y&&/\s/.test(Y)){Z++;continue}let X=/[0-9]/;if(Y&&X.test(Y)||Y==="-"||Y==="."){let V="";if(Y==="-")V+=Y,Y=$[++Z];while(Y&&X.test(Y)||Y===".")V+=Y,Y=$[++Z];J.push({type:"number",value:V});continue}let K=/[a-z]/i;if(Y&&K.test(Y)){let V="";while(Y&&K.test(Y)){if(Z===$.length)break;V+=Y,Y=$[++Z]}if(V=="true"||V=="false"||V==="null")J.push({type:"name",value:V});else{Z++;continue}continue}Z++}return J},e4=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),e4($);break;case"number":let J=Z.value[Z.value.length-1];if(J==="."||J==="-")return $=$.slice(0,$.length-1),e4($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),e4($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),e4($);break;case"delimiter":return $=$.slice(0,$.length-1),e4($);break}return $},HX=($)=>{let Z=[];if($.map((J)=>{if(J.type==="brace")if(J.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(J.type==="paren")if(J.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((J)=>{if(J==="}")$.push({type:"brace",value:"}"});else if(J==="]")$.push({type:"paren",value:"]"})});return $},qX=($)=>{let Z="";return $.map((J)=>{switch(J.type){case"string":Z+='"'+J.value+'"';break;default:Z+=J.value;break}}),Z},R0=($)=>JSON.parse(qX(HX(e4(GX($)))));var L$,H4,$8,t8,E0,e8,$1,L0,Z1,p$,J1,D0,T0,x4,P0,A0,Y1,P5,L2,I0,A5,I5,x5,D2,T2="__json_buf";function P2($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class Q1{constructor($,Z){L$.add(this),this.messages=[],this.receivedMessages=[],H4.set(this,void 0),$8.set(this,null),this.controller=new AbortController,t8.set(this,void 0),E0.set(this,()=>{}),e8.set(this,()=>{}),$1.set(this,void 0),L0.set(this,()=>{}),Z1.set(this,()=>{}),p$.set(this,{}),J1.set(this,!1),D0.set(this,!1),T0.set(this,!1),x4.set(this,!1),P0.set(this,void 0),A0.set(this,void 0),Y1.set(this,void 0),I0.set(this,(J)=>{if(D(this,D0,!0,"f"),m$(J))J=new Q$;if(J instanceof Q$)return D(this,T0,!0,"f"),this._emit("abort",J);if(J instanceof P)return this._emit("error",J);if(J instanceof Error){let Y=new P(J.message);return Y.cause=J,this._emit("error",Y)}return this._emit("error",new P(String(J)))}),D(this,t8,new Promise((J,Y)=>{D(this,E0,J,"f"),D(this,e8,Y,"f")}),"f"),D(this,$1,new Promise((J,Y)=>{D(this,L0,J,"f"),D(this,Z1,Y,"f")}),"f"),C(this,t8,"f").catch(()=>{}),C(this,$1,"f").catch(()=>{}),D(this,$8,$,"f"),D(this,Y1,Z?.logger??console,"f")}get response(){return C(this,P0,"f")}get request_id(){return C(this,A0,"f")}async withResponse(){D(this,x4,!0,"f");let $=await C(this,t8,"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 Q1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,J,{logger:Y}={}){let Q=new Q1(Z,{logger:Y});for(let X of Z.messages)Q._addMessageParam(X);return D(Q,$8,{...Z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...Z,stream:!0},{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},C(this,I0,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,J){let Y=J?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{C(this,L$,"m",A5).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...J,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)C(this,L$,"m",I5).call(this,V);if(K.controller.signal?.aborted)throw new Q$;C(this,L$,"m",x5).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;D(this,P0,$,"f"),D(this,A0,$?.headers.get("request-id"),"f"),C(this,E0,"f").call(this,$),this._emit("connect")}get ended(){return C(this,J1,"f")}get errored(){return C(this,D0,"f")}get aborted(){return C(this,T0,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,p$,"f")[$]||(C(this,p$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let J=C(this,p$,"f")[$];if(!J)return this;let Y=J.findIndex((Q)=>Q.listener===Z);if(Y>=0)J.splice(Y,1);return this}once($,Z){return(C(this,p$,"f")[$]||(C(this,p$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,J)=>{if(D(this,x4,!0,"f"),$!=="error")this.once("error",J);this.once($,Z)})}async done(){D(this,x4,!0,"f"),await C(this,$1,"f")}get currentMessage(){return C(this,H4,"f")}async finalMessage(){return await this.done(),C(this,L$,"m",P5).call(this)}async finalText(){return await this.done(),C(this,L$,"m",L2).call(this)}_emit($,...Z){if(C(this,J1,"f"))return;if($==="end")D(this,J1,!0,"f"),C(this,L0,"f").call(this);let J=C(this,p$,"f")[$];if(J)C(this,p$,"f")[$]=J.filter((Y)=>!Y.once),J.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!C(this,x4,"f")&&!J?.length)Promise.reject(Y);C(this,e8,"f").call(this,Y),C(this,Z1,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!C(this,x4,"f")&&!J?.length)Promise.reject(Y);C(this,e8,"f").call(this,Y),C(this,Z1,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,L$,"m",P5).call(this))}async _fromReadableStream($,Z){let J=Z?.signal,Y;if(J){if(J.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),J.addEventListener("abort",Y)}try{C(this,L$,"m",A5).call(this),this._connected(null);let Q=C$.fromReadableStream($,this.controller);for await(let X of Q)C(this,L$,"m",I5).call(this,X);if(Q.controller.signal?.aborted)throw new Q$;C(this,L$,"m",x5).call(this)}finally{if(J&&Y)J.removeEventListener("abort",Y)}}[(H4=new WeakMap,$8=new WeakMap,t8=new WeakMap,E0=new WeakMap,e8=new WeakMap,$1=new WeakMap,L0=new WeakMap,Z1=new WeakMap,p$=new WeakMap,J1=new WeakMap,D0=new WeakMap,T0=new WeakMap,x4=new WeakMap,P0=new WeakMap,A0=new WeakMap,Y1=new WeakMap,I0=new WeakMap,L$=new WeakSet,P5=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},L2=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((J)=>J.type==="text").map((J)=>J.text);if(Z.length===0)throw new P("stream ended without producing a content block with type=text");return Z.join(" ")},A5=function(){if(this.ended)return;D(this,H4,void 0,"f")},I5=function(Z){if(this.ended)return;let J=C(this,L$,"m",D2).call(this,Z);switch(this._emit("streamEvent",Z,J),Z.type){case"content_block_delta":{let Y=J.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(P2(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:A2(Z.delta)}break}case"message_stop":{this._addMessageParam(J),this._addMessage(D5(J,C(this,$8,"f"),{logger:C(this,Y1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",J.content.at(-1));break}case"message_start":{D(this,H4,J,"f");break}case"content_block_start":case"message_delta":break}},x5=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let Z=C(this,H4,"f");if(!Z)throw new P("request ended without sending any chunks");return D(this,H4,void 0,"f"),D5(Z,C(this,$8,"f"),{logger:C(this,Y1,"f")})},D2=function(Z){let J=C(this,H4,"f");if(Z.type==="message_start"){if(J)throw new P(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!J)throw new P(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return J;case"message_delta":if(J.container=Z.delta.container,J.stop_reason=Z.delta.stop_reason,J.stop_sequence=Z.delta.stop_sequence,J.usage.output_tokens=Z.usage.output_tokens,J.context_management=Z.context_management,Z.usage.input_tokens!=null)J.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)J.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)J.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)J.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)J.usage.iterations=Z.usage.iterations;return J;case"content_block_start":return J.content.push(Z.content_block),J;case"content_block_delta":{let Y=J.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&P2(Y)){let Q=Y[T2]||"";Q+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,T2,{value:Q,enumerable:!1,writable:!0}),Q)try{X.input=R0(Q)}catch(K){let V=new P(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${K}. JSON: ${Q}`);C(this,I0,"f").call(this,V)}J.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,signature:Z.delta.signature};break}case"compaction_delta":{if(Y?.type==="compaction")J.content[Z.index]={...Y,content:(Y.content||"")+Z.delta.content};break}default:A2(Z.delta)}return J}case"content_block_stop":return J}},Symbol.asyncIterator)](){let $=[],Z=[],J=!1;return this.on("streamEvent",(Y)=>{let Q=Z.shift();if(Q)Q.resolve(Y);else $.push(Y)}),this.on("end",()=>{J=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),this.on("error",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(J)return{value:void 0,done:!0};return new Promise((Q,X)=>Z.push({resolve:Q,reject:X})).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 C$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function A2($){}class Z8 extends Error{constructor($){let Z=typeof $==="string"?$:$.map((J)=>{if(J.type==="text")return J.text;return`[${J.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var I2=1e5,x2=`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:
|
|
58
|
+
${B}`)}return K},d=gX(u2);class Y1 extends l{list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/files",y$,{query:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Q){let{betas:Y}=Z??{};return this._client.delete(d`/v1/files/${$}`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Q?.headers])})}download($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/files/${$}/content`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Q?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/files/${$}`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Q?.headers])})}upload($,Z){let{betas:Q,...Y}=$;return this._client.post("/v1/files",X8({body:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},p2(Y.file),Z?.headers])},this._client))}}class J1 extends l{retrieve($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/models/${$}?beta=true`,{...Q,headers:k([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Q?.headers])})}list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/models?beta=true",y$,{query:Y,...Z,headers:k([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Z?.headers])})}}var S0={"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 d2($){return $?.output_format??$?.output_config?.format}function d5($,Z,Q){let Y=d2(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text"){let X=Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(X,"parsed",{get(){return Q.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return J}),parsed_output:null};return l5($,Z,Q)}function l5($,Z,Q){let Y=null,J=$.content.map((X)=>{if(X.type==="text"){let K=cX(Z,X.text);if(Y===null)Y=K;let V=Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1});return Object.defineProperty(V,"parsed",{get(){return Q.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),K},enumerable:!1})}return X});return{...$,content:J,parsed_output:Y}}function cX($,Z){let Q=d2($);if(Q?.type!=="json_schema")return null;try{if("parse"in Q)return Q.parse(Z);return JSON.parse(Z)}catch(Y){throw new T(`Failed to parse structured output: ${Y}`)}}var uX=($)=>{let Z=0,Q=[];while(Z<$.length){let Y=$[Z];if(Y==="\\"){Z++;continue}if(Y==="{"){Q.push({type:"brace",value:"{"}),Z++;continue}if(Y==="}"){Q.push({type:"brace",value:"}"}),Z++;continue}if(Y==="["){Q.push({type:"paren",value:"["}),Z++;continue}if(Y==="]"){Q.push({type:"paren",value:"]"}),Z++;continue}if(Y===":"){Q.push({type:"separator",value:":"}),Z++;continue}if(Y===","){Q.push({type:"delimiter",value:","}),Z++;continue}if(Y==='"'){let V="",G=!1;Y=$[++Z];while(Y!=='"'){if(Z===$.length){G=!0;break}if(Y==="\\"){if(Z++,Z===$.length){G=!0;break}V+=Y+$[Z],Y=$[++Z]}else V+=Y,Y=$[++Z]}if(Y=$[++Z],!G)Q.push({type:"string",value:V});continue}if(Y&&/\s/.test(Y)){Z++;continue}let X=/[0-9]/;if(Y&&X.test(Y)||Y==="-"||Y==="."){let V="";if(Y==="-")V+=Y,Y=$[++Z];while(Y&&X.test(Y)||Y===".")V+=Y,Y=$[++Z];Q.push({type:"number",value:V});continue}let K=/[a-z]/i;if(Y&&K.test(Y)){let V="";while(Y&&K.test(Y)){if(Z===$.length)break;V+=Y,Y=$[++Z]}if(V=="true"||V=="false"||V==="null")Q.push({type:"name",value:V});else{Z++;continue}continue}Z++}return Q},K8=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),K8($);break;case"number":let Q=Z.value[Z.value.length-1];if(Q==="."||Q==="-")return $=$.slice(0,$.length-1),K8($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),K8($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),K8($);break;case"delimiter":return $=$.slice(0,$.length-1),K8($);break}return $},dX=($)=>{let Z=[];if($.map((Q)=>{if(Q.type==="brace")if(Q.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(Q.type==="paren")if(Q.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((Q)=>{if(Q==="}")$.push({type:"brace",value:"}"});else if(Q==="]")$.push({type:"paren",value:"]"})});return $},lX=($)=>{let Z="";return $.map((Q)=>{switch(Q.type){case"string":Z+='"'+Q.value+'"';break;default:Z+=Q.value;break}}),Z},w0=($)=>JSON.parse(lX(dX(K8(uX($)))));var T$,M4,z8,X1,k0,K1,z1,y0,V1,i$,G1,b0,_0,v4,v0,f0,H1,o5,l2,h0,a5,n5,r5,o2,a2="__json_buf";function n2($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class q1{constructor($,Z){T$.add(this),this.messages=[],this.receivedMessages=[],M4.set(this,void 0),z8.set(this,null),this.controller=new AbortController,X1.set(this,void 0),k0.set(this,()=>{}),K1.set(this,()=>{}),z1.set(this,void 0),y0.set(this,()=>{}),V1.set(this,()=>{}),i$.set(this,{}),G1.set(this,!1),b0.set(this,!1),_0.set(this,!1),v4.set(this,!1),v0.set(this,void 0),f0.set(this,void 0),H1.set(this,void 0),h0.set(this,(Q)=>{if(D(this,b0,!0,"f"),n$(Q))Q=new z$;if(Q instanceof z$)return D(this,_0,!0,"f"),this._emit("abort",Q);if(Q instanceof T)return this._emit("error",Q);if(Q instanceof Error){let Y=new T(Q.message);return Y.cause=Q,this._emit("error",Y)}return this._emit("error",new T(String(Q)))}),D(this,X1,new Promise((Q,Y)=>{D(this,k0,Q,"f"),D(this,K1,Y,"f")}),"f"),D(this,z1,new Promise((Q,Y)=>{D(this,y0,Q,"f"),D(this,V1,Y,"f")}),"f"),M(this,X1,"f").catch(()=>{}),M(this,z1,"f").catch(()=>{}),D(this,z8,$,"f"),D(this,H1,Z?.logger??console,"f")}get response(){return M(this,v0,"f")}get request_id(){return M(this,f0,"f")}async withResponse(){D(this,v4,!0,"f");let $=await M(this,X1,"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 q1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Q,{logger:Y}={}){let J=new q1(Z,{logger:Y});for(let X of Z.messages)J._addMessageParam(X);return D(J,z8,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},M(this,h0,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Q){let Y=Q?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{M(this,T$,"m",a5).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...Q,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)M(this,T$,"m",n5).call(this,V);if(K.controller.signal?.aborted)throw new z$;M(this,T$,"m",r5).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}_connected($){if(this.ended)return;D(this,v0,$,"f"),D(this,f0,$?.headers.get("request-id"),"f"),M(this,k0,"f").call(this,$),this._emit("connect")}get ended(){return M(this,G1,"f")}get errored(){return M(this,b0,"f")}get aborted(){return M(this,_0,"f")}abort(){this.controller.abort()}on($,Z){return(M(this,i$,"f")[$]||(M(this,i$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Q=M(this,i$,"f")[$];if(!Q)return this;let Y=Q.findIndex((J)=>J.listener===Z);if(Y>=0)Q.splice(Y,1);return this}once($,Z){return(M(this,i$,"f")[$]||(M(this,i$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Q)=>{if(D(this,v4,!0,"f"),$!=="error")this.once("error",Q);this.once($,Z)})}async done(){D(this,v4,!0,"f"),await M(this,z1,"f")}get currentMessage(){return M(this,M4,"f")}async finalMessage(){return await this.done(),M(this,T$,"m",o5).call(this)}async finalText(){return await this.done(),M(this,T$,"m",l2).call(this)}_emit($,...Z){if(M(this,G1,"f"))return;if($==="end")D(this,G1,!0,"f"),M(this,y0,"f").call(this);let Q=M(this,i$,"f")[$];if(Q)M(this,i$,"f")[$]=Q.filter((Y)=>!Y.once),Q.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!M(this,v4,"f")&&!Q?.length)Promise.reject(Y);M(this,K1,"f").call(this,Y),M(this,V1,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!M(this,v4,"f")&&!Q?.length)Promise.reject(Y);M(this,K1,"f").call(this,Y),M(this,V1,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",M(this,T$,"m",o5).call(this))}async _fromReadableStream($,Z){let Q=Z?.signal,Y;if(Q){if(Q.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Q.addEventListener("abort",Y)}try{M(this,T$,"m",a5).call(this),this._connected(null);let J=R$.fromReadableStream($,this.controller);for await(let X of J)M(this,T$,"m",n5).call(this,X);if(J.controller.signal?.aborted)throw new z$;M(this,T$,"m",r5).call(this)}finally{if(Q&&Y)Q.removeEventListener("abort",Y)}}[(M4=new WeakMap,z8=new WeakMap,X1=new WeakMap,k0=new WeakMap,K1=new WeakMap,z1=new WeakMap,y0=new WeakMap,V1=new WeakMap,i$=new WeakMap,G1=new WeakMap,b0=new WeakMap,_0=new WeakMap,v4=new WeakMap,v0=new WeakMap,f0=new WeakMap,H1=new WeakMap,h0=new WeakMap,T$=new WeakSet,o5=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},l2=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Q)=>Q.type==="text").map((Q)=>Q.text);if(Z.length===0)throw new T("stream ended without producing a content block with type=text");return Z.join(" ")},a5=function(){if(this.ended)return;D(this,M4,void 0,"f")},n5=function(Z){if(this.ended)return;let Q=M(this,T$,"m",o2).call(this,Z);switch(this._emit("streamEvent",Z,Q),Z.type){case"content_block_delta":{let Y=Q.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(n2(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:r2(Z.delta)}break}case"message_stop":{this._addMessageParam(Q),this._addMessage(d5(Q,M(this,z8,"f"),{logger:M(this,H1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Q.content.at(-1));break}case"message_start":{D(this,M4,Q,"f");break}case"content_block_start":case"message_delta":break}},r5=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let Z=M(this,M4,"f");if(!Z)throw new T("request ended without sending any chunks");return D(this,M4,void 0,"f"),d5(Z,M(this,z8,"f"),{logger:M(this,H1,"f")})},o2=function(Z){let Q=M(this,M4,"f");if(Z.type==="message_start"){if(Q)throw new T(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Q)throw new T(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Q;case"message_delta":if(Q.container=Z.delta.container,Q.stop_reason=Z.delta.stop_reason,Q.stop_sequence=Z.delta.stop_sequence,Q.usage.output_tokens=Z.usage.output_tokens,Q.context_management=Z.context_management,Z.usage.input_tokens!=null)Q.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Q.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Q.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Q.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)Q.usage.iterations=Z.usage.iterations;return Q;case"content_block_start":return Q.content.push(Z.content_block),Q;case"content_block_delta":{let Y=Q.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&n2(Y)){let J=Y[a2]||"";J+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,a2,{value:J,enumerable:!1,writable:!0}),J)try{X.input=w0(J)}catch(K){let V=new T(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${K}. JSON: ${J}`);M(this,h0,"f").call(this,V)}Q.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,signature:Z.delta.signature};break}case"compaction_delta":{if(Y?.type==="compaction")Q.content[Z.index]={...Y,content:(Y.content||"")+Z.delta.content};break}default:r2(Z.delta)}return Q}case"content_block_stop":return Q}},Symbol.asyncIterator)](){let $=[],Z=[],Q=!1;return this.on("streamEvent",(Y)=>{let J=Z.shift();if(J)J.resolve(Y);else $.push(Y)}),this.on("end",()=>{Q=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),this.on("error",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(Q)return{value:void 0,done:!0};return new Promise((J,X)=>Z.push({resolve:J,reject:X})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new R$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function r2($){}class V8 extends Error{constructor($){let Z=typeof $==="string"?$:$.map((Q)=>{if(Q.type==="text")return Q.text;return`[${Q.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var i2=1e5,s2=`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:
|
|
59
59
|
1. Task Overview
|
|
60
60
|
The user's core request and success criteria
|
|
61
61
|
Any clarifications or constraints they specified
|
|
@@ -77,89 +77,122 @@ User preferences or style requirements
|
|
|
77
77
|
Domain-specific details that aren't obvious
|
|
78
78
|
Any promises made to the user
|
|
79
79
|
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.
|
|
80
|
-
Wrap your summary in <summary></summary> tags.`;var
|
|
81
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Q.model in BX&&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 X=this._client._options.timeout;if(!Q.stream&&X==null){let V=F0[Q.model]??void 0;X=this._client.calculateNonstreamingTimeout(Q.max_tokens,V)}let K=O0(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:X??600000,...Z,headers:S([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},K,Z?.headers]),stream:J.stream??!1})}parse($,Z){return Z={...Z,headers:S([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((J)=>T5(J,$,{logger:this._client.logger??console}))}stream($,Z){return Q1.createMessage(this,$,Z)}countTokens($,Z){let J=b2($),{betas:Y,...Q}=J;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...Z,headers:S([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new V1(this._client,$,Z)}}function b2($){if(!$.output_format)return $;if($.output_config?.format)throw new P("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...J}=$;return{...J,output_config:{...$.output_config,format:Z}}}W4.Batches=G1;W4.BetaToolRunner=V1;W4.ToolError=Z8;class H1 extends p{create($,Z={},J){let{betas:Y,...Q}=Z??{};return this._client.post(m`/v1/skills/${$}/versions?beta=true`,t4({body:Q,...J,headers:S([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])},this._client))}retrieve($,Z,J){let{skill_id:Y,betas:Q}=Z;return this._client.get(m`/v1/skills/${Y}/versions/${$}?beta=true`,{...J,headers:S([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},J?.headers])})}list($,Z={},J){let{betas:Y,...Q}=Z??{};return this._client.getAPIList(m`/v1/skills/${$}/versions?beta=true`,a8,{query:Q,...J,headers:S([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}delete($,Z,J){let{skill_id:Y,betas:Q}=Z;return this._client.delete(m`/v1/skills/${Y}/versions/${$}?beta=true`,{...J,headers:S([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},J?.headers])})}}class Q8 extends p{constructor(){super(...arguments);this.versions=new H1(this._client)}create($={},Z){let{betas:J,...Y}=$??{};return this._client.post("/v1/skills?beta=true",t4({body:Y,...Z,headers:S([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/skills/${$}?beta=true`,{...J,headers:S([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",a8,{query:Y,...Z,headers:S([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(m`/v1/skills/${$}?beta=true`,{...J,headers:S([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}}Q8.Versions=H1;class w$ extends p{constructor(){super(...arguments);this.models=new s8(this._client),this.messages=new W4(this._client),this.files=new n8(this._client),this.skills=new Q8(this._client)}}w$.Models=s8;w$.Messages=W4;w$.Files=n8;w$.Skills=Q8;class X8 extends p{create($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...Z,headers:S([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function y2($){return $?.output_config?.format}function w5($,Z,J){let Y=y2(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 k5($,Z,J)}function k5($,Z,J){let Y=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=jX(Z,X.text);if(Y===null)Y=K;return Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1})}return X});return{...$,content:Q,parsed_output:Y}}function jX($,Z){let J=y2($);if(J?.type!=="json_schema")return null;try{if("parse"in J)return J.parse(Z);return JSON.parse(Z)}catch(Y){throw new P(`Failed to parse structured output: ${Y}`)}}var D$,U4,K8,q1,x0,W1,U1,S0,B1,d$,N1,w0,k0,w4,b0,y0,M1,b5,_2,y5,_5,v5,f5,v2,f2="__json_buf";function h2($){return $.type==="tool_use"||$.type==="server_tool_use"}class C1{constructor($,Z){D$.add(this),this.messages=[],this.receivedMessages=[],U4.set(this,void 0),K8.set(this,null),this.controller=new AbortController,q1.set(this,void 0),x0.set(this,()=>{}),W1.set(this,()=>{}),U1.set(this,void 0),S0.set(this,()=>{}),B1.set(this,()=>{}),d$.set(this,{}),N1.set(this,!1),w0.set(this,!1),k0.set(this,!1),w4.set(this,!1),b0.set(this,void 0),y0.set(this,void 0),M1.set(this,void 0),y5.set(this,(J)=>{if(D(this,w0,!0,"f"),m$(J))J=new Q$;if(J instanceof Q$)return D(this,k0,!0,"f"),this._emit("abort",J);if(J instanceof P)return this._emit("error",J);if(J instanceof Error){let Y=new P(J.message);return Y.cause=J,this._emit("error",Y)}return this._emit("error",new P(String(J)))}),D(this,q1,new Promise((J,Y)=>{D(this,x0,J,"f"),D(this,W1,Y,"f")}),"f"),D(this,U1,new Promise((J,Y)=>{D(this,S0,J,"f"),D(this,B1,Y,"f")}),"f"),C(this,q1,"f").catch(()=>{}),C(this,U1,"f").catch(()=>{}),D(this,K8,$,"f"),D(this,M1,Z?.logger??console,"f")}get response(){return C(this,b0,"f")}get request_id(){return C(this,y0,"f")}async withResponse(){D(this,w4,!0,"f");let $=await C(this,q1,"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 C1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,J,{logger:Y}={}){let Q=new C1(Z,{logger:Y});for(let X of Z.messages)Q._addMessageParam(X);return D(Q,K8,{...Z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...Z,stream:!0},{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},C(this,y5,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,J){let Y=J?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{C(this,D$,"m",_5).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...J,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)C(this,D$,"m",v5).call(this,V);if(K.controller.signal?.aborted)throw new Q$;C(this,D$,"m",f5).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;D(this,b0,$,"f"),D(this,y0,$?.headers.get("request-id"),"f"),C(this,x0,"f").call(this,$),this._emit("connect")}get ended(){return C(this,N1,"f")}get errored(){return C(this,w0,"f")}get aborted(){return C(this,k0,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,d$,"f")[$]||(C(this,d$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let J=C(this,d$,"f")[$];if(!J)return this;let Y=J.findIndex((Q)=>Q.listener===Z);if(Y>=0)J.splice(Y,1);return this}once($,Z){return(C(this,d$,"f")[$]||(C(this,d$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,J)=>{if(D(this,w4,!0,"f"),$!=="error")this.once("error",J);this.once($,Z)})}async done(){D(this,w4,!0,"f"),await C(this,U1,"f")}get currentMessage(){return C(this,U4,"f")}async finalMessage(){return await this.done(),C(this,D$,"m",b5).call(this)}async finalText(){return await this.done(),C(this,D$,"m",_2).call(this)}_emit($,...Z){if(C(this,N1,"f"))return;if($==="end")D(this,N1,!0,"f"),C(this,S0,"f").call(this);let J=C(this,d$,"f")[$];if(J)C(this,d$,"f")[$]=J.filter((Y)=>!Y.once),J.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!C(this,w4,"f")&&!J?.length)Promise.reject(Y);C(this,W1,"f").call(this,Y),C(this,B1,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!C(this,w4,"f")&&!J?.length)Promise.reject(Y);C(this,W1,"f").call(this,Y),C(this,B1,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,D$,"m",b5).call(this))}async _fromReadableStream($,Z){let J=Z?.signal,Y;if(J){if(J.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),J.addEventListener("abort",Y)}try{C(this,D$,"m",_5).call(this),this._connected(null);let Q=C$.fromReadableStream($,this.controller);for await(let X of Q)C(this,D$,"m",v5).call(this,X);if(Q.controller.signal?.aborted)throw new Q$;C(this,D$,"m",f5).call(this)}finally{if(J&&Y)J.removeEventListener("abort",Y)}}[(U4=new WeakMap,K8=new WeakMap,q1=new WeakMap,x0=new WeakMap,W1=new WeakMap,U1=new WeakMap,S0=new WeakMap,B1=new WeakMap,d$=new WeakMap,N1=new WeakMap,w0=new WeakMap,k0=new WeakMap,w4=new WeakMap,b0=new WeakMap,y0=new WeakMap,M1=new WeakMap,y5=new WeakMap,D$=new WeakSet,b5=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},_2=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((J)=>J.type==="text").map((J)=>J.text);if(Z.length===0)throw new P("stream ended without producing a content block with type=text");return Z.join(" ")},_5=function(){if(this.ended)return;D(this,U4,void 0,"f")},v5=function(Z){if(this.ended)return;let J=C(this,D$,"m",v2).call(this,Z);switch(this._emit("streamEvent",Z,J),Z.type){case"content_block_delta":{let Y=J.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(h2(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:g2(Z.delta)}break}case"message_stop":{this._addMessageParam(J),this._addMessage(w5(J,C(this,K8,"f"),{logger:C(this,M1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",J.content.at(-1));break}case"message_start":{D(this,U4,J,"f");break}case"content_block_start":case"message_delta":break}},f5=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let Z=C(this,U4,"f");if(!Z)throw new P("request ended without sending any chunks");return D(this,U4,void 0,"f"),w5(Z,C(this,K8,"f"),{logger:C(this,M1,"f")})},v2=function(Z){let J=C(this,U4,"f");if(Z.type==="message_start"){if(J)throw new P(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!J)throw new P(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return J;case"message_delta":if(J.stop_reason=Z.delta.stop_reason,J.stop_sequence=Z.delta.stop_sequence,J.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)J.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)J.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)J.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)J.usage.server_tool_use=Z.usage.server_tool_use;return J;case"content_block_start":return J.content.push({...Z.content_block}),J;case"content_block_delta":{let Y=J.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&h2(Y)){let Q=Y[f2]||"";Q+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,f2,{value:Q,enumerable:!1,writable:!0}),Q)X.input=R0(Q);J.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,signature:Z.delta.signature};break}default:g2(Z.delta)}return J}case"content_block_stop":return J}},Symbol.asyncIterator)](){let $=[],Z=[],J=!1;return this.on("streamEvent",(Y)=>{let Q=Z.shift();if(Q)Q.resolve(Y);else $.push(Y)}),this.on("end",()=>{J=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),this.on("error",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(J)return{value:void 0,done:!0};return new Promise((Q,X)=>Z.push({resolve:Q,reject:X})).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 C$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function g2($){}class j1 extends p{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(m`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",I$,{query:$,...Z})}delete($,Z){return this._client.delete(m`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(m`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let J=await this.retrieve($);if(!J.results_url)throw new P(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);return this._client.get(J.results_url,{...Z,headers:S([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,Q)=>Y8.fromResponse(Q.response,Q.controller))}}class k4 extends p{constructor(){super(...arguments);this.batches=new j1(this._client)}create($,Z){if($.model in m2)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${m2[$.model]}
|
|
82
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in
|
|
80
|
+
Wrap your summary in <summary></summary> tags.`;var U1,G8,f4,e,W1,E$,s$,F4,B1,t2,i5;function e2(){let $,Z;return{promise:new Promise((Y,J)=>{$=Y,Z=J}),resolve:$,reject:Z}}class C1{constructor($,Z,Q){U1.add(this),this.client=$,G8.set(this,!1),f4.set(this,!1),e.set(this,void 0),W1.set(this,void 0),E$.set(this,void 0),s$.set(this,void 0),F4.set(this,void 0),B1.set(this,0),D(this,e,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let J=["BetaToolRunner",...u5(Z.tools,Z.messages)].join(", ");D(this,W1,{...Q,headers:k([{"x-stainless-helper":J},Q?.headers])},"f"),D(this,F4,e2(),"f")}async*[(G8=new WeakMap,f4=new WeakMap,e=new WeakMap,W1=new WeakMap,E$=new WeakMap,s$=new WeakMap,F4=new WeakMap,B1=new WeakMap,U1=new WeakSet,t2=async function(){let Z=M(this,e,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Q=0;if(M(this,E$,"f")!==void 0)try{let G=await M(this,E$,"f");Q=G.usage.input_tokens+(G.usage.cache_creation_input_tokens??0)+(G.usage.cache_read_input_tokens??0)+G.usage.output_tokens}catch{return!1}let Y=Z.contextTokenThreshold??i2;if(Q<Y)return!1;let J=Z.model??M(this,e,"f").params.model,X=Z.summaryPrompt??s2,K=M(this,e,"f").params.messages;if(K[K.length-1].role==="assistant"){let G=K[K.length-1];if(Array.isArray(G.content)){let H=G.content.filter((z)=>z.type!=="tool_use");if(H.length===0)K.pop();else G.content=H}}let V=await this.client.beta.messages.create({model:J,messages:[...K,{role:"user",content:[{type:"text",text:X}]}],max_tokens:M(this,e,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(V.content[0]?.type!=="text")throw new T("Expected text response for compaction");return M(this,e,"f").params.messages=[{role:"user",content:V.content}],!0},Symbol.asyncIterator)](){var $;if(M(this,G8,"f"))throw new T("Cannot iterate over a consumed stream");D(this,G8,!0,"f"),D(this,f4,!0,"f"),D(this,s$,void 0,"f");try{while(!0){let Z;try{if(M(this,e,"f").params.max_iterations&&M(this,B1,"f")>=M(this,e,"f").params.max_iterations)break;D(this,f4,!1,"f"),D(this,s$,void 0,"f"),D(this,B1,($=M(this,B1,"f"),$++,$),"f"),D(this,E$,void 0,"f");let{max_iterations:Q,compactionControl:Y,...J}=M(this,e,"f").params;if(J.stream)Z=this.client.beta.messages.stream({...J},M(this,W1,"f")),D(this,E$,Z.finalMessage(),"f"),M(this,E$,"f").catch(()=>{}),yield Z;else D(this,E$,this.client.beta.messages.create({...J,stream:!1},M(this,W1,"f")),"f"),yield M(this,E$,"f");if(!await M(this,U1,"m",t2).call(this)){if(!M(this,f4,"f")){let{role:V,content:G}=await M(this,E$,"f");M(this,e,"f").params.messages.push({role:V,content:G})}let K=await M(this,U1,"m",i5).call(this,M(this,e,"f").params.messages.at(-1));if(K)M(this,e,"f").params.messages.push(K);else if(!M(this,f4,"f"))break}}finally{if(Z)Z.abort()}}if(!M(this,E$,"f"))throw new T("ToolRunner concluded without a message from the server");M(this,F4,"f").resolve(await M(this,E$,"f"))}catch(Z){throw D(this,G8,!1,"f"),M(this,F4,"f").promise.catch(()=>{}),M(this,F4,"f").reject(Z),D(this,F4,e2(),"f"),Z}}setMessagesParams($){if(typeof $==="function")M(this,e,"f").params=$(M(this,e,"f").params);else M(this,e,"f").params=$;D(this,f4,!0,"f"),D(this,s$,void 0,"f")}async generateToolResponse(){let $=await M(this,E$,"f")??this.params.messages.at(-1);if(!$)return null;return M(this,U1,"m",i5).call(this,$)}done(){return M(this,F4,"f").promise}async runUntilDone(){if(!M(this,G8,"f"))for await(let $ of this);return this.done()}get params(){return M(this,e,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}i5=async function(Z){if(M(this,s$,"f")!==void 0)return M(this,s$,"f");return D(this,s$,oX(M(this,e,"f").params,Z),"f"),M(this,s$,"f")};async function oX($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Q=Z.content.filter((J)=>J.type==="tool_use");if(Q.length===0)return null;return{role:"user",content:await Promise.all(Q.map(async(J)=>{let X=$.tools.find((K)=>("name"in K?K.name:K.mcp_server_name)===J.name);if(!X||!("run"in X))return{type:"tool_result",tool_use_id:J.id,content:`Error: Tool '${J.name}' not found`,is_error:!0};try{let K=J.input;if("parse"in X&&X.parse)K=X.parse(K);let V=await X.run(K);return{type:"tool_result",tool_use_id:J.id,content:V}}catch(K){return{type:"tool_result",tool_use_id:J.id,content:K instanceof V8?K.content:`Error: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}))}}class H8{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new N4;for await(let Z of this.iterator)for(let Q of $.decode(Z))yield JSON.parse(Q);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 T("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 T("Attempted to iterate over a response with no body")}return new H8(r8($.body),Z)}}class N1 extends l{create($,Z){let{betas:Q,...Y}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/messages/batches/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Q?.headers])})}list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",y$,{query:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Q){let{betas:Y}=Z??{};return this._client.delete(d`/v1/messages/batches/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Q?.headers])})}cancel($,Z={},Q){let{betas:Y}=Z??{};return this._client.post(d`/v1/messages/batches/${$}/cancel?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Q?.headers])})}async results($,Z={},Q){let Y=await this.retrieve($);if(!Y.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);let{betas:J}=Z??{};return this._client.get(Y.results_url,{...Q,headers:k([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Q?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,K)=>H8.fromResponse(K.response,K.controller))}}var $6={"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"},nX=["claude-opus-4-6"];class O4 extends l{constructor(){super(...arguments);this.batches=new N1(this._client)}create($,Z){let Q=Z6($),{betas:Y,...J}=Q;if(J.model in $6)console.warn(`The model '${J.model}' is deprecated and will reach end-of-life on ${$6[J.model]}
|
|
81
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(J.model in nX&&J.thinking&&J.thinking.type==="enabled")console.warn(`Using Claude with ${J.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let X=this._client._options.timeout;if(!J.stream&&X==null){let V=S0[J.model]??void 0;X=this._client.calculateNonstreamingTimeout(J.max_tokens,V)}let K=x0(J.tools,J.messages);return this._client.post("/v1/messages?beta=true",{body:J,timeout:X??600000,...Z,headers:k([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},K,Z?.headers]),stream:Q.stream??!1})}parse($,Z){return Z={...Z,headers:k([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Q)=>l5(Q,$,{logger:this._client.logger??console}))}stream($,Z){return q1.createMessage(this,$,Z)}countTokens($,Z){let Q=Z6($),{betas:Y,...J}=Q;return this._client.post("/v1/messages/count_tokens?beta=true",{body:J,...Z,headers:k([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new C1(this._client,$,Z)}}function Z6($){if(!$.output_format)return $;if($.output_config?.format)throw new T("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...Q}=$;return{...Q,output_config:{...$.output_config,format:Z}}}O4.Batches=N1;O4.BetaToolRunner=C1;O4.ToolError=V8;class M1 extends l{create($,Z={},Q){let{betas:Y,...J}=Z??{};return this._client.post(d`/v1/skills/${$}/versions?beta=true`,X8({body:J,...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])},this._client))}retrieve($,Z,Q){let{skill_id:Y,betas:J}=Z;return this._client.get(d`/v1/skills/${Y}/versions/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Q?.headers])})}list($,Z={},Q){let{betas:Y,...J}=Z??{};return this._client.getAPIList(d`/v1/skills/${$}/versions?beta=true`,$1,{query:J,...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])})}delete($,Z,Q){let{skill_id:Y,betas:J}=Z;return this._client.delete(d`/v1/skills/${Y}/versions/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Q?.headers])})}}class q8 extends l{constructor(){super(...arguments);this.versions=new M1(this._client)}create($={},Z){let{betas:Q,...Y}=$??{};return this._client.post("/v1/skills?beta=true",X8({body:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/skills/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])})}list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",$1,{query:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Q){let{betas:Y}=Z??{};return this._client.delete(d`/v1/skills/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])})}}q8.Versions=M1;class v$ extends l{constructor(){super(...arguments);this.models=new J1(this._client),this.messages=new O4(this._client),this.files=new Y1(this._client),this.skills=new q8(this._client)}}v$.Models=J1;v$.Messages=O4;v$.Files=Y1;v$.Skills=q8;class U8 extends l{create($,Z){let{betas:Q,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...Z,headers:k([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function Q6($){return $?.output_config?.format}function s5($,Z,Q){let Y=Q6(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text")return Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return J}),parsed_output:null};return t5($,Z,Q)}function t5($,Z,Q){let Y=null,J=$.content.map((X)=>{if(X.type==="text"){let K=tX(Z,X.text);if(Y===null)Y=K;return Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1})}return X});return{...$,content:J,parsed_output:Y}}function tX($,Z){let Q=Q6($);if(Q?.type!=="json_schema")return null;try{if("parse"in Q)return Q.parse(Z);return JSON.parse(Z)}catch(Y){throw new T(`Failed to parse structured output: ${Y}`)}}var A$,R4,W8,F1,g0,O1,R1,m0,E1,t$,L1,p0,c0,h4,u0,d0,j1,e5,Y6,$9,Z9,Q9,Y9,J6,X6="__json_buf";function K6($){return $.type==="tool_use"||$.type==="server_tool_use"}class D1{constructor($,Z){A$.add(this),this.messages=[],this.receivedMessages=[],R4.set(this,void 0),W8.set(this,null),this.controller=new AbortController,F1.set(this,void 0),g0.set(this,()=>{}),O1.set(this,()=>{}),R1.set(this,void 0),m0.set(this,()=>{}),E1.set(this,()=>{}),t$.set(this,{}),L1.set(this,!1),p0.set(this,!1),c0.set(this,!1),h4.set(this,!1),u0.set(this,void 0),d0.set(this,void 0),j1.set(this,void 0),$9.set(this,(Q)=>{if(D(this,p0,!0,"f"),n$(Q))Q=new z$;if(Q instanceof z$)return D(this,c0,!0,"f"),this._emit("abort",Q);if(Q instanceof T)return this._emit("error",Q);if(Q instanceof Error){let Y=new T(Q.message);return Y.cause=Q,this._emit("error",Y)}return this._emit("error",new T(String(Q)))}),D(this,F1,new Promise((Q,Y)=>{D(this,g0,Q,"f"),D(this,O1,Y,"f")}),"f"),D(this,R1,new Promise((Q,Y)=>{D(this,m0,Q,"f"),D(this,E1,Y,"f")}),"f"),M(this,F1,"f").catch(()=>{}),M(this,R1,"f").catch(()=>{}),D(this,W8,$,"f"),D(this,j1,Z?.logger??console,"f")}get response(){return M(this,u0,"f")}get request_id(){return M(this,d0,"f")}async withResponse(){D(this,h4,!0,"f");let $=await M(this,F1,"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 D1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Q,{logger:Y}={}){let J=new D1(Z,{logger:Y});for(let X of Z.messages)J._addMessageParam(X);return D(J,W8,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},M(this,$9,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Q){let Y=Q?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{M(this,A$,"m",Z9).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...Q,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)M(this,A$,"m",Q9).call(this,V);if(K.controller.signal?.aborted)throw new z$;M(this,A$,"m",Y9).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}_connected($){if(this.ended)return;D(this,u0,$,"f"),D(this,d0,$?.headers.get("request-id"),"f"),M(this,g0,"f").call(this,$),this._emit("connect")}get ended(){return M(this,L1,"f")}get errored(){return M(this,p0,"f")}get aborted(){return M(this,c0,"f")}abort(){this.controller.abort()}on($,Z){return(M(this,t$,"f")[$]||(M(this,t$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Q=M(this,t$,"f")[$];if(!Q)return this;let Y=Q.findIndex((J)=>J.listener===Z);if(Y>=0)Q.splice(Y,1);return this}once($,Z){return(M(this,t$,"f")[$]||(M(this,t$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Q)=>{if(D(this,h4,!0,"f"),$!=="error")this.once("error",Q);this.once($,Z)})}async done(){D(this,h4,!0,"f"),await M(this,R1,"f")}get currentMessage(){return M(this,R4,"f")}async finalMessage(){return await this.done(),M(this,A$,"m",e5).call(this)}async finalText(){return await this.done(),M(this,A$,"m",Y6).call(this)}_emit($,...Z){if(M(this,L1,"f"))return;if($==="end")D(this,L1,!0,"f"),M(this,m0,"f").call(this);let Q=M(this,t$,"f")[$];if(Q)M(this,t$,"f")[$]=Q.filter((Y)=>!Y.once),Q.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!M(this,h4,"f")&&!Q?.length)Promise.reject(Y);M(this,O1,"f").call(this,Y),M(this,E1,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!M(this,h4,"f")&&!Q?.length)Promise.reject(Y);M(this,O1,"f").call(this,Y),M(this,E1,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",M(this,A$,"m",e5).call(this))}async _fromReadableStream($,Z){let Q=Z?.signal,Y;if(Q){if(Q.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Q.addEventListener("abort",Y)}try{M(this,A$,"m",Z9).call(this),this._connected(null);let J=R$.fromReadableStream($,this.controller);for await(let X of J)M(this,A$,"m",Q9).call(this,X);if(J.controller.signal?.aborted)throw new z$;M(this,A$,"m",Y9).call(this)}finally{if(Q&&Y)Q.removeEventListener("abort",Y)}}[(R4=new WeakMap,W8=new WeakMap,F1=new WeakMap,g0=new WeakMap,O1=new WeakMap,R1=new WeakMap,m0=new WeakMap,E1=new WeakMap,t$=new WeakMap,L1=new WeakMap,p0=new WeakMap,c0=new WeakMap,h4=new WeakMap,u0=new WeakMap,d0=new WeakMap,j1=new WeakMap,$9=new WeakMap,A$=new WeakSet,e5=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Y6=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Q)=>Q.type==="text").map((Q)=>Q.text);if(Z.length===0)throw new T("stream ended without producing a content block with type=text");return Z.join(" ")},Z9=function(){if(this.ended)return;D(this,R4,void 0,"f")},Q9=function(Z){if(this.ended)return;let Q=M(this,A$,"m",J6).call(this,Z);switch(this._emit("streamEvent",Z,Q),Z.type){case"content_block_delta":{let Y=Q.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(K6(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:z6(Z.delta)}break}case"message_stop":{this._addMessageParam(Q),this._addMessage(s5(Q,M(this,W8,"f"),{logger:M(this,j1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Q.content.at(-1));break}case"message_start":{D(this,R4,Q,"f");break}case"content_block_start":case"message_delta":break}},Y9=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let Z=M(this,R4,"f");if(!Z)throw new T("request ended without sending any chunks");return D(this,R4,void 0,"f"),s5(Z,M(this,W8,"f"),{logger:M(this,j1,"f")})},J6=function(Z){let Q=M(this,R4,"f");if(Z.type==="message_start"){if(Q)throw new T(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Q)throw new T(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Q;case"message_delta":if(Q.stop_reason=Z.delta.stop_reason,Q.stop_sequence=Z.delta.stop_sequence,Q.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)Q.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Q.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Q.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Q.usage.server_tool_use=Z.usage.server_tool_use;return Q;case"content_block_start":return Q.content.push({...Z.content_block}),Q;case"content_block_delta":{let Y=Q.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&K6(Y)){let J=Y[X6]||"";J+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,X6,{value:J,enumerable:!1,writable:!0}),J)X.input=w0(J);Q.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,signature:Z.delta.signature};break}default:z6(Z.delta)}return Q}case"content_block_stop":return Q}},Symbol.asyncIterator)](){let $=[],Z=[],Q=!1;return this.on("streamEvent",(Y)=>{let J=Z.shift();if(J)J.resolve(Y);else $.push(Y)}),this.on("end",()=>{Q=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),this.on("error",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(Q)return{value:void 0,done:!0};return new Promise((J,X)=>Z.push({resolve:J,reject:X})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new R$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function z6($){}class P1 extends l{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(d`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",y$,{query:$,...Z})}delete($,Z){return this._client.delete(d`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(d`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Q=await this.retrieve($);if(!Q.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);return this._client.get(Q.results_url,{...Z,headers:k([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,J)=>H8.fromResponse(J.response,J.controller))}}class g4 extends l{constructor(){super(...arguments);this.batches=new P1(this._client)}create($,Z){if($.model in V6)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${V6[$.model]}
|
|
82
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in $K&&$.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 Q=this._client._options.timeout;if(!$.stream&&Q==null){let J=S0[$.model]??void 0;Q=this._client.calculateNonstreamingTimeout($.max_tokens,J)}let Y=x0($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Q??600000,...Z,headers:k([Y,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Q)=>t5(Q,$,{logger:this._client.logger??console}))}stream($,Z){return D1.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var V6={"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"},$K=["claude-opus-4-6"];g4.Batches=P1;class B8 extends l{retrieve($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/models/${$}`,{...Q,headers:k([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Q?.headers])})}list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/models",y$,{query:Y,...Z,headers:k([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Z?.headers])})}}var T1=($)=>{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 J9,X9,l0,G6,H6="\\n\\nHuman:",q6="\\n\\nAssistant:";class o{constructor({baseURL:$=T1("ANTHROPIC_BASE_URL"),apiKey:Z=T1("ANTHROPIC_API_KEY")??null,authToken:Q=T1("ANTHROPIC_AUTH_TOKEN")??null,...Y}={}){J9.add(this),l0.set(this,void 0);let J={apiKey:Z,authToken:Q,...Y,baseURL:$||"https://api.anthropic.com"};if(!J.dangerouslyAllowBrowser&&T2())throw new T(`It looks like you're running in a browser-like environment.
|
|
83
83
|
|
|
84
84
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
85
85
|
If you understand the risks and have appropriate mitigations in place,
|
|
86
86
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
87
87
|
|
|
88
88
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
89
|
-
`);this.baseURL=Q.baseURL,this.timeout=Q.timeout??g5.DEFAULT_TIMEOUT,this.logger=Q.logger??console;let X="warn";this.logLevel=X,this.logLevel=M5(Q.logLevel,"ClientOptions.logLevel",this)??M5(O1("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??K2(),D(this,_0,V2,"f"),this._options=Q,this.apiKey=typeof Z==="string"?Z:null,this.authToken=J}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 S([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return S([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return S([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return G2($)}getUserAgent(){return`${this.constructor.name}/JS ${V4}`}defaultIdempotencyKey(){return`stainless-node-retry-${H5()}`}makeStatusError($,Z,J,Y){return i.generate($,Z,J,Y)}buildURL($,Z,J){let Y=!C(this,h5,"m",c2).call(this)&&J||this.baseURL,Q=sZ($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery(),K=Object.fromEntries(Q.searchParams);if(!U5(X)||!U5(K))Z={...K,...X,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))Q.search=this.stringifyQuery(Z);return Q.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new P("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:J}){}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,J){return this.request(Promise.resolve(J).then((Y)=>{return{method:$,path:Z,...Y}}))}request($,Z=null){return new A4(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,J){let Y=await $,Q=Y.maxRetries??this.maxRetries;if(Z==null)Z=Q;await this.prepareOptions(Y);let{req:X,url:K,timeout:V}=await this.buildRequest(Y,{retryCount:Q-Z});await this.prepareRequest(X,{url:K,options:Y});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=J===void 0?"":`, retryOf: ${J}`,z=Date.now();if(t(this).debug(`[${G}] sending request`,c$({retryOfRequestLogID:J,method:Y.method,url:K,options:Y,headers:X.headers})),Y.signal?.aborted)throw new Q$;let U=new AbortController,B=await this.fetchWithTimeout(K,X,V,U).catch(k8),M=Date.now();if(B instanceof globalThis.Error){let T=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new Q$;let _=m$(B)||/timed? ?out/i.test(String(B)+("cause"in B?String(B.cause):""));if(Z)return t(this).info(`[${G}] connection ${_?"timed out":"failed"} - ${T}`),t(this).debug(`[${G}] connection ${_?"timed out":"failed"} (${T})`,c$({retryOfRequestLogID:J,url:K,durationMs:M-z,message:B.message})),this.retryRequest(Y,Z,J??G);if(t(this).info(`[${G}] connection ${_?"timed out":"failed"} - error; no more retries left`),t(this).debug(`[${G}] connection ${_?"timed out":"failed"} (error; no more retries left)`,c$({retryOfRequestLogID:J,url:K,durationMs:M-z,message:B.message})),_)throw new b8;throw new P4({cause:B})}let O=[...B.headers.entries()].filter(([T])=>T==="request-id").map(([T,_])=>", "+T+": "+JSON.stringify(_)).join(""),L=`[${G}${H}${O}] ${X.method} ${K} ${B.ok?"succeeded":"failed"} with status ${B.status} in ${M-z}ms`;if(!B.ok){let T=await this.shouldRetry(B);if(Z&&T){let d=`retrying, ${Z} attempts remaining`;return await z2(B.body),t(this).info(`${L} - ${d}`),t(this).debug(`[${G}] response error (${d})`,c$({retryOfRequestLogID:J,url:B.url,status:B.status,headers:B.headers,durationMs:M-z})),this.retryRequest(Y,Z,J??G,B.headers)}let _=T?"error; no more retries left":"error; not retryable";t(this).info(`${L} - ${_}`);let V$=await B.text().catch((d)=>k8(d).message),s=H0(V$),y=s?void 0:V$;throw t(this).debug(`[${G}] response error (${_})`,c$({retryOfRequestLogID:J,url:B.url,status:B.status,headers:B.headers,message:y,durationMs:Date.now()-z})),this.makeStatusError(B.status,s,y,B.headers)}return t(this).info(L),t(this).debug(`[${G}] response start`,c$({retryOfRequestLogID:J,url:B.url,status:B.status,headers:B.headers,durationMs:M-z})),{response:B,options:Y,controller:U,requestLogID:G,retryOfRequestLogID:J,startTime:z}}getAPIList($,Z,J){return this.requestAPIList(Z,J&&"then"in J?J.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...J})}requestAPIList($,Z){let J=this.makeRequest(Z,null,void 0);return new M0(this,J,$)}async fetchWithTimeout($,Z,J,Y){let{signal:Q,method:X,...K}=Z||{},V=this._makeAbort(Y);if(Q)Q.addEventListener("abort",V,{once:!0});let G=setTimeout(V,J),H=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,z={signal:Y.signal,...H?{duplex:"half"}:{},method:"GET",...K};if(X)z.method=X.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(G)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,J,Y){let Q,X=Y?.get("retry-after-ms");if(X){let V=parseFloat(X);if(!Number.isNaN(V))Q=V}let K=Y?.get("retry-after");if(K&&!Q){let V=parseFloat(K);if(!Number.isNaN(V))Q=V*1000;else Q=Date.parse(K)-Date.now()}if(Q===void 0){let V=$.maxRetries??this.maxRetries;Q=this.calculateDefaultRetryTimeoutMillis(Z,V)}return await $2(Q),this.makeRequest($,Z-1,J)}calculateDefaultRetryTimeoutMillis($,Z){let Q=Z-$,X=Math.min(0.5*Math.pow(2,Q),8),K=1-Math.random()*0.25;return X*K*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new P("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let J={...$},{method:Y,path:Q,query:X,defaultBaseURL:K}=J,V=this.buildURL(Q,X,K);if("timeout"in J)eZ("timeout",J.timeout);J.timeout=J.timeout??this.timeout;let{bodyHeaders:G,body:H}=this.buildBody({options:J}),z=await this.buildHeaders({options:$,method:Y,bodyHeaders:G,retryCount:Z});return{req:{method:Y,headers:z,...J.signal&&{signal:J.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...J.fetchOptions??{}},url:V,timeout:J.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:J,retryCount:Y}){let Q={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Q[this.idempotencyHeader]=$.idempotencyKey}let X=S([Q,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...X2(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,J,$.headers]);return this.validateHeaders(X),X.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let J=S([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&J.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:q0($)};else if(typeof $==="object"&&J.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return C(this,_0,"f").call(this,{body:$,headers:J})}}g5=u,_0=new WeakMap,h5=new WeakSet,c2=function(){return this.baseURL!=="https://api.anthropic.com"};u.Anthropic=g5;u.HUMAN_PROMPT=p2;u.AI_PROMPT=u2;u.DEFAULT_TIMEOUT=600000;u.AnthropicError=P;u.APIError=i;u.APIConnectionError=P4;u.APIConnectionTimeoutError=b8;u.APIUserAbortError=Q$;u.NotFoundError=f8;u.ConflictError=h8;u.RateLimitError=m8;u.BadRequestError=y8;u.AuthenticationError=_8;u.InternalServerError=c8;u.PermissionDeniedError=v8;u.UnprocessableEntityError=g8;u.toFile=C0;class k$ extends u{constructor(){super(...arguments);this.completions=new X8(this),this.messages=new k4(this),this.models=new z8(this),this.beta=new w$(this)}}k$.Completions=X8;k$.Messages=k4;k$.Models=z8;k$.Beta=w$;r();$$();import{existsSync as _1,readdirSync as iV,readFileSync as m9,writeFileSync as nV,statSync as P3,realpathSync as sV}from"fs";import{resolve as x$,join as A3,sep as O8}from"path";import{existsSync as EX,readFileSync as LX,writeFileSync as DX}from"fs";import{basename as m5}from"path";var d2=50;class c5{entries=[];saveState($){let Z=EX($),J=Z?LX($,"utf-8"):"";if(this.entries.push({path:$,content:J,timestamp:Date.now(),existed:Z}),this.entries.length>d2)this.entries=this.entries.slice(-d2)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${m5($.path)} was a new file. Remove it manually if needed.`;DX($.path,$.content);let Z=$.content.split(`
|
|
90
|
-
`).length;return`Undo: restored ${
|
|
89
|
+
`);this.baseURL=J.baseURL,this.timeout=J.timeout??X9.DEFAULT_TIMEOUT,this.logger=J.logger??console;let X="warn";this.logLevel=X,this.logLevel=v5(J.logLevel,"ClientOptions.logLevel",this)??v5(T1("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??I2(),D(this,l0,S2,"f"),this._options=J,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Q}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 k([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return k([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return k([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return w2($)}getUserAgent(){return`${this.constructor.name}/JS ${C4}`}defaultIdempotencyKey(){return`stainless-node-retry-${S5()}`}makeStatusError($,Z,Q,Y){return t.generate($,Z,Q,Y)}buildURL($,Z,Q){let Y=!M(this,J9,"m",G6).call(this)&&Q||this.baseURL,J=O2($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery(),K=Object.fromEntries(J.searchParams);if(!y5(X)||!y5(K))Z={...K,...X,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))J.search=this.stringifyQuery(Z);return J.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new T("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:Q}){}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,Q){return this.request(Promise.resolve(Q).then((Y)=>{return{method:$,path:Z,...Y}}))}request($,Z=null){return new b4(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Q){let Y=await $,J=Y.maxRetries??this.maxRetries;if(Z==null)Z=J;await this.prepareOptions(Y);let{req:X,url:K,timeout:V}=await this.buildRequest(Y,{retryCount:J-Z});await this.prepareRequest(X,{url:K,options:Y});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Q===void 0?"":`, retryOf: ${Q}`,z=Date.now();if(Q$(this).debug(`[${G}] sending request`,r$({retryOfRequestLogID:Q,method:Y.method,url:K,options:Y,headers:X.headers})),Y.signal?.aborted)throw new z$;let B=new AbortController,W=await this.fetchWithTimeout(K,X,V,B).catch(g8),N=Date.now();if(W instanceof globalThis.Error){let P=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new z$;let _=n$(W)||/timed? ?out/i.test(String(W)+("cause"in W?String(W.cause):""));if(Z)return Q$(this).info(`[${G}] connection ${_?"timed out":"failed"} - ${P}`),Q$(this).debug(`[${G}] connection ${_?"timed out":"failed"} (${P})`,r$({retryOfRequestLogID:Q,url:K,durationMs:N-z,message:W.message})),this.retryRequest(Y,Z,Q??G);if(Q$(this).info(`[${G}] connection ${_?"timed out":"failed"} - error; no more retries left`),Q$(this).debug(`[${G}] connection ${_?"timed out":"failed"} (error; no more retries left)`,r$({retryOfRequestLogID:Q,url:K,durationMs:N-z,message:W.message})),_)throw new m8;throw new y4({cause:W})}let O=[...W.headers.entries()].filter(([P])=>P==="request-id").map(([P,_])=>", "+P+": "+JSON.stringify(_)).join(""),j=`[${G}${H}${O}] ${X.method} ${K} ${W.ok?"succeeded":"failed"} with status ${W.status} in ${N-z}ms`;if(!W.ok){let P=await this.shouldRetry(W);if(Z&&P){let a=`retrying, ${Z} attempts remaining`;return await x2(W.body),Q$(this).info(`${j} - ${a}`),Q$(this).debug(`[${G}] response error (${a})`,r$({retryOfRequestLogID:Q,url:W.url,status:W.status,headers:W.headers,durationMs:N-z})),this.retryRequest(Y,Z,Q??G,W.headers)}let _=P?"error; no more retries left":"error; not retryable";Q$(this).info(`${j} - ${_}`);let q$=await W.text().catch((a)=>g8(a).message),$$=R0(q$),y=$$?void 0:q$;throw Q$(this).debug(`[${G}] response error (${_})`,r$({retryOfRequestLogID:Q,url:W.url,status:W.status,headers:W.headers,message:y,durationMs:Date.now()-z})),this.makeStatusError(W.status,$$,y,W.headers)}return Q$(this).info(j),Q$(this).debug(`[${G}] response start`,r$({retryOfRequestLogID:Q,url:W.url,status:W.status,headers:W.headers,durationMs:N-z})),{response:W,options:Y,controller:B,requestLogID:G,retryOfRequestLogID:Q,startTime:z}}getAPIList($,Z,Q){return this.requestAPIList(Z,Q&&"then"in Q?Q.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...Q})}requestAPIList($,Z){let Q=this.makeRequest(Z,null,void 0);return new T0(this,Q,$)}async fetchWithTimeout($,Z,Q,Y){let{signal:J,method:X,...K}=Z||{},V=this._makeAbort(Y);if(J)J.addEventListener("abort",V,{once:!0});let G=setTimeout(V,Q),H=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,z={signal:Y.signal,...H?{duplex:"half"}:{},method:"GET",...K};if(X)z.method=X.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(G)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Q,Y){let J,X=Y?.get("retry-after-ms");if(X){let V=parseFloat(X);if(!Number.isNaN(V))J=V}let K=Y?.get("retry-after");if(K&&!J){let V=parseFloat(K);if(!Number.isNaN(V))J=V*1000;else J=Date.parse(K)-Date.now()}if(J===void 0){let V=$.maxRetries??this.maxRetries;J=this.calculateDefaultRetryTimeoutMillis(Z,V)}return await L2(J),this.makeRequest($,Z-1,Q)}calculateDefaultRetryTimeoutMillis($,Z){let J=Z-$,X=Math.min(0.5*Math.pow(2,J),8),K=1-Math.random()*0.25;return X*K*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new T("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 Q={...$},{method:Y,path:J,query:X,defaultBaseURL:K}=Q,V=this.buildURL(J,X,K);if("timeout"in Q)E2("timeout",Q.timeout);Q.timeout=Q.timeout??this.timeout;let{bodyHeaders:G,body:H}=this.buildBody({options:Q}),z=await this.buildHeaders({options:$,method:Y,bodyHeaders:G,retryCount:Z});return{req:{method:Y,headers:z,...Q.signal&&{signal:Q.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Q.fetchOptions??{}},url:V,timeout:Q.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Q,retryCount:Y}){let J={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let X=k([J,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...A2(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Q,$.headers]);return this.validateHeaders(X),X.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Q=k([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Q.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:E0($)};else if(typeof $==="object"&&Q.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return M(this,l0,"f").call(this,{body:$,headers:Q})}}X9=o,l0=new WeakMap,J9=new WeakSet,G6=function(){return this.baseURL!=="https://api.anthropic.com"};o.Anthropic=X9;o.HUMAN_PROMPT=H6;o.AI_PROMPT=q6;o.DEFAULT_TIMEOUT=600000;o.AnthropicError=T;o.APIError=t;o.APIConnectionError=y4;o.APIConnectionTimeoutError=m8;o.APIUserAbortError=z$;o.NotFoundError=d8;o.ConflictError=l8;o.RateLimitError=a8;o.BadRequestError=p8;o.AuthenticationError=c8;o.InternalServerError=n8;o.PermissionDeniedError=u8;o.UnprocessableEntityError=o8;o.toFile=A0;class f$ extends o{constructor(){super(...arguments);this.completions=new U8(this),this.messages=new g4(this),this.models=new B8(this),this.beta=new v$(this)}}f$.Completions=U8;f$.Messages=g4;f$.Models=B8;f$.Beta=v$;n();Z$();import{existsSync as a1,readdirSync as oG,readFileSync as GZ,writeFileSync as aG,statSync as zY,realpathSync as nG}from"fs";import{resolve as b$,join as VY,sep as A8}from"path";import{existsSync as QK,readFileSync as YK,writeFileSync as JK}from"fs";import{basename as K9}from"path";var U6=50;class z9{entries=[];saveState($){let Z=QK($),Q=Z?YK($,"utf-8"):"";if(this.entries.push({path:$,content:Q,timestamp:Date.now(),existed:Z}),this.entries.length>U6)this.entries=this.entries.slice(-U6)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${K9($.path)} was a new file. Remove it manually if needed.`;JK($.path,$.content);let Z=$.content.split(`
|
|
90
|
+
`).length;return`Undo: restored ${K9($.path)} (${Z} lines, from ${W6($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${K9($.path)} (${W6($.timestamp)})`}}function W6($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let Q=Math.floor(Z/60);if(Q<60)return`${Q}m ago`;return`${Math.floor(Q/60)}h ago`}Z$();import{existsSync as B6,readdirSync as XK,readFileSync as KK,mkdirSync as zK}from"fs";import{join as V9}from"path";function C6($){if(!B6($))return[];let Z=[],Q=XK($).filter((Y)=>Y.endsWith(".json"));for(let Y of Q)try{let J=JSON.parse(KK(V9($,Y),"utf-8"));if(!J.name||!J.description||!J.command)continue;if(typeof J.name!=="string"||typeof J.command!=="string")continue;if(J.command.includes("$(")||J.command.includes("`"))continue;Z.push({name:J.name,description:J.description,inputSchema:J.input_schema||{type:"object",properties:{},required:[]},command:J.command,source:V9($,Y)})}catch{}return Z}function N6($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function M6($,Z){let Q=$.command;for(let[z,B]of Object.entries(Z)){let W=String(B).replace(/[;&|`$()]/g,"");Q=Q.replace(new RegExp(`\\{\\{input\\.${z}\\}\\}`,"g"),W)}Q=Q.replace(/\{\{input\.\w+\}\}/g,"");let Y=Q8(),J=Bun.spawn([...Y,Q],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>J.kill(),30000),[K,V]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),G=await J.exited;clearTimeout(X);let H=K.trim();if(V.trim())H+=(H?`
|
|
91
91
|
`:"")+V.trim();if(G!==0)H+=(H?`
|
|
92
|
-
`:"")+`Exit code: ${G}`;return H||"(no output)"}function
|
|
92
|
+
`:"")+`Exit code: ${G}`;return H||"(no output)"}function F6($){if($.length===0)return"No plugins loaded. Add .json files to ~/.config/smolerclaw/plugins/";return`Plugins:
|
|
93
93
|
`+$.map((Z)=>` ${Z.name} \u2014 ${Z.description}`).join(`
|
|
94
|
-
`)}function
|
|
95
|
-
--- Built-in ---`);for(let Z of
|
|
96
|
-
--- Custom ---`);for(let Z of
|
|
97
|
-
Total: ${
|
|
98
|
-
`)}var
|
|
99
|
-
Falhas: ${Y.join(", ")}`:"Nenhuma noticia encontrada.";return
|
|
94
|
+
`)}function O6($){let Z=V9($,"plugins");if(!B6(Z))zK(Z,{recursive:!0});return Z}d4();n();import{existsSync as GK,readFileSync as HK}from"fs";import{join as qK}from"path";var C8=[{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}],o0="",B$=[],L$=new Set,D6=()=>qK(o0,"news-feeds.json");function a0(){if(!o0)return;let $={custom:B$,disabled:[...L$]};S(D6(),JSON.stringify($,null,2))}function UK(){if(!o0)return;let $=D6();if(!GK($)){B$=[],L$=new Set;return}try{let Z=JSON.parse(HK($,"utf-8"));B$=Z.custom||[],L$=new Set(Z.disabled||[])}catch{B$=[],L$=new Set}}function P6($){o0=$,UK()}function W9(){return[...C8.filter((Z)=>!L$.has(Z.url)),...B$]}function n0($,Z,Q){let Y=$.trim();if(!Y||Y.length>100)return"Error: nome invalido (1-100 caracteres).";let J=Q.trim().toLowerCase();if(!J||J.length>30)return"Error: categoria invalida (1-30 caracteres).";let X=Z.trim();if(!X.startsWith("http://")&&!X.startsWith("https://"))return"Error: URL deve comecar com http:// ou https://";if(X.length>500)return"Error: URL muito longa (max 500 caracteres).";if([...C8,...B$].some((G)=>G.url===X))return"Error: essa URL ja esta cadastrada.";let V={name:Y,url:X,category:J};return B$=[...B$,V],a0(),V}function r0($){let Z=$.toLowerCase().trim(),Q=B$.findIndex((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(Q===-1)return!1;return B$=[...B$.slice(0,Q),...B$.slice(Q+1)],a0(),!0}function i0($){let Z=$.toLowerCase().trim(),Q=C8.find((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(!Q)return!1;if(L$.has(Q.url))return!1;return L$=new Set([...L$,Q.url]),a0(),!0}function s0($){let Z=$.toLowerCase().trim(),Q=C8.find((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(!Q)return!1;if(!L$.has(Q.url))return!1;return L$=new Set([...L$].filter((Y)=>Y!==Q.url)),a0(),!0}function t0(){let $=["Fontes de noticias:"];$.push(`
|
|
95
|
+
--- Built-in ---`);for(let Z of C8){let Q=L$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Q} \u2014 ${Z.url}`)}if(B$.length>0){$.push(`
|
|
96
|
+
--- Custom ---`);for(let Z of B$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
|
|
97
|
+
Total: ${W9().length} ativas (${C8.length} built-in, ${B$.length} custom, ${L$.size} desativadas)`),$.join(`
|
|
98
|
+
`)}var E6=2097152,U9=10,WK=1e4;function BK($,Z,Q){let Y=[],J=/<item[\s>]([\s\S]*?)<\/item>/gi,X;while((X=J.exec($))!==null){let K=X[1],V=L6(K,Z,Q);if(V)Y.push(V);if(Y.length>=U9)break}if(Y.length===0){let K=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((X=K.exec($))!==null){let V=X[1],G=L6(V,Z,Q);if(G)Y.push(G);if(Y.length>=U9)break}}return Y}function L6($,Z,Q){let Y=x1($,"title");if(!Y)return null;let J=x1($,"link")||OK($),X=CK(J),K=x1($,"pubDate")||x1($,"published")||x1($,"updated"),V;if(K){let G=new Date(K);V=isNaN(G.getTime())?void 0:G}return{title:w1(Y),link:X,source:Z,category:Q,pubDate:V}}function CK($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function NK($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x1($,Z){let Q=NK(Z),J=new RegExp(`<${Q}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Q}>`,"i").exec($);if(J)return J[1].trim();let K=new RegExp(`<${Q}[^>]*>([\\s\\S]*?)</${Q}>`,"i").exec($);return K?K[1].trim():null}function MK($,Z){let Q=FK($,Z);try{return new TextDecoder(Q).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function FK($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return S1(J[1])}let Y=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Y)return S1(Y[1]);return"utf-8"}function S1($){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 OK($){let Q=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Q?Q[1]:null}var RK={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 w1($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Q)=>RK[Q]??Z).replace(/&#(\d+);/g,(Z,Q)=>String.fromCharCode(Number(Q))).replace(/&#x([0-9a-fA-F]+);/g,(Z,Q)=>String.fromCharCode(parseInt(Q,16))).trim()}async function B9($,Z=5){let Q=Math.max(1,Math.min(Z,U9));if($&&$.length===0)return{items:[],errors:[]};let Y=W9(),J=$?Y.filter((G)=>$.includes(G.category)):Y,X=await Promise.allSettled(J.map((G)=>LK(G,Q))),K=[],V=[];for(let G=0;G<X.length;G++){let H=X[G];if(H.status==="fulfilled")K.push(...H.value);else V.push(`${J[G].name}: ${EK(H.reason)}`)}return K.sort((G,H)=>{let z=G.pubDate?.getTime()||0;return(H.pubDate?.getTime()||0)-z}),{items:K,errors:V}}async function E4($,Z=5){if($&&$.length===0)return DK();let{items:Q,errors:Y}=await B9($,Z);if(Q.length===0)return Y.length>0?`Nenhuma noticia encontrada.
|
|
99
|
+
Falhas: ${Y.join(", ")}`:"Nenhuma noticia encontrada.";return jK(Q,Y)}function EK($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function LK($,Z){let Q=new AbortController,Y=setTimeout(()=>Q.abort(),WK);try{let J=await fetch($.url,{signal:Q.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Y),!J.ok)return[];let X=J.headers.get("content-length");if(X&&Number(X)>E6)return[];let K=J.body?.getReader();if(!K)return[];let V=[],G=0;while(!0){let{done:W,value:N}=await K.read();if(W)break;if(G+=N.byteLength,G>E6)return K.cancel(),[];V.push(N)}let H=Buffer.concat(V),z=MK(H,J.headers.get("content-type"));return BK(z,$.name,$.category).slice(0,Z)}catch(J){throw clearTimeout(Y),J}}function jK($,Z){let Q={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Y=new Map;for(let V of $){let G=Y.get(V.category)||[];Y.set(V.category,[...G,V])}let J=[],X=["finance","business","tech","security","brazil","world"];for(let V of X){let G=Y.get(V);if(!G||G.length===0)continue;let H=Q[V],z=G.slice(0,8).map((B)=>{let W=B.pubDate?B.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${W?`[${W}]`:""} ${B.title} (${B.source})`});J.push(`--- ${H} ---
|
|
100
100
|
${z.join(`
|
|
101
|
-
`)}`)}let K=
|
|
101
|
+
`)}`)}let K=J.join(`
|
|
102
102
|
|
|
103
103
|
`);if(Z.length>0)K+=`
|
|
104
104
|
|
|
105
|
-
(Fontes indisponiveis: ${Z.join(", ")})`;return K}function
|
|
106
|
-
Uso: /news [categoria]`}
|
|
105
|
+
(Fontes indisponiveis: ${Z.join(", ")})`;return K}function DK(){let $=W9();return`Categorias: ${[...new Set($.map((Q)=>Q.category))].sort().join(", ")}
|
|
106
|
+
Uso: /news [categoria]`}var PK=15000,j6=5242880;async function T6($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Q=setTimeout(()=>Z.abort(),PK);try{let Y=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(Q),!Y.ok)return`Error: HTTP ${Y.status}`;let J=Y.headers.get("content-length");if(J&&Number(J)>j6)return"Error: pagina muito grande";let X=Y.body?.getReader();if(!X)return"Error: sem corpo de resposta";let K=[],V=0;while(!0){let{done:W,value:N}=await X.read();if(W)break;if(V+=N.byteLength,V>j6)return X.cancel(),"Error: pagina muito grande";K.push(N)}let G=Buffer.concat(K),H=Y.headers.get("content-type"),z=TK(G,H);return IK(z)}catch(Y){if(clearTimeout(Q),Y instanceof Error){if(Y.name==="AbortError")return"Error: timeout ao buscar pagina";return`Error: ${Y.message.slice(0,100)}`}return"Error: falha ao buscar pagina"}}function TK($,Z){let Q=AK($,Z);try{return new TextDecoder(Q).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function AK($,Z){if(Z){let X=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(X)return S1(X[1])}let Q=$.subarray(0,2048).toString("ascii"),Y=Q.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Y)return S1(Y[1]);let J=Q.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(J)return S1(J[1]);return"utf-8"}function IK($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Q=Z?w1(Z[1]):"Sem titulo",Y="",J=$.match(/<article[^>]*>([\s\S]*?)<\/article>/i);if(J)Y=J[1];if(!Y){let K=[/<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 V of K){let G=$.match(V);if(G){Y=G[1];break}}}if(!Y){let K=[],V=/<p[^>]*>([\s\S]*?)<\/p>/gi,G;while((G=V.exec($))!==null){let H=w1(G[1]).trim();if(H.length>50)K.push(H)}Y=K.join(`
|
|
107
|
+
|
|
108
|
+
`)}else Y=xK(Y);let X=Y.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Q,content:X}}function xK($){let Z=[],Q=/<p[^>]*>([\s\S]*?)<\/p>/gi,Y;while((Y=Q.exec($))!==null){let J=w1(Y[1]).trim();if(J.length>20)Z.push(J)}if(Z.length===0){let J=w1($).trim();if(J.length>50)return J}return Z.join(`
|
|
109
|
+
|
|
110
|
+
`)}Z$();n();d$();import{existsSync as A6,mkdirSync as SK,readFileSync as wK}from"fs";import{join as kK}from"path";import{randomUUID as yK}from"crypto";var I6="",r=[],N8=null,x6=null,S6=()=>kK(I6,"tasks.json");function e0(){S(S6(),JSON.stringify(r,null,2))}function bK(){let $=S6();if(!A6($)){r=[];return}try{r=JSON.parse(wK($,"utf-8"))}catch{r=[]}}function w6($,Z){if(I6=$,x6=Z,!A6($))SK($,{recursive:!0});if(bK(),N8)clearInterval(N8);N8=setInterval(_K,30000),hK().catch(()=>{})}function k6(){if(N8)clearInterval(N8),N8=null}function $7($,Z){let Q={id:gK(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(r=[...r,Q],e0(),Z&&A)C9(Q).catch(()=>{});return Q}function Z7($){let Z=$.toLowerCase(),Q=r.find((Y)=>Y.id===$||Y.title.toLowerCase().includes(Z));if(!Q||Q.done)return null;if(r=r.map((Y)=>Y.id===Q.id?{...Y,done:!0}:Y),e0(),Q.dueAt&&A)b6(Q.id).catch(()=>{});return r.find((Y)=>Y.id===Q.id)||null}function y6($){let Z=$.toLowerCase(),Q=r.findIndex((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(Q===-1)return!1;let Y=r[Q];if(r=[...r.slice(0,Q),...r.slice(Q+1)],e0(),Y.dueAt&&A)b6(Y.id).catch(()=>{});return!0}function e$($=!1){return $?[...r]:r.filter((Z)=>!Z.done)}function l4($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Q)=>{let Y=Q.done?"[x]":"[ ]",J=Q.dueAt?` (${mK(Q.dueAt)})`:"";return` ${Y} ${Q.title}${J} [${Q.id}]`});return`Tarefas (${$.length}):
|
|
111
|
+
${Z.join(`
|
|
112
|
+
`)}`}function k1($){let Z=new Date,Q=$.toLowerCase().trim(),Y=Q.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Y){let K=parseInt(Y[1]),V=Y[2].startsWith("h")?"hours":"minutes",G=new Date(Z);if(V==="hours")G.setHours(G.getHours()+K);else G.setMinutes(G.getMinutes()+K);return G}let J=new Date(Z);if(Q.includes("amanha")||Q.includes("amanh\xE3"))J.setDate(J.getDate()+1);let X=Q.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(X){let K=parseInt(X[1]),V=parseInt(X[2]||"0");if(K>=0&&K<=23&&V>=0&&V<=59){if(J.setHours(K,V,0,0),J<=Z&&!Q.includes("amanha")&&!Q.includes("amanh\xE3"))J.setDate(J.getDate()+1);return J}}return null}function _K(){let $=new Date,Z=!1;for(let Q of r){if(Q.done||Q.notified||!Q.dueAt)continue;let Y=new Date(Q.dueAt);if(isNaN(Y.getTime()))continue;let J=$.getTime()-Y.getTime();if(J>=0&&J<300000)r=r.map((X)=>X.id===Q.id?{...X,notified:!0}:X),Z=!0,fK(Q),x6?.(Q)}if(Z)e0()}function vK($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function fK($){if(!A)return;try{await H4("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var N9="smolerclaw-reminder-";async function C9($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Q=`${N9}${$.id}`,Y=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),J=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),K=["[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"">${$2(vK($.title))}</text></binding></visual><audio src=""ms-winsoundevent:Notification.Reminder""/></toast>');`,"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show([Windows.UI.Notifications.ToastNotification]::new($x))"].join(" ");try{await u$("Create",Q,["/SC","ONCE","/SD",Y,"/ST",J,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${K}"`,"/F"])}catch{}}async function b6($){let Z=`${N9}${$}`;try{await u$("Delete",Z,["/F"])}catch{}}async function hK(){if(!A)return;let $=Date.now();for(let Z of r){if(Z.done||Z.notified||!Z.dueAt)continue;let Q=new Date(Z.dueAt);if(isNaN(Q.getTime())||Q.getTime()<=$)continue;try{if((await u$("Query",`${N9}${Z.id}`)).exitCode!==0)await C9(Z)}catch{await C9(Z)}}}function gK(){return yK().slice(0,8)}function mK($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Q=new Date,Y=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()),J=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),X=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(J.getTime()===Y.getTime())return`hoje ${X}`;let K=new Date(Y);if(K.setDate(K.getDate()+1),J.getTime()===K.getTime())return`amanha ${X}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${X}`}n();import{existsSync as _6,mkdirSync as pK,readFileSync as cK}from"fs";import{join as uK}from"path";import{randomUUID as dK}from"crypto";var v6="",C$=[],f6=()=>uK(v6,"memos.json");function h6(){S(f6(),JSON.stringify(C$,null,2))}function lK(){let $=f6();if(!_6($)){C$=[];return}try{C$=JSON.parse(cK($,"utf-8"))}catch{C$=[]}}function g6($){if(v6=$,!_6($))pK($,{recursive:!0});lK()}function Q7($,Z=[]){let Q=new Date().toISOString(),Y=$.match(/#(\w+)/g)?.map((K)=>K.slice(1).toLowerCase())||[],J=[...new Set([...Z.map((K)=>K.toLowerCase()),...Y])],X={id:aK(),content:$.trim(),tags:J,createdAt:Q,updatedAt:Q};return C$=[...C$,X],h6(),X}function m6($){let Z=C$.findIndex((Q)=>Q.id===$);if(Z===-1)return!1;return C$=[...C$.slice(0,Z),...C$.slice(Z+1)],h6(),!0}function Y7($){let Z=$.toLowerCase().trim();if(!Z)return[...C$];let Q=Z.startsWith("#"),Y=Q?Z.slice(1):Z;return C$.filter((J)=>{if(Q)return J.tags.some((X)=>X.includes(Y));return J.content.toLowerCase().includes(Y)||J.tags.some((X)=>X.includes(Y))}).sort((J,X)=>new Date(X.updatedAt).getTime()-new Date(J.updatedAt).getTime())}function y1($=20){return[...C$].reverse().sort((Z,Q)=>new Date(Q.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function oK(){let $=new Map;for(let Z of C$)for(let Q of Z.tags)$.set(Q,($.get(Q)||0)+1);return[...$.entries()].map(([Z,Q])=>({tag:Z,count:Q})).sort((Z,Q)=>Q.count-Z.count)}function o4($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Q)=>{let Y=new Date(Q.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Q.tags.length>0?` [${Q.tags.map((K)=>`#${K}`).join(" ")}]`:"",X=Q.content.length>80?Q.content.slice(0,80).replace(/\n/g," ")+"...":Q.content.replace(/\n/g," ");return` [${Y}] ${X}${J} {${Q.id}}`});return`Memos (${$.length}):
|
|
107
113
|
${Z.join(`
|
|
108
|
-
`)}`}function
|
|
114
|
+
`)}`}function p6(){let $=oK();if($.length===0)return"Nenhuma tag.";return`Tags:
|
|
115
|
+
${$.map((Q)=>` #${Q.tag} (${Q.count})`).join(`
|
|
116
|
+
`)}`}function aK(){return dK().slice(0,8)}Z$();async function J7($){if(A)return nK($);return M9($)}async function nK($){let Z=$.to.replace(/'/g,"''"),Q=$.subject.replace(/'/g,"''"),Y=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),J=$.cc?.replace(/'/g,"''")||"",X=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${Q}'`,` $mail.Body = '${Y}'`,J?` $mail.CC = '${J}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
|
|
117
|
+
`);try{let K=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>K.kill(),15000),[G]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]);await K.exited,clearTimeout(V);let H=G.trim();if(H.includes("mailto"))return M9($);return H||"Email aberto no Outlook."}catch{return M9($)}}async function M9($){let Z=[];if($.subject)Z.push(`subject=${encodeURIComponent($.subject)}`);if($.body)Z.push(`body=${encodeURIComponent($.body)}`);if($.cc)Z.push(`cc=${encodeURIComponent($.cc)}`);let Q=`mailto:${encodeURIComponent($.to)}${Z.length?"?"+Z.join("&"):""}`;try{let Y=A?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Q}'`]:["xdg-open",Q],J=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>J.kill(),1e4);return await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),await J.exited,clearTimeout(X),"Email aberto no cliente de email padrao."}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}function X7($){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(`
|
|
118
|
+
`)}Z$();n();d$();import{existsSync as z7,mkdirSync as l6,readFileSync as rK,writeFileSync as iK,unlinkSync as sK}from"fs";import{join as V7}from"path";import{randomUUID as tK}from"crypto";var F9="",c=[],eK=null,o6=()=>V7(F9,"scheduler.json"),$z="Smolerclaw_";function a6($,Z){if(F9=$,eK=Z??null,!z7($))l6($,{recursive:!0});if(Jz(),A)Yz().catch(()=>{})}async function G7($,Z,Q,Y,J,X){let K=Xz(),V=`${$z}${K}`,G={id:K,name:$.trim(),scheduleType:Z,time:Q,dateOrDay:X,action:Y,target:J.trim(),enabled:!0,taskName:V,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};if(A)await K7(G);return c=[...c,G],M8(),G}async function H7($){let Z=$.toLowerCase(),Q=c.findIndex((J)=>J.id===$||J.name.toLowerCase().includes(Z));if(Q===-1)return!1;let Y=c[Q];if(A)await R9(Y.taskName,Y.id);return c=[...c.slice(0,Q),...c.slice(Q+1)],M8(),!0}async function q7($){let Z=M7($);if(!Z||Z.enabled)return null;if(A)await K7(Z);return c=c.map((Q)=>Q.id===Z.id?{...Q,enabled:!0,updatedAt:new Date().toISOString()}:Q),M8(),c.find((Q)=>Q.id===Z.id)??null}async function U7($){let Z=M7($);if(!Z||!Z.enabled)return null;if(A)await R9(Z.taskName,void 0);return c=c.map((Q)=>Q.id===Z.id?{...Q,enabled:!1,updatedAt:new Date().toISOString()}:Q),M8(),c.find((Q)=>Q.id===Z.id)??null}function b1($=!1){return $?[...c]:c.filter((Z)=>Z.enabled)}function n6($){return M7($)}async function W7($){let Z=M7($);if(!Z)return"Agendamento nao encontrado.";if(A){let Q=await u$("Run",Z.taskName);if(Q.exitCode!==0)return`Erro ao executar: ${Q.stderr}`}return c=c.map((Q)=>Q.id===Z.id?{...Q,lastRun:new Date().toISOString()}:Q),M8(),`Agendamento "${Z.name}" executado.`}function _1($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Q)=>{let Y=Q.enabled?"ativo":"desativado",J=Kz(Q),X=Q.action==="toast"?"msg":Q.action==="command"?"cmd":"wf";return` [${Q.id}] ${Q.name} \u2014 ${J} [${X}] (${Y})`});return`Agendamentos (${$.length}):
|
|
109
119
|
${Z.join(`
|
|
110
|
-
`)}`}function
|
|
111
|
-
${
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
120
|
+
`)}`}function O9($){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: ${u6($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${u6($.lastRun)}`);return Z.join(`
|
|
121
|
+
`)}function B7($){let Z=$.toLowerCase().trim(),Q=Z.match(/^(\d{1,2}):(\d{2})$/);if(Q){let X=parseInt(Q[1]),K=parseInt(Q[2]);if(X>=0&&X<=23&&K>=0&&K<=59)return`${String(X).padStart(2,"0")}:${String(K).padStart(2,"0")}`}let Y=Z.match(/^(\d{1,2})h(\d{2})?$/);if(Y){let X=parseInt(Y[1]),K=parseInt(Y[2]||"0");if(X>=0&&X<=23&&K>=0&&K<=59)return`${String(X).padStart(2,"0")}:${String(K).padStart(2,"0")}`}let J=Z.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/);if(J){let X=parseInt(J[1]),K=parseInt(J[2]||"0"),V=J[3]==="pm";if(X===12)X=V?12:0;else if(V)X+=12;if(X>=0&&X<=23&&K>=0&&K<=59)return`${String(X).padStart(2,"0")}:${String(K).padStart(2,"0")}`}return null}function C7($){let Z=$.toLowerCase().trim(),Q=new Date;if(Z==="hoje"||Z==="today")return d6(Q);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let X=new Date(Q);return X.setDate(X.getDate()+1),d6(X)}let Y=Z.match(/^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})$/);if(Y){let X=parseInt(Y[1]),K=parseInt(Y[2]),V=parseInt(Y[3]);if(X>=1&&X<=31&&K>=1&&K<=12&&V>=2024)return`${String(K).padStart(2,"0")}/${String(X).padStart(2,"0")}/${V}`}let J=Z.match(/^(\d{1,2})[/.-](\d{1,2})$/);if(J){let X=parseInt(J[1]),K=parseInt(J[2]);if(X>=1&&X<=31&&K>=1&&K<=12)return`${String(K).padStart(2,"0")}/${String(X).padStart(2,"0")}/${Q.getFullYear()}`}return null}function N7($){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 K7($){let Z=Qz($),Q=[];switch($.scheduleType){case"once":if(Q.push("/SC","ONCE"),$.dateOrDay)Q.push("/SD",$.dateOrDay);break;case"daily":Q.push("/SC","DAILY");break;case"weekly":if(Q.push("/SC","WEEKLY"),$.dateOrDay)Q.push("/D",$.dateOrDay);break}Q.push("/ST",$.time),Q.push("/TR",Z),Q.push("/F");try{await u$("Create",$.taskName,Q)}catch{}}async function R9($,Z){try{await u$("Delete",$,["/F"])}catch{}if(Z)Zz(Z)}function r6(){let $=V7(F9,"scripts");if(!z7($))l6($,{recursive:!0});return $}function c6($,Z,Q){let Y=r6(),J=V7(Y,`toast_${$}.ps1`),X=`# Toast notification script for smolerclaw
|
|
122
|
+
# Job ID: ${$}
|
|
123
|
+
# Generated: ${new Date().toISOString()}
|
|
124
|
+
|
|
125
|
+
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
|
126
|
+
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
|
|
127
|
+
|
|
128
|
+
$title = '${Z.replace(/'/g,"''")}'
|
|
129
|
+
$body = '${Q.replace(/'/g,"''")}'
|
|
130
|
+
|
|
131
|
+
$template = @"
|
|
132
|
+
<toast>
|
|
133
|
+
<visual>
|
|
134
|
+
<binding template="ToastText02">
|
|
135
|
+
<text id="1">$title</text>
|
|
136
|
+
<text id="2">$body</text>
|
|
137
|
+
</binding>
|
|
138
|
+
</visual>
|
|
139
|
+
<audio src="ms-winsoundevent:Notification.Reminder"/>
|
|
140
|
+
</toast>
|
|
141
|
+
"@
|
|
142
|
+
|
|
143
|
+
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
|
144
|
+
$xml.LoadXml($template)
|
|
145
|
+
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
|
146
|
+
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show($toast)
|
|
147
|
+
`,K=Buffer.from([239,187,191]),V=Buffer.concat([K,Buffer.from(X,"utf-8")]);return iK(J,V),J}function Zz($){let Z=V7(r6(),`toast_${$}.ps1`);try{if(z7(Z))sK(Z)}catch{}}function Qz($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${c6($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${c6($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function Yz(){if(!A)return;for(let $ of c){if(!$.enabled)continue;try{if((await u$("Query",$.taskName)).exitCode!==0)await K7($)}catch{await K7($)}}}function i6(){}async function s6(){let $=0;for(let Z of c){if(A)await R9(Z.taskName,Z.id);$++}return c=[],M8(),`${$} agendamento(s) removido(s).`}function Jz(){let $=o6();if(!z7($)){c=[];return}try{c=JSON.parse(rK($,"utf-8"))}catch{c=[]}}function M8(){S(o6(),JSON.stringify(c,null,2))}function Xz(){return tK().slice(0,8)}function M7($){let Z=$.toLowerCase();return c.find((Q)=>Q.id===$||Q.name.toLowerCase().includes(Z))??null}function Kz($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${zz($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function zz($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function u6($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function d6($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}n();import{existsSync as e6,mkdirSync as Vz,readFileSync as Gz}from"fs";import{join as Hz}from"path";import{randomUUID as qz}from"crypto";var $3="",L4=[],Z3=()=>Hz($3,"finance.json");function Uz(){S(Z3(),JSON.stringify(L4,null,2))}function Wz(){let $=Z3();if(!e6($)){L4=[];return}try{L4=JSON.parse(Gz($,"utf-8"))}catch{L4=[]}}function Q3($){if($3=$,!e6($))Vz($,{recursive:!0});Wz()}function v1($,Z,Q,Y){let J={id:Bz(),type:$,amount:Math.abs(Z),category:Q.toLowerCase().trim(),description:Y.trim(),date:new Date().toISOString()};return L4=[...L4,J],Uz(),J}function F7($,Z){let Q=new Date,Y=$||Q.getFullYear(),J=Z!==void 0?Z:Q.getMonth(),X=L4.filter((B)=>{let W=new Date(B.date);return W.getFullYear()===Y&&W.getMonth()===J});if(X.length===0)return`Nenhuma transacao em ${t6(J)}/${Y}.`;let K=X.filter((B)=>B.type==="entrada").reduce((B,W)=>B+W.amount,0),V=X.filter((B)=>B.type==="saida").reduce((B,W)=>B+W.amount,0),G=K-V,H=new Map;for(let B of X.filter((W)=>W.type==="saida"))H.set(B.category,(H.get(B.category)||0)+B.amount);let z=[`--- Resumo ${t6(J)}/${Y} ---`,`Entradas: R$ ${K.toFixed(2)}`,`Saidas: R$ ${V.toFixed(2)}`,`Saldo: R$ ${G.toFixed(2)} ${G>=0?"":"(NEGATIVO)"}`];if(H.size>0){z.push(""),z.push("Saidas por categoria:");let B=[...H.entries()].sort((W,N)=>N[1]-W[1]);for(let[W,N]of B){let O=V>0?Math.round(N/V*100):0;z.push(` ${W.padEnd(15)} R$ ${N.toFixed(2)} (${O}%)`)}}return z.join(`
|
|
148
|
+
`)}function E9($=10){let Z=[...L4].sort((Y,J)=>new Date(J.date).getTime()-new Date(Y.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
|
|
149
|
+
${Z.map((Y)=>{let J=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.type==="entrada"?"+":"-";return` [${J}] ${X} R$ ${Y.amount.toFixed(2)} ${Y.category} \u2014 ${Y.description} [${Y.id}]`}).join(`
|
|
150
|
+
`)}`}function Bz(){return qz().slice(0,8)}function t6($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}n();import{existsSync as Y3,mkdirSync as Cz,readFileSync as Nz}from"fs";import{join as Mz}from"path";import{randomUUID as Fz}from"crypto";var J3="",j4=[],X3=()=>Mz(J3,"decisions.json");function Oz(){S(X3(),JSON.stringify(j4,null,2))}function Rz(){let $=X3();if(!Y3($)){j4=[];return}try{j4=JSON.parse(Nz($,"utf-8"))}catch{j4=[]}}function K3($){if(J3=$,!Y3($))Cz($,{recursive:!0});Rz()}function z3($,Z,Q,Y,J=[]){let X={id:Ez(),title:$.trim(),context:Z.trim(),chosen:Q.trim(),alternatives:Y?.trim(),tags:J.map((K)=>K.toLowerCase()),date:new Date().toISOString()};return j4=[...j4,X],Oz(),X}function a4($){let Z=$.toLowerCase();return j4.filter((Q)=>Q.title.toLowerCase().includes(Z)||Q.chosen.toLowerCase().includes(Z)||Q.context.toLowerCase().includes(Z)||Q.tags.some((Y)=>Y.includes(Z))).sort((Q,Y)=>new Date(Y.date).getTime()-new Date(Q.date).getTime())}function O7($=15){return[...j4].sort((Z,Q)=>new Date(Q.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function F8($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Q)=>{let Y=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"";return` [${Y}] ${Q.title}${J} {${Q.id}}`});return`Decisoes (${$.length}):
|
|
118
151
|
${Z.join(`
|
|
119
|
-
`)}`}function
|
|
152
|
+
`)}`}function Ez(){return Fz().slice(0,8)}h1();n();import{existsSync as B3,mkdirSync as Iz,readFileSync as xz}from"fs";import{join as Sz}from"path";import{randomUUID as wz}from"crypto";var C3="",f={people:[],interactions:[],delegations:[]},N3=()=>Sz(C3,"people.json");function L7(){S(N3(),JSON.stringify(f,null,2))}function kz(){let $=N3();if(!B3($)){f={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(xz($,"utf-8"));f={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{f={people:[],interactions:[],delegations:[]}}}function M3($){if(C3=$,!B3($))Iz($,{recursive:!0});kz()}function j7($,Z,Q,Y){let J={id:b9(),name:$.trim(),group:Z,role:Q?.trim(),contact:Y?.trim(),createdAt:new Date().toISOString()};return f={...f,people:[...f.people,J]},L7(),J}function $4($){let Z=$.toLowerCase();return f.people.find((Q)=>Q.id===$||Q.name.toLowerCase().includes(Z))||null}function D7($){if($)return f.people.filter((Z)=>Z.group===$);return[...f.people]}function F3($,Z,Q,Y){let J=$4($);if(!J)return null;let X={id:b9(),personId:J.id,date:new Date().toISOString(),type:Z,summary:Q.trim(),followUpDate:Y?.toISOString(),followUpDone:!1};return f={...f,interactions:[...f.interactions,X]},L7(),X}function yz($,Z=10){let Q=$4($);if(!Q)return[];return[...f.interactions].filter((Y)=>Y.personId===Q.id).reverse().sort((Y,J)=>new Date(J.date).getTime()-new Date(Y.date).getTime()).slice(0,Z)}function O8(){let $=new Date,Z=[];for(let Q of f.interactions){if(Q.followUpDone||!Q.followUpDate)continue;let Y=new Date(Q.followUpDate);if(isNaN(Y.getTime()))continue;if(Y<=$){let J=f.people.find((X)=>X.id===Q.personId);if(J)Z.push({person:J,interaction:Q})}}return Z.sort((Q,Y)=>new Date(Q.interaction.followUpDate).getTime()-new Date(Y.interaction.followUpDate).getTime())}function P7($,Z,Q){let Y=$4($);if(!Y)return null;let J={id:b9(),personId:Y.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Q?.toISOString(),status:"pendente"};return f={...f,delegations:[...f.delegations,J]},L7(),J}function O3($,Z,Q){if(!f.delegations.find((J)=>J.id===$))return null;return f={...f,delegations:f.delegations.map((J)=>J.id===$?{...J,status:Z,notes:Q||J.notes}:J)},L7(),f.delegations.find((J)=>J.id===$)||null}function n4($,Z=!0){let Q=[...f.delegations];if($){let J=$4($);if(!J)return[];Q=Q.filter((X)=>X.personId===J.id)}if(Z)Q=Q.filter((J)=>J.status!=="concluido");let Y=new Date;return Q=Q.map((J)=>{if(J.status==="pendente"&&J.dueDate){let X=new Date(J.dueDate);if(!isNaN(X.getTime())&&X<Y)return{...J,status:"atrasado"}}return J}),Q.sort((J,X)=>{if(J.status==="atrasado"&&X.status!=="atrasado")return-1;if(X.status==="atrasado"&&J.status!=="atrasado")return 1;let K=J.dueDate?new Date(J.dueDate).getTime():1/0,V=X.dueDate?new Date(X.dueDate).getTime():1/0;return K-V})}var R3={equipe:"Equipe",familia:"Familia",contato:"Contato"};function T7($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let J of $){let X=Z.get(J.group)||[];Z.set(J.group,[...X,J])}let Q=[],Y=["equipe","familia","contato"];for(let J of Y){let X=Z.get(J);if(!X?.length)continue;let K=X.map((V)=>{let G=V.role?` (${V.role})`:"",H=V.contact?` \u2014 ${V.contact}`:"";return` ${V.name}${G}${H} [${V.id}]`});Q.push(`--- ${R3[J]} ---
|
|
120
153
|
${K.join(`
|
|
121
|
-
`)}`)}return
|
|
154
|
+
`)}`)}return Q.join(`
|
|
122
155
|
|
|
123
|
-
`)}function
|
|
124
|
-
Interacoes recentes:`);for(let
|
|
125
|
-
Tarefas delegadas:`);for(let
|
|
126
|
-
`)}function
|
|
156
|
+
`)}function A7($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${R3[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Q=yz($.id,5);if(Q.length>0){Z.push(`
|
|
157
|
+
Interacoes recentes:`);for(let J of Q){let X=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${X}] ${J.type}: ${J.summary}`)}}let Y=n4($.id);if(Y.length>0){Z.push(`
|
|
158
|
+
Tarefas delegadas:`);for(let J of Y){let X=J.status==="atrasado"?"!!":J.status==="em_andamento"?">>":" ",K=J.dueDate?` (${_9(J.dueDate)})`:"";Z.push(` ${X} ${J.task}${K} [${J.status}]`)}}return Z.join(`
|
|
159
|
+
`)}function I7($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Q)=>{let J=f.people.find((V)=>V.id===Q.personId)?.name||"?",X=Q.status==="atrasado"?"!! ":Q.status==="em_andamento"?">> ":" ",K=Q.dueDate?` (${_9(Q.dueDate)})`:"";return`${X}${J}: ${Q.task}${K} [${Q.status}] [${Q.id}]`});return`Delegacoes (${$.length}):
|
|
127
160
|
${Z.join(`
|
|
128
|
-
`)}`}function
|
|
161
|
+
`)}`}function x7($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Q,interaction:Y})=>{return` [${_9(Y.followUpDate)}] ${Q.name}: ${Y.summary} [${Y.id}]`});return`Follow-ups pendentes (${$.length}):
|
|
129
162
|
${Z.join(`
|
|
130
|
-
`)}`}function
|
|
131
|
-
`);let Z=f.people.filter((H)=>H.group==="equipe").length,
|
|
132
|
-
!! ${
|
|
133
|
-
!! ${K.length} delegacao(oes) atrasada(s):`);for(let H of K.slice(0,5)){let z=f.people.find((
|
|
163
|
+
`)}`}function E3(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
|
|
164
|
+
`);let Z=f.people.filter((H)=>H.group==="equipe").length,Q=f.people.filter((H)=>H.group==="familia").length,Y=f.people.filter((H)=>H.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Q} | Contatos: ${Y}`);let J=O8();if(J.length>0){$.push(`
|
|
165
|
+
!! ${J.length} follow-up(s) pendente(s):`);for(let{person:H,interaction:z}of J.slice(0,5))$.push(` ${H.name}: ${z.summary}`)}let X=n4(),K=X.filter((H)=>H.status==="atrasado"),V=X.filter((H)=>H.status==="pendente"||H.status==="em_andamento");if(K.length>0){$.push(`
|
|
166
|
+
!! ${K.length} delegacao(oes) atrasada(s):`);for(let H of K.slice(0,5)){let z=f.people.find((B)=>B.id===H.personId);$.push(` ${z?.name}: ${H.task}`)}}if(V.length>0)$.push(`
|
|
134
167
|
${V.length} delegacao(oes) em andamento`);let G=[...f.interactions].sort((H,z)=>new Date(z.date).getTime()-new Date(H.date).getTime()).slice(0,3);if(G.length>0){$.push(`
|
|
135
|
-
Ultimas interacoes:`);for(let H of G){let z=f.people.find((
|
|
168
|
+
Ultimas interacoes:`);for(let H of G){let z=f.people.find((W)=>W.id===H.personId),B=new Date(H.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${B}] ${z?.name}: ${H.summary}`)}}return $.push(`
|
|
136
169
|
========================`),$.join(`
|
|
137
|
-
`)}function
|
|
138
|
-
[${
|
|
139
|
-
`)}function
|
|
170
|
+
`)}function b9(){return wz().slice(0,8)}function _9($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Q=new Date,Y=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()),J=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(J.getTime()===Y.getTime())return"hoje";let X=new Date(Y);if(X.setDate(X.getDate()+1),J.getTime()===X.getTime())return"amanha";let K=Math.floor((J.getTime()-Y.getTime())/86400000);if(K<0)return`${Math.abs(K)}d atras`;if(K<=7)return`em ${K}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}n();import{existsSync as L3,mkdirSync as bz,readFileSync as _z}from"fs";import{join as vz}from"path";import{randomUUID as fz}from"crypto";var j3="",i=[],D3=()=>vz(j3,"materials.json");function v9(){S(D3(),JSON.stringify(i,null,2))}function hz(){let $=D3();if(!L3($)){i=[];return}try{i=JSON.parse(_z($,"utf-8"))}catch{i=[]}}function P3($){if(j3=$,!L3($))bz($,{recursive:!0});hz()}function S7($,Z,Q="geral",Y=[]){let J=new Date().toISOString(),X=Z.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],K=$.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],V=[...new Set([...Y.map((H)=>H.toLowerCase()),...X,...K])],G={id:gz(),title:$.trim(),content:Z.trim(),category:Q.toLowerCase().trim(),tags:V,createdAt:J,updatedAt:J};return i=[...i,G],v9(),G}function T3($,Z){let Q=i.find((H)=>H.id===$);if(!Q)return null;let Y=Z.content??Q.content,J=Z.title??Q.title,X=Y.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],K=J.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],V=Z.tags??Q.tags,G=[...new Set([...V.map((H)=>H.toLowerCase()),...X,...K])];return i=i.map((H)=>H.id===$?{...H,title:J.trim(),content:Y.trim(),category:(Z.category??H.category).toLowerCase().trim(),tags:G,updatedAt:new Date().toISOString()}:H),v9(),i.find((H)=>H.id===$)||null}function w7($){let Z=i.findIndex((Q)=>Q.id===$);if(Z===-1)return!1;return i=[...i.slice(0,Z),...i.slice(Z+1)],v9(),!0}function A3($){return i.find((Z)=>Z.id===$)||null}function R8($){let Z=$.toLowerCase().trim();if(!Z)return[...i];let Q=Z.startsWith("#"),Y=Z.startsWith("@"),J=Q||Y?Z.slice(1):Z;return i.filter((X)=>{if(Q)return X.tags.some((K)=>K.includes(J));if(Y)return X.category.includes(J);return X.title.toLowerCase().includes(J)||X.content.toLowerCase().includes(J)||X.category.toLowerCase().includes(J)||X.tags.some((K)=>K.includes(J))}).sort((X,K)=>new Date(K.updatedAt).getTime()-new Date(X.updatedAt).getTime())}function E8($=30,Z){let Q=[...i];if(Z){let Y=Z.toLowerCase().trim();Q=Q.filter((J)=>J.category===Y)}return Q.sort((Y,J)=>new Date(J.updatedAt).getTime()-new Date(Y.updatedAt).getTime()).slice(0,$)}function I3(){let $=new Map;for(let Z of i)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,Q])=>({category:Z,count:Q})).sort((Z,Q)=>Q.count-Z.count)}function x3(){if(i.length===0)return"";let $=I3(),Z=["--- Materiais do Assistente ---"];for(let{category:Q}of $){let Y=i.filter((J)=>J.category===Q).sort((J,X)=>new Date(X.updatedAt).getTime()-new Date(J.updatedAt).getTime());Z.push(`
|
|
171
|
+
[${Q}]`);for(let J of Y){let X=J.content.length>200?J.content.slice(0,200).replace(/\n/g," ")+"...":J.content.replace(/\n/g," "),K=J.tags.length>0?` [${J.tags.map((V)=>`#${V}`).join(" ")}]`:"";Z.push(` \u2022 ${J.title}: ${X}${K}`)}}return Z.join(`
|
|
172
|
+
`)}function D4($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((Q)=>{let Y=new Date(Q.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Q.tags.length>0?` [${Q.tags.map((K)=>`#${K}`).join(" ")}]`:"",X=Q.content.length>60?Q.content.slice(0,60).replace(/\n/g," ")+"...":Q.content.replace(/\n/g," ");return` [${Y}] (${Q.category}) ${Q.title} \u2014 ${X}${J} {${Q.id}}`});return`Materiais (${$.length}):
|
|
140
173
|
${Z.join(`
|
|
141
|
-
`)}`}function
|
|
174
|
+
`)}`}function S3($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),Q=new Date($.updatedAt).toLocaleDateString("pt-BR"),Y=$.tags.length>0?`Tags: ${$.tags.map((X)=>`#${X}`).join(" ")}`:"",J=Z===Q?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${Q}`;return`--- Material {${$.id}} ---
|
|
142
175
|
Titulo: ${$.title}
|
|
143
176
|
Categoria: ${$.category}
|
|
144
177
|
|
|
145
178
|
${$.content}
|
|
146
179
|
|
|
147
180
|
${Y}
|
|
148
|
-
${
|
|
149
|
-
${$.map((
|
|
150
|
-
`)}`}function
|
|
181
|
+
${J}`}function w3(){let $=I3();if($.length===0)return"Nenhuma categoria.";return`Categorias:
|
|
182
|
+
${$.map((Q)=>` @${Q.category} (${Q.count})`).join(`
|
|
183
|
+
`)}`}function gz(){return fz().slice(0,8)}n();import{existsSync as i4,mkdirSync as mz,readFileSync as L8,readdirSync as pz}from"fs";import{join as r4}from"path";import{createHash as cz}from"crypto";var b3=1,f9=400,uz=80,k3=1.5,y3=0.75,dz=10,lz=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"]),g1="",k7="",X$=[],Z4={},Q4=0,Y4={},y7=!1,g9=()=>r4(k7,"rag-index.json");function _3($){if(g1=$,k7=r4($,"rag"),!i4(k7))mz(k7,{recursive:!0});tz(),y7=!0}function b7(){return y7}function _7(){return{chunks:X$.length,sources:Object.keys(Y4).length,builtAt:X$.length>0?ez()?.builtAt??null:null}}function v7(){if(!y7)throw Error("Memory not initialized. Call initMemory() first.");let $=rz(),Z=0,Q=0,Y={},J=new Set;for(let[K,V]of Object.entries($)){let G=$V(V);if(Y[K]=G,Y4[K]!==G)J.add(K)}let X=Object.keys(Y4).filter((K)=>!(K in $));if(J.size===0&&X.length===0)return{indexed:0,skipped:Object.keys($).length,total:X$.length};X$=X$.filter((K)=>{let V=`${K.source}:${K.sourceId}`;return!J.has(V)&&!X.includes(V)});for(let K of J){let V=$[K],G=K.indexOf(":");if(G===-1)continue;let H=K.slice(0,G),z=K.slice(G+1);if(!["memo","material","session","decision"].includes(H))continue;let W=ZV(H,z,V),N=nz(V,H,z,W);X$=[...X$,...N],Z++}return Q=Object.keys($).length-Z,iz(),Y4=Y,sz(),{indexed:Z,skipped:Q,total:X$.length}}function f7($,Z=3){if(X$.length===0)return[];let Q=h9($);if(Q.length===0)return[];return X$.map((J)=>{let X=oz(Q,J),K=az(Q,J),V=0.6*X+0.4*K;return{chunk:J,score:V}}).filter((J)=>J.score>0).sort((J,X)=>X.score-J.score).slice(0,Math.min(Z,dz))}function h7($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Q,Y)=>{let J=QV(Q.chunk.source),X=(Q.score*100).toFixed(1),K=Q.chunk.content.length>300?Q.chunk.content.slice(0,300).replace(/\n/g," ")+"...":Q.chunk.content.replace(/\n/g," ");return`[${Y+1}] ${J}: ${Q.chunk.title} (relevancia: ${X}%)
|
|
151
184
|
${K}`});return`Resultados da memoria (${$.length}):
|
|
152
185
|
|
|
153
186
|
${Z.join(`
|
|
154
187
|
|
|
155
|
-
`)}`}function
|
|
188
|
+
`)}`}function oz($,Z){let Q=Z.tokens.length;if(Q===0||Q4===0)return 0;let Y=new Map;for(let X of Z.tokens)Y.set(X,(Y.get(X)??0)+1);let J=0;for(let X of $){let K=Y.get(X)??0;if(K===0)continue;let V=Z4[X]??0;if(V===0)continue;let G=K*(k3+1),H=K+k3*(1-y3+y3*(Q/Q4));J+=V*(G/H)}return J}function az($,Z){let Q=new Map;for(let H of $)Q.set(H,(Q.get(H)??0)+1);let Y=new Map;for(let H of Z.tokens)Y.set(H,(Y.get(H)??0)+1);let J=new Set([...$,...Z.tokens]),X=0,K=0,V=0;for(let H of J){let z=Z4[H]??0,B=(Q.get(H)??0)*z,W=(Y.get(H)??0)*z;X+=B*W,K+=B*B,V+=W*W}let G=Math.sqrt(K)*Math.sqrt(V);return G>0?X/G:0}function h9($){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&&!lz.has(Z))}function nz($,Z,Q,Y){let J=$.trim();if(J.length===0)return[];if(J.length<=f9)return[{id:`${Z}:${Q}:0`,source:Z,sourceId:Q,title:Y,content:J,tokens:h9(J)}];let X=[],K=0,V=0;while(K<J.length){let G=Math.min(K+f9,J.length),H=J.slice(K,G);X.push({id:`${Z}:${Q}:${V}`,source:Z,sourceId:Q,title:Y,content:H,tokens:h9(H)}),K+=f9-uz,V++}return X}function rz(){let $={},Z=r4(g1,"memos.json");if(i4(Z))try{let X=JSON.parse(L8(Z,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let K of X){if(!K||typeof K!=="object")continue;let V=K;if(typeof V.id!=="string"||typeof V.content!=="string")continue;let G=Array.isArray(V.tags)&&V.tags.length>0?` [${V.tags.join(", ")}]`:"";$[`memo:${V.id}`]=`${V.content}${G}`}}catch{}let Q=r4(g1,"materials.json");if(i4(Q))try{let X=JSON.parse(L8(Q,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let K of X){if(!K||typeof K!=="object")continue;let V=K;if(typeof V.id!=="string"||typeof V.title!=="string"||typeof V.content!=="string")continue;let G=typeof V.category==="string"?V.category:"geral",H=Array.isArray(V.tags)&&V.tags.length>0?` [${V.tags.join(", ")}]`:"";$[`material:${V.id}`]=`${V.title}
|
|
156
189
|
${G}
|
|
157
|
-
${V.content}${H}`}}catch{}let Y=
|
|
158
|
-
`)}}catch{}let
|
|
190
|
+
${V.content}${H}`}}catch{}let Y=r4(g1,"decisions.json");if(i4(Y))try{let X=JSON.parse(L8(Y,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let K of X){if(!K||typeof K!=="object")continue;let V=K;if(typeof V.id!=="string"||typeof V.title!=="string"||typeof V.context!=="string"||typeof V.chosen!=="string")continue;let G=[V.title,V.context,`Escolha: ${V.chosen}`];if(typeof V.alternatives==="string")G.push(`Alternativas: ${V.alternatives}`);if(Array.isArray(V.tags)&&V.tags.length>0)G.push(`[${V.tags.join(", ")}]`);$[`decision:${V.id}`]=G.join(`
|
|
191
|
+
`)}}catch{}let J=r4(g1,"sessions");if(i4(J))try{let X=pz(J,{withFileTypes:!0}).filter((K)=>K.isFile()&&K.name.endsWith(".json")&&!K.name.startsWith(".")).map((K)=>K.name);for(let K of X){let V=r4(J,K);try{let G=JSON.parse(L8(V,"utf-8"));if(!G||typeof G!=="object"||!Array.isArray(G.messages))continue;let H=G.messages.filter((z)=>{if(!z||typeof z!=="object")return!1;let B=z;return B.role==="assistant"&&typeof B.content==="string"&&B.content.length>50}).map((z)=>z.content).join(`
|
|
159
192
|
---
|
|
160
|
-
`);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function
|
|
161
|
-
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"memo":return
|
|
162
|
-
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"session":return`Sessao ${Z}`;default:return Z}}function
|
|
193
|
+
`);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function iz(){let $=X$.length;if($===0){Z4={},Q4=0;return}let Z=new Map,Q=0;for(let J of X$){let X=new Set;for(let K of J.tokens)if(!X.has(K))Z.set(K,(Z.get(K)??0)+1),X.add(K);Q+=J.tokens.length}Q4=Q/$;let Y={};for(let[J,X]of Z)Y[J]=Math.log(($-X+0.5)/(X+0.5)+1);Z4=Y}function sz(){if(!y7)return;let $={chunks:X$,idf:Z4,avgDocLength:Q4,sourceHashes:Y4,builtAt:new Date().toISOString(),version:b3};S(g9(),JSON.stringify($))}function tz(){let $=g9();if(!i4($)){X$=[],Z4={},Q4=0,Y4={};return}try{let Z=JSON.parse(L8($,"utf-8"));if(Z.version!==b3){X$=[],Z4={},Q4=0,Y4={};return}X$=Z.chunks,Z4=Z.idf,Q4=Z.avgDocLength,Y4=Z.sourceHashes}catch{X$=[],Z4={},Q4=0,Y4={}}}function ez(){let $=g9();if(!i4($))return null;try{return{builtAt:JSON.parse(L8($,"utf-8")).builtAt}}catch{return null}}function $V($){return cz("sha256").update($).digest("hex").slice(0,16)}function ZV($,Z,Q){switch($){case"material":{let Y=Q.split(`
|
|
194
|
+
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"memo":return Q.slice(0,60).replace(/\n/g," ")+(Q.length>60?"...":"");case"decision":{let Y=Q.split(`
|
|
195
|
+
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"session":return`Sessao ${Z}`;default:return Z}}function QV($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}Z$();b8();d$();import{writeFileSync as YV,unlinkSync as JV,existsSync as XV}from"fs";import{join as KV}from"path";import{tmpdir as zV}from"os";import{randomUUID as VV}from"crypto";var GV=30000,v3=50000;var HV=[{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)"}],qV=[{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 m9($){for(let{pattern:Z,reason:Q}of HV)if(Z.test($))return{safe:!1,blocked:!0,reason:Q};for(let{pattern:Z,reason:Q}of qV)if(Z.test($))return{safe:!1,blocked:!1,reason:Q};return{safe:!0,blocked:!1}}async function m1($){if(!A)return{stdout:"",stderr:"Error: PowerShell scripts only available on Windows.",exitCode:1,duration:0};if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>v3)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${v3}).`,exitCode:1,duration:0};let Z=m9($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};let Q=VV().slice(0,8),Y=KV(zV(),`smolerclaw-${Q}.ps1`);try{YV(Y,$,"utf-8");let J=await sZ(Y,{timeout:GV});return{stdout:J.stdout,stderr:J.timedOut?"Script timeout exceeded":J.stderr,exitCode:J.exitCode,duration:J.duration}}finally{try{if(XV(Y))JV(Y)}catch{}}}async function g7(){if(!A)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await UV();if($.type==="text")return $;return await WV()}async function UV(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await F5($,{timeout:1e4});if(Z.timedOut)return{type:"error",text:"Clipboard read timeout."};let Q=Z.stdout.trim();if(Q==="___EMPTY___"||!Q)return{type:"empty",text:""};return{type:"text",text:Q}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function WV(){try{let Z=await F5(`
|
|
163
196
|
Add-Type -AssemblyName System.Windows.Forms
|
|
164
197
|
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
165
198
|
if (-not $img) {
|
|
@@ -209,8 +242,8 @@ try {
|
|
|
209
242
|
} finally {
|
|
210
243
|
if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
|
|
211
244
|
}
|
|
212
|
-
`,{timeout:20000});if(Z.timedOut)return{type:"error",text:"OCR timeout."};let
|
|
213
|
-
${
|
|
245
|
+
`,{timeout:20000});if(Z.timedOut)return{type:"error",text:"OCR timeout."};let Q=Z.stdout.trim();if(Q==="___NO_IMAGE___")return{type:"empty",text:""};if(Q==="___NO_TEXT___")return{type:"image",text:"(Imagem detectada no clipboard, mas sem texto reconhecivel)"};if(Q.startsWith("___OCR_ERROR___"))return{type:"error",text:`OCR falhou: ${Q.replace("___OCR_ERROR___: ","")}`};if(Q)return{type:"image",text:`[OCR do clipboard]
|
|
246
|
+
${Q}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function m7(){if(!A)return"Error: screen context analysis only available on Windows.";let $=`
|
|
214
247
|
$sig = @'
|
|
215
248
|
[DllImport("user32.dll")]
|
|
216
249
|
public static extern IntPtr GetForegroundWindow();
|
|
@@ -243,48 +276,61 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
|
|
|
243
276
|
$marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
|
|
244
277
|
Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
|
|
245
278
|
}
|
|
246
|
-
`;try{let Z=await
|
|
247
|
-
$
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
279
|
+
`;try{let Z=await U$($,{timeout:15000});if(Z.timedOut)return"Error: screen context analysis timeout";let Q=Z.stdout.trim();if(!Q&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;return Q||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function f3($,Z){if(!A)return{success:!1,error:"Notifications only available on Windows."};if(!$?.trim())return{success:!1,error:"Title is required."};if(!Z?.trim())return{success:!1,error:"Message is required."};let Q=$.replace(/'/g,"''"),Y=Z.replace(/'/g,"''"),J=`
|
|
280
|
+
$notificationTitle = '${Q}'
|
|
281
|
+
$notificationText = '${Y}'
|
|
282
|
+
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
|
|
283
|
+
$template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
|
|
284
|
+
$toastXml = [xml]$template.GetXml()
|
|
285
|
+
$toastXml.GetElementsByTagName('text').Item(0).AppendChild($toastXml.CreateTextNode($notificationTitle)) > $null
|
|
286
|
+
$toastXml.GetElementsByTagName('text').Item(1).AppendChild($toastXml.CreateTextNode($notificationText)) > $null
|
|
287
|
+
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
|
288
|
+
$xml.LoadXml($toastXml.OuterXml)
|
|
289
|
+
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
|
290
|
+
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Smolerclaw').Show($toast)
|
|
291
|
+
Write-Output 'OK'
|
|
292
|
+
`;try{let X=await m1(J);if(X.exitCode===0&&X.stdout.includes("OK"))return{success:!0};return{success:!1,error:X.stderr||"Unknown error sending notification."}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}n();import{existsSync as I$,mkdirSync as BV,readFileSync as c7}from"fs";import{join as N$,basename as CV}from"path";import{randomUUID as NV}from"crypto";var j8="",S$=[],x$=[],g$=[],P4=null,h3=()=>N$(j8,"projects.json"),g3=()=>N$(j8,"work-sessions.json"),m3=()=>N$(j8,"opportunities.json"),p3=()=>N$(j8,"active-project.txt");function MV(){S(h3(),JSON.stringify(S$,null,2))}function c9(){S(g3(),JSON.stringify(x$,null,2))}function c3(){S(m3(),JSON.stringify(g$,null,2))}function FV(){S(p3(),P4||"")}function OV(){S$=p9(h3,[]),x$=p9(g3,[]),g$=p9(m3,[]);let $=p3();if(I$($))try{P4=c7($,"utf-8").trim()||null}catch{P4=null}}function p9($,Z){let Q=$();if(!I$(Q))return Z;try{return JSON.parse(c7(Q,"utf-8"))}catch(Y){if(process.env.DEBUG)console.error(`[projects] Failed to load ${Q}: ${Y instanceof Error?Y.message:Y}`);return Z}}function u3($){if(j8=$,!I$($))BV($,{recursive:!0});OV()}function u9($,Z,Q="",Y=[],J=[]){let X={id:d9(),name:$.trim(),path:Z.trim(),description:Q.trim(),tags:Y.map((K)=>K.trim().toLowerCase()).filter(Boolean),techStack:J.map((K)=>K.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return S$=[...S$,X],MV(),X}function u7($){let Z=$.toLowerCase().trim();return S$.find((Q)=>Q.id===$)||S$.find((Q)=>Q.name.toLowerCase()===Z)||S$.find((Q)=>Q.name.toLowerCase().includes(Z))||null}function D8($=!1){return($?S$.filter((Q)=>Q.active):[...S$]).sort((Q,Y)=>new Date(Y.createdAt).getTime()-new Date(Q.createdAt).getTime())}function P8($){let Z=u7($);if(!Z)return null;return P4=Z.id,FV(),Z}function T4(){if(!P4)return null;return S$.find(($)=>$.id===P4)||null}function d7($,Z=""){if(!S$.find((J)=>J.id===$))return null;RV($);let Y={id:d9(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return x$=[...x$,Y],c9(),Y}function l7($,Z){let Q=x$.find((K)=>K.id===$);if(!Q||Q.endedAt)return null;let Y=new Date,J=new Date(Q.startedAt),X=Math.round((Y.getTime()-J.getTime())/60000);return x$=x$.map((K)=>K.id===$?{...K,endedAt:Y.toISOString(),durationMinutes:X,notes:Z?`${K.notes}
|
|
293
|
+
${Z}`.trim():K.notes}:K),c9(),x$.find((K)=>K.id===$)||null}function RV($){let Z=new Date;x$=x$.map((Q)=>{if(Q.projectId===$&&!Q.endedAt){let Y=new Date(Q.startedAt),J=Math.round((Z.getTime()-Y.getTime())/60000);return{...Q,endedAt:Z.toISOString(),durationMinutes:J}}return Q}),c9()}function A4($){return x$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function EV($,Z,Q){let Y=Q||new Date;return x$.filter((J)=>{if(J.projectId!==$)return!1;let X=new Date(J.startedAt);return X>=Z&&X<=Y})}async function LV($,Z="1 day ago"){if(!I$(N$($,".git")))return null;try{let Q=await p7(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!Q.ok||!Q.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Y=Q.stdout.trim().split(`
|
|
294
|
+
`).filter(Boolean),J=[...new Set(Y.map((O)=>O.split("|||")[0]))],X=Y.map((O)=>O.split("|||")[1]||"").filter(Boolean),K=await p7(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),V=await p7(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),G=0,H=0,z=0;if(V.ok&&V.stdout.trim())for(let O of V.stdout.trim().split(`
|
|
295
|
+
`)){let j=O.match(/(\d+)\s+files?\s+changed/),P=O.match(/(\d+)\s+insertions?/),_=O.match(/(\d+)\s+deletions?/);if(j)G+=parseInt(j[1]);if(P)H+=parseInt(P[1]);if(_)z+=parseInt(_[1])}let B=await p7(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),W=new Map;if(B.ok&&B.stdout.trim())for(let O of B.stdout.trim().split(`
|
|
296
|
+
`).filter(Boolean))W.set(O,(W.get(O)||0)+1);let N=[...W.entries()].sort((O,j)=>j[1]-O[1]).slice(0,10).map(([O])=>O);return{commits:Y.length,authors:J,filesChanged:G,insertions:H,deletions:z,topFiles:N,messages:X}}catch{return null}}async function p7($,Z){let Q=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Y,J]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),X=await Q.exited;return{stdout:Y.trim(),stderr:J.trim(),ok:X===0}}function d3($,Z,Q,Y=[],J="media",X=null){let K=new Date().toISOString(),V={id:d9(),title:$.trim(),description:Z.trim(),source:Q.trim(),techRequired:Y.map((G)=>G.toLowerCase()),priority:J,status:"nova",deadline:X,createdAt:K,updatedAt:K};return g$=[...g$,V],c3(),V}function l3($,Z){if(!g$.find((Y)=>Y.id===$))return null;return g$=g$.map((Y)=>Y.id===$?{...Y,status:Z,updatedAt:new Date().toISOString()}:Y),c3(),g$.find((Y)=>Y.id===$)||null}function o7($,Z){let Q=[...g$];if($)Q=Q.filter((Y)=>Y.status===$);if(Z&&Z.length>0){let Y=Z.map((J)=>J.toLowerCase());Q=Q.filter((J)=>J.techRequired.some((X)=>Y.includes(X)))}return Q.sort((Y,J)=>{let X={alta:3,media:2,baixa:1};return(X[J.priority]||0)-(X[Y.priority]||0)})}async function a7($,Z="today",Q="pt"){let Y=u7($);if(!Y)return null;let X=new Date(new Date);switch(Z){case"today":X.setHours(0,0,0,0);break;case"week":X.setDate(X.getDate()-7);break;case"month":X.setDate(X.getDate()-30);break}let K=Z==="today"?"1 day ago":Z==="week"?"7 days ago":"30 days ago",V=await LV(Y.path,K),G=EV(Y.id,X),H=G.reduce((W,N)=>W+N.durationMinutes,0),z=0;try{let W=N$(j8,"tasks.json");if(I$(W))z=JSON.parse(c7(W,"utf-8")).filter((O)=>{if(!O.done)return!1;return new Date(O.createdAt)>=X}).length}catch{}let B=jV(Y,Z,V,G,H,z,Q);return{project:Y,period:Z,gitSummary:V,sessions:G,totalMinutes:H,completedTasks:z,markdown:B}}function jV($,Z,Q,Y,J,X,K){let V=K==="pt",G=[],H=new Date,z=H.toLocaleDateString(V?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(G.push(`# ${V?"Relatorio de Progresso":"Work Progress Report"}`),G.push(`**${V?"Projeto":"Project"}:** ${$.name}`),G.push(`**${V?"Periodo":"Period"}:** ${Z} (${z})`),G.push(`**${V?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)G.push(`**Tech:** ${$.techStack.join(", ")}`);G.push("");let B=Math.floor(J/60),W=J%60;if(G.push(`## ${V?"Tempo Trabalhado":"Time Tracked"}`),G.push(`- **${V?"Total":"Total"}:** ${B}h ${W}m`),G.push(`- **${V?"Sessoes":"Sessions"}:** ${Y.length}`),X>0)G.push(`- **${V?"Tarefas concluidas":"Tasks completed"}:** ${X}`);if(G.push(""),Q&&Q.commits>0){if(G.push(`## ${V?"Atividade Git":"Git Activity"}`),G.push(`- **Commits:** ${Q.commits}`),Q.authors.length>0)G.push(`- **${V?"Autores":"Authors"}:** ${Q.authors.join(", ")}`);if(G.push(`- **${V?"Arquivos alterados":"Files changed"}:** ${Q.filesChanged}`),G.push(`- **${V?"Linhas":"Lines"}:** +${Q.insertions} / -${Q.deletions}`),Q.messages.length>0){G.push(""),G.push(`### ${V?"Commits recentes":"Recent commits"}`);for(let N of Q.messages.slice(0,15))G.push(`- ${N}`)}if(Q.topFiles.length>0){G.push(""),G.push(`### ${V?"Arquivos mais alterados":"Most changed files"}`);for(let N of Q.topFiles.slice(0,8))G.push(`- \`${N}\``)}G.push("")}else G.push(`## ${V?"Atividade Git":"Git Activity"}`),G.push(V?"_Nenhum commit no periodo._":"_No commits in this period._"),G.push("");if(Y.length>0){G.push(`## ${V?"Sessoes de Trabalho":"Work Sessions"}`);for(let N of Y){let O=new Date(N.startedAt).toLocaleTimeString(V?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),j=N.durationMinutes>0?`${N.durationMinutes}m`:V?"em andamento":"ongoing",P=N.notes?` \u2014 ${N.notes}`:"";G.push(`- ${O} (${j})${P}`)}G.push("")}return G.push("---"),G.push(V?`_Gerado por smolerclaw em ${H.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${H.toLocaleString("en-US")}_`),G.join(`
|
|
297
|
+
`)}function n7($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Q)=>{let Y=Q.id===P4?" [ATIVO]":"",J=Q.active?"":" (inativo)",X=Q.techStack.length>0?` [${Q.techStack.join(", ")}]`:"";return` ${Q.name}${Y}${J}${X} \u2014 ${Q.path} {${Q.id}}`});return`Projetos (${$.length}):
|
|
252
298
|
${Z.join(`
|
|
253
|
-
`)}`}function
|
|
254
|
-
`)}function
|
|
299
|
+
`)}`}function r7($){let Z=$.id===P4?" [ATIVO]":"",Q=[`--- Projeto {${$.id}}${Z} ---`,`Nome: ${$.name}`,`Caminho: ${$.path}`];if($.description)Q.push(`Descricao: ${$.description}`);if($.techStack.length>0)Q.push(`Tech: ${$.techStack.join(", ")}`);if($.tags.length>0)Q.push(`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`);Q.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Q.push(`Status: ${$.active?"ativo":"inativo"}`);let Y=A4($.id);if(Y){let J=new Date(Y.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Q.push(`Sessao aberta: desde ${J}`)}return Q.join(`
|
|
300
|
+
`)}function i7($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((Q)=>{let Y={alta:"!!!",media:"!!",baixa:"!"}[Q.priority],J=Q.techRequired.length>0?` [${Q.techRequired.join(", ")}]`:"",X=Q.deadline?` \u2014 prazo: ${Q.deadline}`:"";return` ${Y} (${Q.status}) ${Q.title}${J}${X} \u2014 ${Q.source} {${Q.id}}`});return`Oportunidades (${$.length}):
|
|
255
301
|
${Z.join(`
|
|
256
|
-
`)}`}function
|
|
257
|
-
`)}function
|
|
258
|
-
`);
|
|
259
|
-
`)}function
|
|
260
|
-
`)}function
|
|
261
|
-
`)}function
|
|
262
|
-
`)}
|
|
263
|
-
`)}function
|
|
264
|
-
${Z}`:$,Y=
|
|
265
|
-
`)}function
|
|
302
|
+
`)}`}function s7(){let $=T4();if(!$)return"";let Z=A4($.id),Q=g$.filter((J)=>J.status==="nova").length,Y=["--- Projetos ---"];if(Y.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let J=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta desde ${J}`)}if(Q>0)Y.push(`${Q} oportunidade(s) nova(s) pendente(s)`);return Y.join(`
|
|
303
|
+
`)}function t7($){let Z=S$.find((J)=>J.path===$);if(Z)return Z;if(!I$(N$($,".git")))return null;let Q=[];if(I$(N$($,"package.json")))try{let J=JSON.parse(c7(N$($,"package.json"),"utf-8"));if(J.dependencies?.typescript||J.devDependencies?.typescript)Q.push("typescript");if(J.dependencies?.react)Q.push("react");if(J.dependencies?.next)Q.push("nextjs");if(J.dependencies?.vue)Q.push("vue");if(I$(N$($,"bun.lock")))Q.push("bun");else Q.push("node")}catch{}if(I$(N$($,"Cargo.toml")))Q.push("rust");if(I$(N$($,"go.mod")))Q.push("go");if(I$(N$($,"requirements.txt"))||I$(N$($,"pyproject.toml")))Q.push("python");let Y=CV($);return u9(Y,$,"",[],Q)}function d9(){return NV().slice(0,8)}n();Z$();import{existsSync as a9,mkdirSync as DV,readFileSync as n3}from"fs";import{join as r3,basename as PV}from"path";var i3=2,s3="pitwall-baselines.json",TV=0.1,AV=0.05,IV=5000000,xV=512000,o3=2048,SV=120000,Z5="",Y$=[];function t3($){if(Z5=$,!a9($))DV($,{recursive:!0});hV()}async function a3($,Z){let Y=[...Q8(),$],J=process.cpuUsage(),X=Bun.nanoseconds(),K=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe",cwd:Z}),V=setTimeout(()=>K.kill(),SV),G=K.pid,H=wV(G),[,z]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]),B=await K.exited;clearTimeout(V);let W=Bun.nanoseconds(),N=process.cpuUsage(J),O=await H,j=z.length>o3?`...${z.slice(-o3)}`:z;return{durationNs:W-X,peakMemoryBytes:O,cpuUserUs:N.user,cpuSystemUs:N.system,exitCode:B,stderr:j.trim()}}async function n9($,Z={}){let Q=Z.cwd||process.cwd(),Y=Math.min(Math.max(Z.iterations||1,1),10),J=Z.scriptKey||fV($);if(Z.warmup&&Y>1)await a3($,Q);let X=[];for(let z=0;z<Y;z++)X.push(await a3($,Q));let K=X[X.length-1],V=X.map((z)=>z.durationNs),G={durationNs:l9(V),peakMemoryBytes:Math.max(...X.map((z)=>z.peakMemoryBytes)),cpuUserUs:l9(X.map((z)=>z.cpuUserUs)),cpuSystemUs:l9(X.map((z)=>z.cpuSystemUs))},H=Y>1?{min:Math.min(...V),max:Math.max(...V),median:G.durationNs,stddev:vV(V)}:null;return{scriptKey:J,command:$,metrics:G,spread:H,exitCode:K.exitCode,stderr:K.stderr,timestamp:new Date().toISOString(),iterations:Y}}async function wV($){try{if(A){let Z=`(Get-Process -Id ${$} -ErrorAction SilentlyContinue).PeakWorkingSet64`,Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>Q.kill(),5000),J=await new Response(Q.stdout).text();await Q.exited,clearTimeout(Y);let X=parseInt(J.trim(),10);if(!isNaN(X)&&X>0)return X}else{let Z=`/proc/${$}/status`;if(a9(Z)){let Y=n3(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Y)return parseInt(Y[1],10)*1024}}}catch{}return process.memoryUsage().rss}function e3($,Z=[]){let Q=Y$.find((X)=>X.scriptKey===$.scriptKey),Y=new Date().toISOString();if(Q){let X=Q.runs+1,K={durationNs:Math.round((Q.metrics.durationNs*Q.runs+$.metrics.durationNs)/X),peakMemoryBytes:Math.round((Q.metrics.peakMemoryBytes*Q.runs+$.metrics.peakMemoryBytes)/X),cpuUserUs:Math.round((Q.metrics.cpuUserUs*Q.runs+$.metrics.cpuUserUs)/X),cpuSystemUs:Math.round((Q.metrics.cpuSystemUs*Q.runs+$.metrics.cpuSystemUs)/X)},V={...Q,metrics:K,spread:$.spread||Q.spread,updatedAt:Y,runs:X,tags:[...new Set([...Q.tags,...Z])]};return Y$=Y$.map((G)=>G.scriptKey===$.scriptKey?V:G),Q5(),V}let J={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return Y$=[...Y$,J],Q5(),J}function kV($){return Y$.find((Z)=>Z.scriptKey===$)||null}function $Q(){return[...Y$].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function r9($){let Z=Y$.findIndex((Q)=>Q.scriptKey===$);if(Z===-1)return!1;return Y$=[...Y$.slice(0,Z),...Y$.slice(Z+1)],Q5(),!0}function ZQ($,Z=[]){r9($.scriptKey);let Q=new Date().toISOString(),Y={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return Y$=[...Y$,Y],Q5(),Y}function i9($){let Z=kV($.scriptKey),Q=[];if(Z)Q.push(e7("duration",Z.metrics.durationNs,$.metrics.durationNs,IV),e7("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,xV),e7("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),e7("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Y=Q.some((X)=>X.severity==="regression"),J=_V($,Z,Q,Y);return{run:$,baseline:Z,alerts:Q,hasRegression:Y,markdown:J}}function e7($,Z,Q,Y){let J=Q-Z;if(Z===0||Math.abs(J)<Y)return{metric:$,baselineValue:Z,currentValue:Q,deltaPercent:0,absoluteDelta:J,severity:"ok"};let X=J/Z,K="ok";if(X>TV)K="regression";else if(X>AV)K="warning";return{metric:$,baselineValue:Z,currentValue:Q,deltaPercent:Math.round(X*1e4)/100,absoluteDelta:J,severity:K}}function J4($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function o9($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function $5($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function yV($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function bV($){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 _V($,Z,Q,Y){let J=[];if(Y)J.push("=== PIT WALL: REGRESSAO DETECTADA ===");else J.push("=== Pit Wall: Relatorio de Performance ===");if(J.push(`Script: ${$.scriptKey}`),J.push(`Comando: ${$.command}`),J.push(`Execucoes: ${$.iterations}`),$.exitCode!==0)J.push(`Exit code: ${$.exitCode} (FALHA)`);if(J.push(""),J.push("--- Metricas Atuais ---"),J.push(` Duracao: ${J4($.metrics.durationNs)}`),J.push(` Memoria: ${o9($.metrics.peakMemoryBytes)}`),J.push(` CPU (user): ${$5($.metrics.cpuUserUs)}`),J.push(` CPU (sys): ${$5($.metrics.cpuSystemUs)}`),$.spread){J.push(""),J.push("--- Dispersao ---"),J.push(` Min: ${J4($.spread.min)}`),J.push(` Max: ${J4($.spread.max)}`),J.push(` Mediana: ${J4($.spread.median)}`),J.push(` Stddev: ${J4($.spread.stddev)}`);let X=$.spread.median>0?($.spread.stddev/$.spread.median*100).toFixed(1):"0";if(J.push(` CV: ${X}%`),parseFloat(X)>15)J.push(" (!) Alta variancia \u2014 resultados podem ser inst\xE1veis")}if($.exitCode!==0&&$.stderr)J.push(""),J.push("--- Stderr ---"),J.push($.stderr.slice(0,500));if(J.push(""),!Z)return J.push("Nenhum baseline salvo para este script."),J.push("Use pitwall_save_baseline para definir o baseline atual."),J.join(`
|
|
304
|
+
`);J.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${QQ(Z.updatedAt)}) ---`),J.push(` Duracao: ${J4(Z.metrics.durationNs)}`),J.push(` Memoria: ${o9(Z.metrics.peakMemoryBytes)}`),J.push(` CPU (user): ${$5(Z.metrics.cpuUserUs)}`),J.push(` CPU (sys): ${$5(Z.metrics.cpuSystemUs)}`),J.push(""),J.push("--- Comparacao ---");for(let X of Q){let K=X.deltaPercent>=0?"+":"",V=bV(X.metric);J.push(` ${yV(X.severity)} ${V}: ${K}${X.deltaPercent}%`)}if(J.push(""),Y)J.push("*** ALERTA: Regressao de performance > 10% detectada! ***"),J.push("Revise as mudancas recentes no codigo.");else if(Q.some((X)=>X.severity==="warning"))J.push("Atencao: algumas metricas estao proximas do limite (5-10%).");else J.push("Performance dentro do esperado.");return J.join(`
|
|
305
|
+
`)}function QQ($){let Z=Date.now()-new Date($).getTime(),Q=Math.floor(Z/60000);if(Q<60)return`ha ${Q}min`;let Y=Math.floor(Q/60);if(Y<24)return`ha ${Y}h`;return`ha ${Math.floor(Y/24)}d`}function YQ($){if($.length===0)return"Nenhum baseline salvo no Pit Wall.";let Z=["=== Pit Wall: Baselines ===",""];for(let Q of $){let Y=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"",J=QQ(Q.updatedAt);if(Z.push(` ${Q.scriptKey}`),Z.push(` Duracao: ${J4(Q.metrics.durationNs)} | Memoria: ${o9(Q.metrics.peakMemoryBytes)} | ${Q.runs} runs | ${J}${Y}`),Q.spread){let X=Q.spread.median>0?(Q.spread.stddev/Q.spread.median*100).toFixed(1):"0";Z.push(` Spread: ${J4(Q.spread.min)} ~ ${J4(Q.spread.max)} (CV ${X}%)`)}Z.push("")}return Z.join(`
|
|
306
|
+
`)}function l9($){if($.length===0)return 0;let Z=[...$].sort((Y,J)=>Y-J),Q=Math.floor(Z.length/2);return Z.length%2!==0?Z[Q]:Math.round((Z[Q-1]+Z[Q])/2)}function vV($){if($.length<2)return 0;let Z=$.reduce((Y,J)=>Y+J,0)/$.length,Q=$.reduce((Y,J)=>Y+(J-Z)**2,0)/($.length-1);return Math.round(Math.sqrt(Q))}function fV($){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 PV(Z[0])}function hV(){let $=r3(Z5,s3);if(!a9($)){Y$=[];return}try{let Z=JSON.parse(n3($,"utf-8"));if(Z.version!==i3&&Z.version!==1){Y$=[];return}Y$=(Z.baselines||[]).map(gV)}catch{Y$=[]}}function gV($){let{durationMs:Z,...Q}=$.metrics;return{...$,metrics:Q,spread:$.spread||null}}function Q5(){if(!Z5)return;let $=r3(Z5,s3);S($,JSON.stringify({baselines:Y$,version:i3},null,2))}Z$();import{readdirSync as mV,readFileSync as pV,lstatSync as cV}from"fs";import{join as uV,resolve as p1,relative as s9,dirname as dV,extname as lV}from"path";var oV=[".ts",".tsx",".mts",".cts"],aV=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],nV=new Set(y8),JQ=5000,rV=5000,XQ=new Map;function iV($){let Z=XQ.get($);if(Z&&Date.now()-Z.ts<rV)return Z.graph;return null}function sV($,Z){XQ.set($,{graph:Z,ts:Date.now()})}var tV=[/^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 eV($){let Z=new Set,Q=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Y of tV){Y.lastIndex=0;let J;while((J=Y.exec(Q))!==null){let X=J[1];if(X.startsWith("./")||X.startsWith("../"))Z.add(X)}}return[...Z]}function $G($){let Z=[];function Q(Y){if(Z.length>=JQ)return;let J;try{J=mV(Y)}catch{return}for(let X of J){if(Z.length>=JQ)return;if(nV.has(X))continue;let K=uV(Y,X),V;try{V=cV(K)}catch{continue}if(V.isSymbolicLink())continue;if(V.isDirectory())Q(K);else if(V.isFile()&&oV.includes(lV(X)))Z.push(K)}}return Q($),Z}function ZG($,Z,Q){let Y=dV(Z),J=p1(Y,$);if(Q.has(J))return J;for(let X of aV){let K=J+X;if(Q.has(K))return K}return null}function t9($){let Z=p1($),Q=iV(Z);if(Q)return Q;let Y=$G(Z),J=new Set(Y),X=new Map,K=new Map;for(let G of Y)X.set(G,new Set),K.set(G,new Set);for(let G of Y){let H;try{H=pV(G,"utf-8")}catch{continue}let z=eV(H),B=X.get(G);for(let W of z){let N=ZG(W,G,J);if(N){B.add(N);let O=K.get(N)||new Set;O.add(G),K.set(N,O)}}}let V={imports:X,importedBy:K,files:Y,root:Z};return sV(Z,V),V}function e9($,Z){let Q=p1(Z),Y=$.importedBy.get(Q)||new Set,J=[...Y],X=new Set([Q]),K=[],V=new Map,G=0;for(let O of Y)K.push({file:O,depth:1}),X.add(O),V.set(O,1);let H=[],z=0;while(z<K.length){let{file:O,depth:j}=K[z++];if(j>G)G=j;if(!Y.has(O))H.push(O);let P=$.importedBy.get(O)||new Set;for(let _ of P)if(!X.has(_))X.add(_),V.set(_,j+1),K.push({file:_,depth:j+1})}let B=KQ(Q,$.importedBy,new Set,0),W=(O)=>s9($.root,O).replace(/\\/g,"/"),N=new Map;for(let[O,j]of V)N.set(W(O),j);return{target:W(Q),directDependents:J.map(W),transitiveDependents:H.map(W),depthMap:N,totalAffected:J.length+H.length,depth:G,tree:zQ(B,$.root)}}function KQ($,Z,Q,Y){Q.add($);let J=Z.get($)||new Set,X=[];for(let K of J)if(!Q.has(K))X.push(KQ(K,Z,Q,Y+1));return{file:$,depth:Y,children:X}}function zQ($,Z){return{file:s9(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Q)=>zQ(Q,Z))}}function VQ($,Z){let Q=p1(Z),Y=e9($,Z),J=(O)=>p1($.root,O),X=new Set([...Y.directDependents.map(J),...Y.transitiveDependents.map(J)]);X.add(Q);let K=new Map;for(let O of X)K.set(O,0);for(let O of X){let j=$.importedBy.get(O)||new Set;for(let P of j)if(X.has(P)&&P!==O)K.set(O,(K.get(O)||0)+1)}let V=[];for(let[O,j]of K)if(j===0&&O!==Q)V.push(O);let G=[],H=new Set,z=0;while(z<V.length){let O=V[z++];G.push(O),H.add(O);let j=$.imports.get(O)||new Set;for(let P of j)if(X.has(P)&&!H.has(P)&&P!==Q){let _=(K.get(P)||1)-1;if(K.set(P,_),_===0)V.push(P)}}for(let O of X)if(!H.has(O)&&O!==Q)G.push(O);let B=[Q,...G],W=(O)=>s9($.root,O).replace(/\\/g,"/"),N=B.map((O)=>{let P=[...$.imports.get(O)||new Set].filter(($$)=>X.has($$)).map(W),_=W(O),q$=O===Q?0:Y.depthMap.get(_)||1;return{file:_,depth:q$,dependsOn:P}});return{target:W(Q),order:N,totalFiles:N.length}}function GQ($){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 Q of $.directDependents)Z.push(` ${Q}`);Z.push("")}if($.transitiveDependents.length>0){Z.push(`--- Dependentes transitivos (${$.transitiveDependents.length}) ---`);for(let Q of $.transitiveDependents){let Y=$.depthMap.get(Q)||0;Z.push(` ${Q} (depth ${Y})`)}Z.push("")}if($.totalAffected===0)Z.push("Nenhum arquivo depende deste modulo. Blast radius = 0."),Z.push("");return Z.push("--- Arvore de impacto ---"),HQ($.tree,Z,"",!0),Z.join(`
|
|
307
|
+
`)}function HQ($,Z,Q,Y){let J=Y?"\u2514\u2500 ":"\u251C\u2500 ",X=$.depth===0?`[ALVO] ${$.file}`:$.file;Z.push(`${Q}${J}${X}`);let K=Q+(Y?" ":"\u2502 ");for(let V=0;V<$.children.length;V++)HQ($.children[V],Z,K,V===$.children.length-1)}function qQ($){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 Q=0;Q<$.order.length;Q++){let Y=$.order[Q],J=`${Q+1}`.padStart(3),X=Y.depth===0?"[ALVO]":`[depth ${Y.depth}]`;if(Z.push(` ${J}. ${Y.file} ${X}`),Y.dependsOn.length>0)Z.push(` depende de: ${Y.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(`
|
|
308
|
+
`)}n();import{existsSync as $Z,mkdirSync as QG,readFileSync as WQ}from"fs";import{join as BQ}from"path";import{randomUUID as YG}from"crypto";var ZZ=[{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"}],QZ="",X4=[],K4=[],CQ=()=>BQ(QZ,"engine-tradeoffs.json"),NQ=()=>BQ(QZ,"engine-incidents.json");function JG(){S(CQ(),JSON.stringify(X4,null,2))}function XG(){S(NQ(),JSON.stringify(K4,null,2))}function KG(){let $=CQ();if(!$Z($)){X4=[];return}try{X4=JSON.parse(WQ($,"utf-8"))}catch{X4=[]}}function zG(){let $=NQ();if(!$Z($)){K4=[];return}try{K4=JSON.parse(WQ($,"utf-8"))}catch{K4=[]}}function MQ($){if(QZ=$,!$Z($))QG($,{recursive:!0});KG(),zG()}function FQ($,Z,Q=ZZ){let Y=Q.reduce((z,B)=>z+B.weight,0);if(Math.abs(Y-1)>0.01)Q=Q.map((B)=>({...B,weight:B.weight/Y}));let J={};for(let z of Z){let B=0;for(let W of Q){let N=z.scores[W.name]??3;B+=N*W.weight}J[z.name]=Math.round(B*100)/100}let K=Object.entries(J).sort(([,z],[,B])=>B-z)[0]?.[0]||Z[0]?.name||"N/A",V=Z.find((z)=>z.name===K),G=VG($,Z,Q,J,K,V),H={id:IQ(),context:$,options:Z,criteria:Q,recommendation:K,weightedScores:J,adr:G,createdAt:new Date().toISOString()};return X4=[...X4,H],JG(),H}function VG($,Z,Q,Y,J,X){let V=new Date().toISOString().split("T")[0],G=[`# ADR: ${$.title}`,"",`**Date:** ${V}`,"**Status:** Proposed","","## Context","",$.background,""];if($.constraints.length>0){G.push("### Constraints"),G.push("");for(let B of $.constraints)G.push(`- ${B}`);G.push("")}if($.stakeholders.length>0){G.push("### Stakeholders"),G.push("");for(let B of $.stakeholders)G.push(`- ${B}`);G.push("")}G.push("## Options Considered"),G.push("");for(let B of Z){if(G.push(`### ${B.name}`),G.push(""),G.push(B.description),G.push(""),B.pros.length>0){G.push("**Pros:**");for(let W of B.pros)G.push(`- ${W}`);G.push("")}if(B.cons.length>0){G.push("**Cons:**");for(let W of B.cons)G.push(`- ${W}`);G.push("")}}G.push("## Evaluation Matrix"),G.push("");let H=["Criterion (Weight)",...Z.map((B)=>B.name)];G.push(`| ${H.join(" | ")} |`),G.push(`| ${H.map(()=>"---").join(" | ")} |`);for(let B of Q){let W=Math.round(B.weight*100),N=[`${B.name} (${W}%)`,...Z.map((O)=>{return`${O.scores[B.name]??3}/5`})];G.push(`| ${N.join(" | ")} |`)}let z=["**Weighted Total**",...Z.map((B)=>`**${Y[B.name]?.toFixed(2)??"0.00"}**`)];if(G.push(`| ${z.join(" | ")} |`),G.push(""),G.push("## Decision"),G.push(""),G.push(`**Recommended:** ${J}`),G.push(""),X){if(G.push(`Based on the weighted evaluation, **${J}** scores highest with a weighted total of ${Y[J]?.toFixed(2)}.`),G.push(""),X.pros.length>0){G.push("Key advantages:");for(let B of X.pros.slice(0,3))G.push(`- ${B}`);G.push("")}}if(G.push("## Consequences"),G.push(""),G.push("### Positive"),G.push(""),X&&X.pros.length>0)for(let B of X.pros)G.push(`- ${B}`);else G.push("- *To be determined based on implementation*");if(G.push(""),G.push("### Negative"),G.push(""),X&&X.cons.length>0)for(let B of X.cons)G.push(`- ${B}`);else G.push("- *To be determined based on implementation*");return G.push(""),G.push("---"),G.push(""),G.push("*Generated by Decision Engine*"),G.join(`
|
|
309
|
+
`)}function UQ($){let Z=$.toLowerCase(),Q=[/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],Y=new Set;for(let G of Q){let H=Z.match(G);if(H)for(let z of H)Y.add(z.toLowerCase())}let J=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,X=$.match(J)||[];for(let G of X)if(G.length>3&&!G.match(/^(the|and|for|with|from|this|that)$/i))Y.add(G.toLowerCase());let K=/[A-Z]{2,}_[A-Z0-9_]+|E[0-9]{3,}/g,V=$.match(K)||[];for(let G of V)Y.add(G.toLowerCase());return[...Y]}function GG($,Z){if($.length===0||Z.length===0)return 0;let Q=new Set($),Y=new Set(Z),J=0;for(let K of Q)if(Y.has(K))J++;let X=Q.size+Y.size-J;return X>0?J/X:0}function OQ($,Z){let Q=Z?`${$}
|
|
310
|
+
${Z}`:$,Y=UQ(Q),J=[];for(let G of K4){let H=`${G.title} ${G.description} ${G.stacktrace||""} ${G.rootCause} ${G.solution}`,z=UQ(H),B=GG(Y,z);if(B>0.1){let W=Y.filter((j)=>z.includes(j)),N=[];for(let j of G.relatedDecisions){let P=a4(j);if(P.length>0)N.push(P[0])}let O=[];if(G.solution)O.push(`Apply solution: ${G.solution}`);if(G.rootCause)O.push(`Investigate root cause: ${G.rootCause}`);for(let j of N)O.push(`Review decision: ${j.title}`);J.push({incident:G,similarity:B,matchedKeywords:W,relatedDecisions:N,suggestedActions:O})}}J.sort((G,H)=>H.similarity-G.similarity);let X=a4($.slice(0,50)),K=R8($.slice(0,50)),V=HG($,J,X,K);return{query:$,matches:J.slice(0,5),materialsFound:K.slice(0,5),summary:V}}function HG($,Z,Q,Y){let J=["# Incident Correlation Report",""];if(J.push("## Query"),J.push(""),J.push("```"),J.push($.slice(0,500)),J.push("```"),J.push(""),Z.length>0){J.push("## Similar Past Incidents"),J.push("");for(let X of Z.slice(0,3)){let K=Math.round(X.similarity*100);if(J.push(`### ${X.incident.title} (${K}% match)`),J.push(""),J.push(`**Root Cause:** ${X.incident.rootCause}`),J.push(""),J.push(`**Solution:** ${X.incident.solution}`),J.push(""),X.matchedKeywords.length>0)J.push(`**Matched Keywords:** ${X.matchedKeywords.slice(0,5).join(", ")}`),J.push("");if(X.suggestedActions.length>0){J.push("**Suggested Actions:**");for(let V of X.suggestedActions.slice(0,3))J.push(`- ${V}`);J.push("")}}}else J.push("## Similar Past Incidents"),J.push(""),J.push("*No matching incidents found in the database.*"),J.push("");if(Q.length>0){J.push("## Related Decisions"),J.push("");for(let X of Q.slice(0,3))J.push(`- **${X.title}** (${X.date.split("T")[0]}): ${X.chosen}`);J.push("")}if(Y.length>0){J.push("## Relevant Materials"),J.push("");for(let X of Y.slice(0,3)){let K=X.content.length>100?X.content.slice(0,100).replace(/\n/g," ")+"...":X.content.replace(/\n/g," ");J.push(`- **${X.title}** (${X.category}): ${K}`)}J.push("")}return J.push("---"),J.push(""),J.push("*Generated by Decision Engine Post-Mortem Correlator*"),J.join(`
|
|
311
|
+
`)}function RQ($,Z,Q,Y,J,X=[],K=[]){let V={id:IQ(),title:$.trim(),description:Z.trim(),stacktrace:J?.trim(),rootCause:Q.trim(),solution:Y.trim(),relatedDecisions:X,tags:K.map((G)=>G.toLowerCase()),createdAt:new Date().toISOString()};return K4=[...K4,V],XG(),V}function EQ($){let Z=$.toLowerCase();return K4.filter((Q)=>Q.title.toLowerCase().includes(Z)||Q.description.toLowerCase().includes(Z)||Q.rootCause.toLowerCase().includes(Z)||Q.solution.toLowerCase().includes(Z)||Q.tags.some((Y)=>Y.includes(Z))).sort((Q,Y)=>new Date(Y.createdAt).getTime()-new Date(Q.createdAt).getTime())}function LQ($=10){return[...K4].sort((Z,Q)=>new Date(Q.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function jQ($=10){return[...X4].sort((Z,Q)=>new Date(Q.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function DQ($){let Z=$.toLowerCase();return X4.filter((Q)=>Q.context.title.toLowerCase().includes(Z)||Q.context.background.toLowerCase().includes(Z)||Q.recommendation.toLowerCase().includes(Z)||Q.options.some((Y)=>Y.name.toLowerCase().includes(Z)||Y.description.toLowerCase().includes(Z))).sort((Q,Y)=>new Date(Y.createdAt).getTime()-new Date(Q.createdAt).getTime())}function PQ($){return X4.find((Z)=>Z.id===$)||null}function TQ($){if($.length===0)return"Nenhuma analise de trade-off registrada.";let Z=$.map((Q)=>{return` [${new Date(Q.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}] ${Q.context.title} \u2192 ${Q.recommendation} {${Q.id}}`});return`Trade-offs (${$.length}):
|
|
266
312
|
${Z.join(`
|
|
267
|
-
`)}`}function
|
|
313
|
+
`)}`}function AQ($){if($.length===0)return"Nenhum incidente registrado.";let Z=$.map((Q)=>{let Y=new Date(Q.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Q.resolvedAt?"\u2713":"\u25CB",X=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"";return` ${J} [${Y}] ${Q.title}${X} {${Q.id}}`});return`Incidentes (${$.length}):
|
|
268
314
|
${Z.join(`
|
|
269
|
-
`)}`}function
|
|
270
|
-
`),$}function
|
|
271
|
-
`)});return["# Manual de Uso Otimizado","",`Baseado em ${
|
|
272
|
-
`)}var
|
|
273
|
-
`)}function
|
|
274
|
-
Tags: ${$.tags.map((
|
|
275
|
-
`)}function
|
|
315
|
+
`)}`}function IQ(){return YG().slice(0,8)}n();import{existsSync as u1,mkdirSync as xQ,readFileSync as YZ,readdirSync as qG,writeFileSync as SQ}from"fs";import{join as t4}from"path";import{homedir as UG}from"os";import{createHash as WG}from"crypto";var BG=20,wQ=3,CG=0.6,NG={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"]},MG={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."}},c1="",I4="",D$={events:[],sessionStart:Date.now()},s4=new Map,z4=[],j$=[],T8=!1,kQ=null,yQ=()=>t4(c1,"usage-patterns.json"),bQ=()=>t4(c1,"insights.json");function _Q($,Z){if(c1=t4($,"docs-engine"),I4=t4(UG(),".config","smolerclaw","materials","manual"),kQ=Z||null,!u1(c1))xQ(c1,{recursive:!0});if(!u1(I4))xQ(I4,{recursive:!0});SG(),kG(),yG(),D$={events:[],sessionStart:Date.now()},T8=!0}function JZ($){if(!T8)return;let Z={...$,timestamp:Date.now()},Q=[...D$.events,Z].slice(-BG);D$={...D$,events:Q},FG(Z),setImmediate(()=>OG(Z))}function FG($){let Z=`${$.type}:${$.name}`,Q=s4.get(Z);if(Q){let Y=Q.count+1,J=Q.avgDurationMs?(Q.avgDurationMs*Q.count+($.durationMs||0))/Y:$.durationMs||0;s4.set(Z,{action:Z,count:Y,avgDurationMs:J,lastUsed:$.timestamp})}else s4.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function OG($){let Z=D$.events.slice(-5).map((Q)=>Q.name).join(" ");for(let[Q,{pattern:Y,suggestion:J}]of Object.entries(MG))if(Y.test(Z)){if(!z4.find((K)=>K.type==="inefficient_pattern"&&K.relatedActions.includes($.name)&&Date.now()-new Date(K.createdAt).getTime()<3600000)){let K={id:e4(),type:"inefficient_pattern",title:`Padrao detectado: ${Q.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:J,relatedActions:D$.events.slice(-5).map((V)=>V.name),confidence:0.8,createdAt:new Date().toISOString()};vQ(K)}}}async function d1(){if(!T8)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=RG();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Q=EG();$.insightsGenerated+=Q.length;let Y=LG();$.insightsGenerated+=Y.length;for(let J of[...Z,...Q,...Y])if(vQ(J),await DG(J))$.manualUpdates++;return xG(),wG(),D$={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
|
|
316
|
+
`),$}function RG(){let $=[],Z=jG(D$.events);for(let Q of Z)if(Q.count>=wQ){let Y={id:e4(),type:"repetitive_task",title:`Tarefa repetitiva: ${Q.actions.slice(0,3).join(" -> ")}`,description:`Este padrao de acoes foi executado ${Q.count} vezes nesta sessao.`,recommendation:"Considere criar um workflow para automatizar esta sequencia.",relatedActions:Q.actions,confidence:Math.min(0.5+Q.count*0.1,1),createdAt:new Date().toISOString()};$.push(Y)}return $}function EG(){let $=[],Z=new Set;for(let Q of D$.events)if(Q.type==="tool:executed")Z.add(Q.name);for(let[Q,Y]of Object.entries(NG)){let J=Y.filter((K)=>Z.has(K)),X=Y.filter((K)=>!Z.has(K));if(J.length>0&&X.length>0){let K=J.length/Y.length;if(K>=CG){let V={id:e4(),type:"underutilized_tool",title:`Ferramentas subutilizadas: ${Q}`,description:`Voce usa ${J.join(", ")} mas nao ${X.join(", ")}.`,recommendation:`Experimente as ferramentas ${X.slice(0,2).join(" e ")} para aumentar sua produtividade.`,relatedActions:X,confidence:K,createdAt:new Date().toISOString()};$.push(V)}}}return $}function LG(){let $=[];if(Date.now()-D$.sessionStart>1800000&&!D$.events.some((Y)=>Y.name==="save_memo"))$.push({id:e4(),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 Q=D$.events.filter((Y)=>Y.name==="run_command").length;if(Q>=5&&!D$.events.some((Y)=>Y.name.includes("workflow")))$.push({id:e4(),type:"tip",title:"Dica: Automatize com workflows",description:`${Q} 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 jG($){let Z=new Map,Q=$.map((Y)=>Y.name);for(let Y=2;Y<=4;Y++)for(let J=0;J<=Q.length-Y;J++){let X=Q.slice(J,J+Y),K=X.join("|"),V=Z.get(K);if(V)Z.set(K,{...V,count:V.count+1});else Z.set(K,{actions:X,count:1})}return[...Z.values()].filter((Y)=>Y.count>=wQ)}function vQ($){if(!z4.some((Q)=>Q.type===$.type&&Q.title===$.title&&Date.now()-new Date(Q.createdAt).getTime()<86400000))z4=[...z4,$],kQ?.($)}function fQ($=5){return[...z4].sort((Z,Q)=>new Date(Q.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function DG($){try{let Z=AG($.type),Q=`${$.id}.md`,Y=t4(I4,Q),J=j$.find((G)=>G.id===$.id),X=J?J.version+1:1,K={id:$.id,title:$.title,category:Z,content:TG($),tags:IG($),source:"auto_generated",version:X,createdAt:J?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},V=pQ(K);return SQ(Y,V,"utf-8"),j$=j$.filter((G)=>G.id!==K.id),j$=[...j$,K],!0}catch{return!1}}async function hQ($,Z,Q="best_practice",Y=[]){if(!T8)return{success:!1,path:""};try{let J=e4(),X=`${_G($)}-${J.slice(0,4)}.md`,K=t4(I4,X),V={id:J,title:$,category:Q,content:Z,tags:Y,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},G=pQ(V);return SQ(K,G,"utf-8"),j$=[...j$,V],{success:!0,path:K,entry:V}}catch{return{success:!1,path:""}}}function PG($){let Q=$.toLowerCase().split(/\s+/).filter((Y)=>Y.length>2);return j$.map((Y)=>{let J=0,X=`${Y.title} ${Y.content} ${Y.tags.join(" ")}`.toLowerCase();for(let K of Q)if(X.includes(K))J++;return{entry:Y,score:J}}).filter((Y)=>Y.score>0).sort((Y,J)=>J.score-Y.score).map((Y)=>Y.entry)}function gQ($){let Z=$?PG($):j$;if(Z.length===0)return"Nenhum conteudo encontrado no manual. Execute /reflect para gerar insights baseados no seu uso.";let Q=Z.slice(0,5).map((Y)=>{let J=mQ[Y.category]||Y.category;return[`## ${Y.title}`,`*Categoria: ${J}*`,"",Y.content,"",Y.tags.length>0?`Tags: ${Y.tags.map((X)=>`#${X}`).join(" ")}`:""].filter(Boolean).join(`
|
|
317
|
+
`)});return["# Manual de Uso Otimizado","",`Baseado em ${j$.length} entradas do manual vivo.`,"",...Q].join(`
|
|
318
|
+
`)}var mQ={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function TG($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
|
|
319
|
+
`)}function pQ($){let Z=mQ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
|
|
320
|
+
Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`:""].filter(Boolean).join(`
|
|
321
|
+
`)}function AG($){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 IG($){let Z=new Set;Z.add($.type.replace(/_/g,"-"));for(let Q of $.relatedActions)if(Q.includes("_"))Z.add(Q.split("_")[0]);return[...Z]}function cQ($){return $.summary}function uQ($){if($.length===0)return"Nenhum insight disponivel.";let Z=$.map((Q)=>{return[`[${{repetitive_task:"Tarefa Repetitiva",underutilized_tool:"Ferramenta Subutilizada",inefficient_pattern:"Padrao Ineficiente",tip:"Dica"}[Q.type]||Q.type}] ${Q.title}`,` ${Q.recommendation}`,` Confianca: ${Math.round(Q.confidence*100)}%`].join(`
|
|
276
322
|
`)});return`Insights (${$.length}):
|
|
277
323
|
|
|
278
324
|
${Z.join(`
|
|
279
325
|
|
|
280
|
-
`)}`}function
|
|
281
|
-
`),Y=
|
|
282
|
-
`).match(/Tags:\s*(.+)/);if(G){let
|
|
283
|
-
`).trim(),tags:K,source:"auto_generated",version:X,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function
|
|
284
|
-
`):" (nenhuma)",Y=$.risks.length>0?$.risks.map((
|
|
285
|
-
`):" (nenhum identificado)";return[`**Objetivo:** ${$.objective}`,"",`**Complexidade:** ${$.complexity}`,"","**Estrat\xE9gia T\xE9cnica:**",...Z,"","**Premissas/Riscos:**",
|
|
286
|
-
`)}function
|
|
287
|
-
`)}function
|
|
326
|
+
`)}`}function xG(){if(!T8)return;let $=Object.fromEntries(s4);S(yQ(),JSON.stringify($,null,2))}function SG(){let $=yQ();if(!u1($)){s4=new Map;return}try{let Z=JSON.parse(YZ($,"utf-8"));s4=new Map(Object.entries(Z))}catch{s4=new Map}}function wG(){if(!T8)return;S(bQ(),JSON.stringify(z4,null,2))}function kG(){let $=bQ();if(!u1($)){z4=[];return}try{let Z=JSON.parse(YZ($,"utf-8"));z4=Array.isArray(Z)?Z:[]}catch{z4=[]}}function yG(){if(!u1(I4)){j$=[];return}try{let $=qG(I4,{withFileTypes:!0}).filter((Q)=>Q.isFile()&&Q.name.endsWith(".md")),Z=[];for(let Q of $){let Y=t4(I4,Q.name),J=YZ(Y,"utf-8"),X=bG(Q.name,J);if(X)Z.push(X)}j$=Z}catch{j$=[]}}function bG($,Z){try{let Q=Z.split(`
|
|
327
|
+
`),Y=Q[0]?.replace(/^#\s*/,"")||$.replace(".md",""),J="best_practice",X=1,K=[];for(let B of Q.slice(1,6)){if(B.startsWith("> Categoria:")){let W=B.replace("> Categoria:","").trim().toLowerCase();if(W==="workflow"||W==="tool"||W==="shortcut"||W==="best_practice")J=W}if(B.startsWith("> Versao:"))X=parseInt(B.replace("> Versao:","").trim())||1}let G=Q.slice(-3).join(`
|
|
328
|
+
`).match(/Tags:\s*(.+)/);if(G){let W=G[1].match(/#[\w-]+/g);if(W)K.push(...W.map((N)=>N.slice(1)))}let H=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:H?H[1]:e4(),title:Y,category:J,content:Q.slice(5).join(`
|
|
329
|
+
`).trim(),tags:K,source:"auto_generated",version:X,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function e4(){return WG("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function _G($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}n();b8();import{join as vG}from"path";import{createHash as fG}from"crypto";var hG={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},l1={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"]},gG=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],mG="",I=null,XZ=[],aQ={...hG},nQ=!1,dQ=null,pG=()=>vG(mG,"plan-history.json");function V4(){return nQ}function KZ($,Z){let Q=$.toLowerCase(),Y=cG(Q),J=Z?.files||[],X=Z?.modules||[],K=[],V=[];for(let z of J)for(let B of gG)if(B.test(z))K.push(`Modifying sensitive file: ${z}`);if(J.length>3)K.push(`Affects ${J.length} files \u2014 higher coordination risk`);if(X.length>1)K.push(`Spans ${X.length} modules \u2014 may have cascading effects`);if(Q.includes("api"))V.push("API contract may need versioning consideration");if(Q.includes("database")||Q.includes("schema"))V.push("Database changes may require migration");if(Q.includes("auth")||Q.includes("security"))V.push("Security changes require thorough review");let G=aQ.requireApprovalFor.includes(Y),H=G?`Task classified as "${Y}" \u2014 requires explicit approval`:`Task classified as "${Y}" \u2014 can proceed with auto-approval`;return{complexity:Y,filesAffected:J,modulesAffected:X,risks:K,assumptions:V,requiresApproval:G,reason:H}}function cG($){for(let Z of l1.architectural)if($.includes(Z))return"architectural";for(let Z of l1.complex)if($.includes(Z))return"complex";for(let Z of l1.moderate)if($.includes(Z))return"moderate";for(let Z of l1.simple)if($.includes(Z))return"simple";for(let Z of l1.trivial)if($.includes(Z))return"trivial";return"moderate"}function rQ($,Z,Q){let Y=KZ($),J={id:oQ(),objective:$,strategy:Z.map((X,K)=>({...X,id:oQ(),order:K+1,status:"pending"})),assumptions:[...Q?.assumptions||[],...Y.assumptions],risks:[...Q?.risks||[],...Y.risks],status:"draft",complexity:Y.complexity,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return I=J,q4().emit("planning:started",{planId:J.id,objective:$}),J}async function iQ(){if(!I)return{success:!1,plan:null,message:"No active plan to submit"};if(I.status!=="draft")return{success:!1,plan:I,message:`Plan already in status: ${I.status}`};if(I={...I,status:"pending_approval",updatedAt:new Date().toISOString()},aQ.autoApproveComplexity.includes(I.complexity))return lQ("Auto-approved based on complexity classification");if(dQ)if(await dQ(I))return lQ("Approved by user");else return uG("Rejected by user");return{success:!0,plan:I,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function lQ($){if(!I)return{success:!1,plan:null,message:"No active plan to approve"};if(I.status!=="pending_approval"&&I.status!=="draft")return{success:!1,plan:I,message:`Cannot approve plan in status: ${I.status}`};return I={...I,status:"approved",approvedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),userFeedback:$},q4().emit("planning:approved",{planId:I.id,feedback:$}),{success:!0,plan:I,message:"Plan approved \u2014 execution may proceed"}}function uG($){if(!I)return{success:!1,plan:null,message:"No active plan to reject"};return I={...I,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},q4().emit("planning:rejected",{planId:I.id,feedback:$}),ZY(I),I=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function sQ(){if(!I)return{allowed:!0,reason:"No plan required \u2014 trivial operation"};if(I.status==="approved"||I.status==="executing")return{allowed:!0,reason:"Plan approved \u2014 execution permitted"};if(I.status==="draft"||I.status==="pending_approval")return{allowed:!1,reason:`Execution blocked \u2014 plan awaiting approval (status: ${I.status})`};return{allowed:!1,reason:`Execution blocked \u2014 plan status: ${I.status}`}}function tQ($,Z){if(!I)return{success:!1,message:"No active plan"};let Q=I.strategy.findIndex((V)=>V.id===$);if(Q===-1)return{success:!1,message:`Step not found: ${$}`};let Y=I.strategy.map((V,G)=>G===Q?{...V,status:"completed",result:Z}:V);I={...I,strategy:Y,updatedAt:new Date().toISOString()},q4().emit("planning:step_completed",{planId:I.id,stepId:$,result:Z});let J=I.strategy.find((V)=>V.status==="pending"),X=I.strategy[Q].action;if(I.strategy.every((V)=>V.status==="completed"||V.status==="skipped"))dG();return{success:!0,message:`Step completed: ${X}`,nextStep:J}}function eQ($,Z,Q){if(!I)return{success:!1,message:"No active plan"};let Y=I.strategy.findIndex((X)=>X.id===$);if(Y===-1)return{success:!1,message:`Step not found: ${$}`};let J=I.strategy.map((X,K)=>K===Y?{...X,status:"blocked",blockedReason:Z}:X);return I={...I,strategy:J,status:"blocked",blockedAt:new Date().toISOString(),blockedReason:Z,updatedAt:new Date().toISOString()},q4().emit("planning:blocked",{planId:I.id,stepId:$,reason:Z,proposedAlternative:Q}),{success:!0,message:Q?`Step blocked: ${Z}. Proposed alternative: ${Q}`:`Step blocked: ${Z}. Awaiting user guidance.`}}function dG(){if(!I)return;I={...I,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},q4().emit("planning:completed",{planId:I.id,stepsCompleted:I.strategy.filter(($)=>$.status==="completed").length}),ZY(I),I=null}function o1(){return I?{...I}:null}function zZ($){let Z=$.strategy.map((J)=>{return`${J.status==="completed"?"\u2713":J.status==="in_progress"?"\u2192":J.status==="blocked"?"\u2717":"\u25CB"} Passo ${J.order}: ${J.action} \u2192 ${J.target}`}),Q=$.assumptions.length>0?$.assumptions.map((J)=>` - ${J}`).join(`
|
|
330
|
+
`):" (nenhuma)",Y=$.risks.length>0?$.risks.map((J)=>` - ${J}`).join(`
|
|
331
|
+
`):" (nenhum identificado)";return[`**Objetivo:** ${$.objective}`,"",`**Complexidade:** ${$.complexity}`,"","**Estrat\xE9gia T\xE9cnica:**",...Z,"","**Premissas/Riscos:**",Q,Y,"","**Bloqueio:** Posso prosseguir com este plano ou deseja ajustar algum detalhe?"].join(`
|
|
332
|
+
`)}function $Y($){let Z=$.strategy.filter((J)=>J.status==="completed").length,Q=$.strategy.length,Y=$.strategy.find((J)=>J.status==="in_progress"||J.status==="pending");return[`Plano: ${$.objective}`,`Status: ${$.status}`,`Progresso: ${Z}/${Q} passos`,Y?`Pr\xF3ximo: ${Y.action}`:""].filter(Boolean).join(`
|
|
333
|
+
`)}function ZY($){let Z={planId:$.id,objective:$.objective,status:$.status,complexity:$.complexity,stepsCompleted:$.strategy.filter((Q)=>Q.status==="completed").length,totalSteps:$.strategy.length,createdAt:$.createdAt,completedAt:$.completedAt};XZ=[...XZ,Z],lG()}function lG(){if(!nQ)return;S(pG(),JSON.stringify(XZ,null,2))}function oQ(){return fG("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function QY(){return`
|
|
288
334
|
## Protocolo de Alta Ag\xEAncia
|
|
289
335
|
|
|
290
336
|
Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
|
|
@@ -326,73 +372,73 @@ Ao usar \`propose_plan\`, estruture assim:
|
|
|
326
372
|
- **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
|
|
327
373
|
- **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
|
|
328
374
|
- **Bloqueio**: Sempre termine com "Posso prosseguir com este plano?"
|
|
329
|
-
`.trim()}var R8=new c5,I3=[];function x3($){I3=$}var c=[{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"]}}],S3=[{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:[]}}],tV=[{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:[]}}],eV=[{name:"add_person",description:"Register a person (team member, family, or contact). Groups: equipe (work team), familia (family/home), contato (other contacts).",input_schema:{type:"object",properties:{name:{type:"string",description:"Person name"},group:{type:"string",enum:["equipe","familia","contato"],description:"Group: equipe, familia, or contato"},role:{type:"string",description:'Role or relationship (e.g. "dev frontend", "esposa", "fornecedor"). Optional.'},contact:{type:"string",description:"Phone, email, or other contact info. Optional."}},required:["name","group"]}},{name:"find_person_info",description:"Look up a person by name or ID. Returns their profile, recent interactions, and pending delegated tasks.",input_schema:{type:"object",properties:{name_or_id:{type:"string",description:"Person name (partial match) or ID"}},required:["name_or_id"]}},{name:"list_people",description:"List all registered people, optionally filtered by group.",input_schema:{type:"object",properties:{group:{type:"string",enum:["equipe","familia","contato"],description:"Filter by group. Optional."}},required:[]}},{name:"log_interaction",description:"Log an interaction with a person. Types: conversa, email, reuniao, ligacao, mensagem, delegacao, entrega, outro. Optionally set a follow-up date for a reminder.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},type:{type:"string",enum:["conversa","email","reuniao","ligacao","mensagem","delegacao","entrega","outro"],description:"Interaction type"},summary:{type:"string",description:"What was discussed or happened"},follow_up:{type:"string",description:'When to follow up (e.g. "em 3 dias", "amanha", "25/03"). Optional.'}},required:["person","type","summary"]}},{name:"delegate_to_person",description:"Delegate/assign a task to a person with optional due date. Use to track what you asked someone to do.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},task:{type:"string",description:"What they need to do"},due_date:{type:"string",description:'Due date (e.g. "sexta", "em 3 dias", "28/03"). Optional.'}},required:["person","task"]}},{name:"update_delegation_status",description:"Update the status of a delegated task. Statuses: pendente, em_andamento, concluido.",input_schema:{type:"object",properties:{delegation_id:{type:"string",description:"Delegation ID"},status:{type:"string",enum:["pendente","em_andamento","concluido"],description:"New status"},notes:{type:"string",description:"Optional notes about the update"}},required:["delegation_id","status"]}},{name:"get_people_dashboard",description:"Show the people management dashboard: summary of team/family/contacts, overdue follow-ups, overdue delegations, and recent interactions.",input_schema:{type:"object",properties:{},required:[]}}],$G=[{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"]}}],ZG={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"]}},JG=[{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"]}}],YG=[{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:[]}}],QG=[{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"]}}],XG=[{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:[]}}],KG=[{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"]}}],zG=[{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"]}}],VG=[{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"]}}],GG=[{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"]}}],HG=[{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:[]}}],qG=[{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"]}}],WG=[{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:[]}}],UG=[{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:[]}}],BG=[{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:[]}}],NG=[{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"]}}],MG=S3.find(($)=>$.name==="get_news"),E3=!1,Z4=null;function w3($){Z4=$}function k3(){if(E3)return;if(E3=!0,I)c.push(...S3),c.push(...HG);else c.push(MG);c.push(...tV),c.push(...eV),c.push(...$G),c.push(ZG),c.push(...JG),c.push(...YG),c.push(...QG),c.push(...WG),c.push(...qG),c.push(...XG),c.push(...KG),c.push(...zG),c.push(...VG),c.push(...UG),c.push(...GG),c.push(...BG),c.push(...NG)}var f7=50000;async function c9($,Z){let J=performance.now();try{let Y=await CG($,Z);return setImmediate(()=>{_9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!Y.startsWith("Error:")})}),Y}catch(Y){return setImmediate(()=>{_9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function CG($,Z){switch($){case"read_file":return jG(Z);case"write_file":return OG(Z);case"edit_file":return FG(Z);case"search_files":return await RG(Z);case"find_files":return await DG(Z);case"list_directory":return TG(Z);case"run_command":return await PG(Z);case"fetch_url":return await AG(Z);case"open_application":return await b4(Z.name,Z.argument);case"open_file_default":return await F1(Z.path);case"open_url_browser":return await y4(Z.url);case"get_running_apps":return await R1();case"get_system_info":return await _4();case"get_calendar_events":return await b$();case"get_news":{let J=Z.category;return await B4(J?[J]:void 0)}case"create_task":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.time,Q=Y?L1(Y):void 0,X=d0(J,Q||void 0),K=Q?` \u2014 lembrete: ${Q.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${X.title}"${K} [${X.id}]`}case"complete_task":{let J=Z.reference;if(!J?.trim())return"Error: reference is required.";let Y=l0(J);return Y?`Concluida: "${Y.title}"`:`Tarefa nao encontrada: "${J}"`}case"list_tasks":{let J=Z.show_done||!1,Y=l$(J);return h4(Y)}case"add_person":{let J=Z.name;if(!J?.trim())return"Error: name is required.";let Y=Z.group;if(!["equipe","familia","contato"].includes(Y))return"Error: group must be equipe, familia, or contato.";let X=Z7(J,Y,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${Y}) [${X.id}]`}case"find_person_info":{let J=Z.name_or_id;if(!J?.trim())return"Error: name_or_id is required.";let Y=o$(J);if(!Y)return`Pessoa nao encontrada: "${J}"`;return X7(Y)}case"list_people":{let J=Z.group,Y=J7(J);return Q7(Y)}case"log_interaction":{let J=Z.person;if(!J?.trim())return"Error: person is required.";let{type:Y,summary:Q}=Z;if(!Q?.trim())return"Error: summary is required.";let X=Z.follow_up,K=X?T3(X):void 0;if(!g6(J,Y,Q,K||void 0))return`Pessoa nao encontrada: "${J}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${Y} com ${J}${G}`}case"delegate_to_person":{let J=Z.person;if(!J?.trim())return"Error: person is required.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=Z.due_date,X=Q?T3(Q):void 0,K=Y7(J,Y,X||void 0);if(!K)return`Pessoa nao encontrada: "${J}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${J}: "${Y}"${V} [${K.id}]`}case"update_delegation_status":{let J=Z.delegation_id;if(!J?.trim())return"Error: delegation_id is required.";let Y=Z.status,Q=m6(J,Y,Z.notes);if(!Q)return`Delegacao nao encontrada: "${J}"`;return`Delegacao atualizada: "${Q.task}" -> ${Y}`}case"get_people_dashboard":return V7();case"save_memo":{let J=Z.content;if(!J?.trim())return"Error: content is required.";let Y=Z.tags||[],Q=o0(J,Y);return`Memo salvo${Q.tags.length>0?` [${Q.tags.map((K)=>"#"+K).join(" ")}]`:""} {${Q.id}}`}case"search_memos":{let J=Z.query;if(!J?.trim())return g4(D1());let Y=a0(J);return g4(Y)}case"record_transaction":{let{type:J,amount:Y,category:Q,description:X}=Z;if(!J||!Y||!Q||!X)return"Error: all fields required.";let K=T1(J,Y,Q,X);return`${K.type==="entrada"?"+":"-"} R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description} [${K.id}]`}case"financial_summary":return n0();case"log_decision":{let{title:J,context:Y,chosen:Q}=Z;if(!J||!Y||!Q)return"Error: title, context, and chosen are required.";let X=I6(J,Y,Q,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let J=Z.query;if(!J?.trim())return H8(s0());return H8(m4(J))}case"open_investigation":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.type;if(!["bug","feature","test","audit","incident"].includes(Y))return"Error: type must be bug, feature, test, audit, or incident.";let X=$9(J,Y,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${X.title}" (${X.type}) {${X.id}}`}case"collect_evidence":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let{source:Y,label:Q,content:X}=Z;if(!Q?.trim()||!X?.trim())return"Error: label and content are required.";let K=Z9(J,Y,Q,X,Z.path);if(!K)return`Investigacao nao encontrada: "${J}"`;return`Evidencia coletada: [${K.id}] ${K.source}: ${K.label}`}case"add_finding":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let{severity:Y,title:Q,description:X}=Z;if(!Q?.trim()||!X?.trim())return"Error: title and description are required.";let K=Z.evidence_ids||[],V=J9(J,Y,Q,X,K);if(!V)return`Investigacao nao encontrada: "${J}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=Z.summary;if(!Y?.trim())return"Error: summary is required.";let Q=Y9(J,Y,Z.recommendations);if(!Q)return`Investigacao nao encontrada: "${J}"`;return`Investigacao concluida: "${Q.title}" \u2014 ${Q.evidence.length} evidencias, ${Q.findings.length} conclusoes`}case"investigation_status":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=Q9(J);if(!Y)return`Investigacao nao encontrada: "${J}"`;return V9(Y)}case"investigation_report":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=z9(J);if(!Y)return`Investigacao nao encontrada: "${J}"`;return Y}case"list_investigations":{let J=Z.query;if(J?.trim())return e0(K9(J));let{status:Y,type:Q}=Z;return e0(X9(Y,Q))}case"draft_email":{let{to:J,subject:Y,body:Q}=Z;if(!J?.trim()||!Y?.trim()||!Q?.trim())return"Error: to, subject, and body are required.";let X={to:J,subject:Y,body:Q,cc:Z.cc},K=i0(X),V=await r0(X);return`${K}
|
|
375
|
+
`.trim()}var x8=new z9,GY=[];function HY($){GY=$}var p=[{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"]}}],qY=[{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:[]}}],rG=[{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:[]}}],iG=[{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"]}}],sG=[{name:"add_person",description:"Register a person (team member, family, or contact). Groups: equipe (work team), familia (family/home), contato (other contacts).",input_schema:{type:"object",properties:{name:{type:"string",description:"Person name"},group:{type:"string",enum:["equipe","familia","contato"],description:"Group: equipe, familia, or contato"},role:{type:"string",description:'Role or relationship (e.g. "dev frontend", "esposa", "fornecedor"). Optional.'},contact:{type:"string",description:"Phone, email, or other contact info. Optional."}},required:["name","group"]}},{name:"find_person_info",description:"Look up a person by name or ID. Returns their profile, recent interactions, and pending delegated tasks.",input_schema:{type:"object",properties:{name_or_id:{type:"string",description:"Person name (partial match) or ID"}},required:["name_or_id"]}},{name:"list_people",description:"List all registered people, optionally filtered by group.",input_schema:{type:"object",properties:{group:{type:"string",enum:["equipe","familia","contato"],description:"Filter by group. Optional."}},required:[]}},{name:"log_interaction",description:"Log an interaction with a person. Types: conversa, email, reuniao, ligacao, mensagem, delegacao, entrega, outro. Optionally set a follow-up date for a reminder.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},type:{type:"string",enum:["conversa","email","reuniao","ligacao","mensagem","delegacao","entrega","outro"],description:"Interaction type"},summary:{type:"string",description:"What was discussed or happened"},follow_up:{type:"string",description:'When to follow up (e.g. "em 3 dias", "amanha", "25/03"). Optional.'}},required:["person","type","summary"]}},{name:"delegate_to_person",description:"Delegate/assign a task to a person with optional due date. Use to track what you asked someone to do.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},task:{type:"string",description:"What they need to do"},due_date:{type:"string",description:'Due date (e.g. "sexta", "em 3 dias", "28/03"). Optional.'}},required:["person","task"]}},{name:"update_delegation_status",description:"Update the status of a delegated task. Statuses: pendente, em_andamento, concluido.",input_schema:{type:"object",properties:{delegation_id:{type:"string",description:"Delegation ID"},status:{type:"string",enum:["pendente","em_andamento","concluido"],description:"New status"},notes:{type:"string",description:"Optional notes about the update"}},required:["delegation_id","status"]}},{name:"get_people_dashboard",description:"Show the people management dashboard: summary of team/family/contacts, overdue follow-ups, overdue delegations, and recent interactions.",input_schema:{type:"object",properties:{},required:[]}}],tG=[{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"]}}],eG={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"]}},$H=[{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"]}}],ZH=[{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:[]}}],QH=[{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"]}}],YH=[{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:[]}}],JH=[{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"]}}],XH=[{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"]}}],KH=[{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"]}}],zH=[{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"]}}],VH=[{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:[]}}],GH=[{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"]}}],HH=[{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"]}}],qH=[{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:[]}}],UH=[{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:[]}}],WH=[{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:[]}}],BH=[{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"]}}],CH=qY.find(($)=>$.name==="get_news"),YY=!1,G4=null;function UY($){G4=$}function WY(){if(YY)return;if(YY=!0,A)p.push(...qY),p.push(...VH),p.push(...GH);else p.push(CH);p.push(...rG),p.push(...iG),p.push(...sG),p.push(...tG),p.push(eG),p.push(...$H),p.push(...ZH),p.push(...QH),p.push(...qH),p.push(...HH),p.push(...YH),p.push(...JH),p.push(...XH),p.push(...KH),p.push(...UH),p.push(...zH),p.push(...WH),p.push(...BH)}var Y5=50000;async function HZ($,Z){let Q=performance.now();try{let Y=await NH($,Z);return setImmediate(()=>{JZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-Q),success:!Y.startsWith("Error:")})}),Y}catch(Y){return setImmediate(()=>{JZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-Q),success:!1})}),`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function NH($,Z){switch($){case"read_file":return MH(Z);case"write_file":return FH(Z);case"edit_file":return OH(Z);case"search_files":return await RH(Z);case"find_files":return await jH(Z);case"list_directory":return DH(Z);case"run_command":return await PH(Z);case"fetch_url":return await TH(Z);case"open_application":return await m4(Z.name,Z.argument);case"open_file_default":return await A1(Z.path);case"open_url_browser":return await p4(Z.url);case"get_running_apps":return await I1();case"get_system_info":return await c4();case"get_calendar_events":return await h$();case"get_news":{let Q=Z.category;return await E4(Q?[Q]:void 0)}case"create_task":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.time,J=Y?k1(Y):void 0,X=$7(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 Y=Z7(Q);return Y?`Concluida: "${Y.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,Y=e$(Q);return l4(Y)}case"schedule_job":{let{name:Q,time:Y,message:J}=Z;if(!Q?.trim()||!Y?.trim()||!J?.trim())return"Error: name, time, and message are required.";let X=B7(Y);if(!X)return`Error: invalid time format "${Y}". 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=N7(H)??void 0;else V=C7(H)??void 0}if(K==="once"&&!V){let H=new Date,[z,B]=X.split(":").map(Number),W=new Date(H);if(W.setHours(z,B,0,0),W<=H)W.setDate(W.getDate()+1);V=[String(W.getMonth()+1).padStart(2,"0"),String(W.getDate()).padStart(2,"0"),String(W.getFullYear())].join("/")}let G=await G7(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 H7(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,Y=b1(Q);return _1(Y)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let Y=await q7(Q);return Y?`Agendamento "${Y.name}" ativado.`:`Agendamento nao encontrado: "${Q}"`}case"disable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let Y=await U7(Q);return Y?`Agendamento "${Y.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 W7(Q)}case"add_person":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let Y=Z.group;if(!["equipe","familia","contato"].includes(Y))return"Error: group must be equipe, familia, or contato.";let X=j7(Q,Y,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${Y}) [${X.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let Y=$4(Q);if(!Y)return`Pessoa nao encontrada: "${Q}"`;return A7(Y)}case"list_people":{let Q=Z.group,Y=D7(Q);return T7(Y)}case"log_interaction":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let{type:Y,summary:J}=Z;if(!J?.trim())return"Error: summary is required.";let X=Z.follow_up,K=X?KY(X):void 0;if(!F3(Q,Y,J,K||void 0))return`Pessoa nao encontrada: "${Q}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${Y} com ${Q}${G}`}case"delegate_to_person":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let J=Z.due_date,X=J?KY(J):void 0,K=P7(Q,Y,X||void 0);if(!K)return`Pessoa nao encontrada: "${Q}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${Y}"${V} [${K.id}]`}case"update_delegation_status":{let Q=Z.delegation_id;if(!Q?.trim())return"Error: delegation_id is required.";let Y=Z.status,J=O3(Q,Y,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${Y}`}case"get_people_dashboard":return E3();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let Y=Z.tags||[],J=Q7(Q,Y);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 o4(y1());let Y=Y7(Q);return o4(Y)}case"record_transaction":{let{type:Q,amount:Y,category:J,description:X}=Z;if(!Q||!Y||!J||!X)return"Error: all fields required.";let K=v1(Q,Y,J,X);return`${K.type==="entrada"?"+":"-"} R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description} [${K.id}]`}case"financial_summary":return F7();case"log_decision":{let{title:Q,context:Y,chosen:J}=Z;if(!Q||!Y||!J)return"Error: title, context, and chosen are required.";let X=z3(Q,Y,J,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let Q=Z.query;if(!Q?.trim())return F8(O7());return F8(a4(Q))}case"open_investigation":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.type;if(!["bug","feature","test","audit","incident"].includes(Y))return"Error: type must be bug, feature, test, audit, or incident.";let X=j9(Q,Y,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:Y,label:J,content:X}=Z;if(!J?.trim()||!X?.trim())return"Error: label and content are required.";let K=D9(Q,Y,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:Y,title:J,description:X}=Z;if(!J?.trim()||!X?.trim())return"Error: title and description are required.";let K=Z.evidence_ids||[],V=P9(Q,Y,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 Y=Z.summary;if(!Y?.trim())return"Error: summary is required.";let J=T9(Q,Y,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 Y=A9(Q);if(!Y)return`Investigacao nao encontrada: "${Q}"`;return w9(Y)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let Y=S9(Q);if(!Y)return`Investigacao nao encontrada: "${Q}"`;return Y}case"list_investigations":{let Q=Z.query;if(Q?.trim())return E7(x9(Q));let{status:Y,type:J}=Z;return E7(I9(Y,J))}case"draft_email":{let{to:Q,subject:Y,body:J}=Z;if(!Q?.trim()||!Y?.trim()||!J?.trim())return"Error: to, subject, and body are required.";let X={to:Q,subject:Y,body:J,cc:Z.cc},K=X7(X),V=await J7(X);return`${K}
|
|
330
376
|
|
|
331
|
-
${V}`}case"save_material":{let
|
|
332
|
-
Esse tipo de operacao nao e permitido.`;if(!Y.safe&&Y.reason);let
|
|
333
|
-
${
|
|
334
|
-
${
|
|
377
|
+
${V}`}case"save_material":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let J=Z.category||"geral",X=Z.tags||[],K=S7(Q,Y,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 D4(E8());let Y=R8(Q);return D4(Y)}case"list_materials":{let Q=Z.category,Y=Z.limit||30,J=E8(Y,Q);return D4(J)}case"update_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let Y={};if(Z.title)Y.title=Z.title;if(Z.content)Y.content=Z.content;if(Z.category)Y.category=Z.category;if(Z.tags)Y.tags=Z.tags;let J=T3(Q,Y);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 w7(Q)?"Material removido.":`Material nao encontrado: "${Q}"`}case"execute_powershell_script":{let Q=Z.script;if(!Q?.trim())return"Error: script is required.";let Y=m9(Q);if(Y.blocked)return`BLOCKED: ${Y.reason}
|
|
378
|
+
Esse tipo de operacao nao e permitido.`;if(!Y.safe&&Y.reason);let J=await m1(Q),X=[];if(J.stdout.trim())X.push(`stdout:
|
|
379
|
+
${J.stdout.trim()}`);if(J.stderr.trim())X.push(`stderr:
|
|
380
|
+
${J.stderr.trim()}`);return X.push(`exit: ${J.exitCode} (${J.duration}ms)`),X.join(`
|
|
335
381
|
|
|
336
|
-
`)}case"analyze_screen_context":return await
|
|
337
|
-
${
|
|
338
|
-
Chunks: ${
|
|
339
|
-
Fontes: ${
|
|
340
|
-
Ultima indexacao: ${Y}`}case"vault_status":{if(!
|
|
382
|
+
`)}case"analyze_screen_context":return await m7();case"read_clipboard_content":{let Q=await g7();switch(Q.type){case"text":return`Clipboard (texto):
|
|
383
|
+
${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:Y}=Z,J=await f3(Q,Y);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 t0();case"add":{let{name:Y,url:J,category:X}=Z;if(!Y?.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=n0(Y,J,X);if(typeof K==="string")return K;return`Fonte adicionada: ${K.name} (${K.category}) \u2014 ${K.url}`}case"remove":{let Y=Z.name;if(!Y?.trim())return"Error: name or URL is required.";return r0(Y)?`Fonte removida: ${Y}`:`Fonte custom nao encontrada: "${Y}"`}case"disable":{let Y=Z.name;if(!Y?.trim())return"Error: name or URL is required.";return i0(Y)?`Fonte desativada: ${Y}`:`Fonte built-in nao encontrada ou ja desativada: "${Y}"`}case"enable":{let Y=Z.name;if(!Y?.trim())return"Error: name or URL is required.";return s0(Y)?`Fonte reativada: ${Y}`:`Fonte nao encontrada ou nao esta desativada: "${Y}"`}default:return"Error: action must be add, remove, disable, enable, or list."}case"recall_memory":{if(!b7())return"Error: memory not initialized. Run /indexar first.";let Q=Z.query;if(!Q?.trim())return"Error: query is required.";let Y=Math.min(Math.max(Z.top_k||3,1),10),J=f7(Q,Y);return h7(J)}case"index_memory":{if(!b7())return"Error: memory not initialized.";let Q=v7();return`Indexacao concluida: ${Q.indexed} fonte(s) indexada(s), ${Q.skipped} sem alteracao. Total: ${Q.total} chunks.`}case"memory_status":{if(!b7())return"Memory: nao inicializada.";let Q=_7(),Y=Q.builtAt?new Date(Q.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
|
|
384
|
+
Chunks: ${Q.chunks}
|
|
385
|
+
Fontes: ${Q.sources}
|
|
386
|
+
Ultima indexacao: ${Y}`}case"vault_status":{if(!v8())return"Vault nao inicializado.";return W0(U0())}case"vault_backup":{if(!v8())return"Vault nao inicializado.";let Q=Z.message||void 0;return await Y8(Q)}case"sync_cloud_context":{if(!v8())return"Vault nao inicializado.";return await C0()}case"vault_init_backup":{if(!v8())return"Vault nao inicializado.";return await B0()}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=t7(process.cwd());if(!J)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return P8(J.id),`Projeto ativo: "${J.name}" (${J.path}) \u2014 auto-detectado [${J.id}]`}let Y=P8(Q);if(!Y)return`Projeto nao encontrado: "${Q}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${Y.name}" (${Y.path}) [${Y.id}]`}case"report_work_progress":{let Q=Z.project||"",Y=Z.period||"today",J=Z.lang||"pt",X=Z.save_to_file,K=Q;if(!K){let G=T4();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=G.id}let V=await a7(K,Y,J);if(!V)return`Projeto nao encontrado: "${K}"`;if(X)return aG(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
|
|
341
387
|
|
|
342
|
-
${V.markdown}`;return V.markdown}case"manage_work_session":{let
|
|
388
|
+
${V.markdown}`;return V.markdown}case"manage_work_session":{let Q=Z.action,Y=Z.notes||"",J=T4();if(!J)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let X=d7(J.id,Y);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=A4(J.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=l7(X.id,Y);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${J.name}".`}case"status":{let X=A4(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 Y=Z.path;if(!Y?.trim())return"Error: path is required.";let J=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],V=u9(Q,Y,J,K,X);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let Q=Z.active_only||!1;return n7(D8(Q))}case"fetch_opportunities":{let{status:Q,tech:Y}=Z,J=o7(Q,Y);return i7(J)}case"add_opportunity":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.description;if(!Y?.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=d3(Q,Y,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 Y=Z.status,J=l3(Q,Y);if(!J)return`Oportunidade nao encontrada: "${Q}"`;return`Oportunidade atualizada: "${J.title}" -> ${Y}`}case"pitwall_benchmark":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let Y=Z.key,J=Math.min(Math.max(Z.iterations||1,1),10),X=Z.warmup||!1,K=Z.cwd,V=await n9(Q,{scriptKey:Y,cwd:K,iterations:J,warmup:X});if(V.exitCode!==0){let G=i9(V);return`AVISO: Comando terminou com exit code ${V.exitCode}. Metricas podem nao ser confiaveis.
|
|
343
389
|
|
|
344
|
-
${G.markdown}`}return
|
|
345
|
-
`+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let H=K?
|
|
390
|
+
${G.markdown}`}return i9(V).markdown}case"pitwall_save_baseline":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let Y=Z.key,J=Math.min(Math.max(Z.iterations||3,1),10),X=Z.tags||[],K=Z.reset||!1,V=Z.cwd,G=await n9(Q,{scriptKey:Y,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.
|
|
391
|
+
`+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let H=K?ZQ(G,X):e3(G,X),z=H.metrics.durationNs/1e6;return`Baseline salvo: "${H.scriptKey}" (${H.runs} run${H.runs>1?"s":""})
|
|
346
392
|
Duracao: ${z.toFixed(2)}ms
|
|
347
393
|
Memoria: ${(H.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
|
|
348
|
-
CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return
|
|
394
|
+
CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return YQ($Q());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return r9(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 Y=b$(Z.project_dir||process.cwd()),J=b$(Y,Q);if(!J.startsWith(Y+A8))return"Error: file must be inside project_dir.";try{let X=t9(Y),K=e9(X,J);return GQ(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 Y=b$(Z.project_dir||process.cwd()),J=b$(Y,Q);if(!J.startsWith(Y+A8))return"Error: file must be inside project_dir.";try{let X=t9(Y),K=VQ(X,J);return qQ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"archive_session":{if(!G4)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";if(Q==="all"){let Y=G4.archiveAll();return Y.length>0?`Arquivadas ${Y.length} sessoes: ${Y.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return G4.archive(Q)?`Sessao arquivada: "${Q}"`:`Falha ao arquivar "${Q}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!G4)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";return G4.unarchive(Q)?`Sessao restaurada: "${Q}"`:`Sessao arquivada nao encontrada: "${Q}"`}case"list_archived_sessions":{if(!G4)return"Error: session manager not initialized.";let Q=G4.listArchived();if(Q.length===0)return"Nenhuma sessao arquivada.";let Y=Q.map((J)=>{let X=G4.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}):
|
|
349
395
|
${Y.join(`
|
|
350
|
-
`)}`}case"evaluate_architecture_tradeoffs":{let
|
|
396
|
+
`)}`}case"evaluate_architecture_tradeoffs":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.background;if(!Y?.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:Y.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},K=J.map((z)=>({name:z.name.trim(),description:z.description.trim(),scores:z.scores,pros:z.pros||[],cons:z.cons||[]})),V=Z.custom_criteria,G=V&&V.length>0?V:ZZ;return FQ(X,K,G).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let Y=Z.stacktrace;return OQ(Q,Y).summary}case"log_incident":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.description;if(!Y?.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=RQ(Q,Y,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
|
|
351
397
|
Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
|
|
352
|
-
Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let
|
|
353
|
-
Arquivo: ${K.path}`}case"explain_optimal_usage":{let
|
|
398
|
+
Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,Y=Z.query,J=Y?DQ(Y).slice(0,Q):jQ(Q);return TQ(J)}case"list_incidents":{let Q=Z.limit||10,Y=Z.query,J=Y?EQ(Y).slice(0,Q):LQ(Q);return AQ(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let Y=PQ(Q);if(!Y)return`Trade-off nao encontrado: "${Q}"`;return Y.adr}case"update_living_manual":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let J=Z.category||"best_practice",X=Z.tags||[],K=await hQ(Q,Y,J,X);if(!K.success)return"Falha ao atualizar o manual. Verifique se o docs-engine foi inicializado.";return`Manual atualizado: "${Q}" (${J})
|
|
399
|
+
Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return gQ(Q)}case"trigger_self_reflection":{let Q=await d1();return cQ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),Y=fQ(Q);return uQ(Y)}case"propose_plan":{if(!V4())return"Error: Agency engine not initialized. Planning features unavailable.";let Q=Z.objective;if(!Q?.trim())return"Error: objective is required.";let Y=Z.steps;if(!Y?.length)return"Error: at least one step is required.";let J=Y.map((G)=>({action:G.action,target:G.target,description:G.description,estimatedImpact:G.estimatedImpact||"low",dependencies:G.dependencies||[]})),X=rQ(Q,J,{assumptions:Z.assumptions,risks:Z.risks}),K=await iQ();if(!K.success)return`Error creating plan: ${K.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
|
|
354
400
|
|
|
355
|
-
${
|
|
401
|
+
${zZ(X)}`}case"check_plan_status":{if(!V4())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Q=sQ(),Y=o1();if(!Y)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${$Y(Y)}
|
|
356
402
|
|
|
357
|
-
Execu\xE7\xE3o: ${
|
|
358
|
-
Motivo: ${
|
|
359
|
-
`)}case"complete_plan_step":{if(
|
|
403
|
+
Execu\xE7\xE3o: ${Q.allowed?"PERMITIDA":"BLOQUEADA"}
|
|
404
|
+
Motivo: ${Q.reason}`}case"report_plan_deviation":{if(!V4())return"Error: Agency engine not initialized.";let{obstacle:Q,impact:Y,alternative:J}=Z;if(!Q?.trim())return"Error: obstacle is required.";if(!Y?.trim())return"Error: impact is required.";if(!J?.trim())return"Error: alternative is required.";let X=o1();if(!X)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let K=Z.step_id,V=K?X.strategy.find((G)=>G.id===K):X.strategy.find((G)=>G.status==="in_progress"||G.status==="pending");if(V)eQ(V.id,Q,J);return["**Desvio Detectado**","",`**Obst\xE1culo:** ${Q}`,`**Impacto no Plano:** ${Y}`,"","**Alternativa Proposta:**",J,"","**Status:** Execu\xE7\xE3o BLOQUEADA. Aguardando aprova\xE7\xE3o da alternativa.","","**Bloqueio:** Posso prosseguir com esta alternativa?"].join(`
|
|
405
|
+
`)}case"complete_plan_step":{if(!V4())return"Error: Agency engine not initialized.";let Q=Z.step_id;if(!Q?.trim())return"Error: step_id is required.";let Y=tQ(Q,Z.result);if(!Y.success)return`Error: ${Y.message}`;let J=o1(),X=J?`Progresso: ${J.strategy.filter((V)=>V.status==="completed").length}/${J.strategy.length}`:"",K=Y.nextStep?`
|
|
360
406
|
Pr\xF3ximo passo: ${Y.nextStep.action} \u2192 ${Y.nextStep.target}`:`
|
|
361
407
|
Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Y.message}
|
|
362
|
-
${X}${K}`}case"get_current_plan":{if(
|
|
363
|
-
`)}default:{let
|
|
364
|
-
`),V=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),
|
|
365
|
-
`),
|
|
366
|
-
... (${
|
|
367
|
-
`).length;return`${X?"Updated":"Created"}: ${
|
|
408
|
+
${X}${K}`}case"get_current_plan":{if(!V4())return"Agency engine not initialized. No planning features available.";let Q=o1();if(!Q)return"Nenhum plano ativo no momento.";return zZ(Q)}case"analyze_task_complexity":{if(!V4())return"Agency engine not initialized. Cannot analyze complexity.";let Q=Z.task;if(!Q?.trim())return"Error: task is required.";let Y=KZ(Q,{files:Z.files,modules:Z.modules}),J=["**An\xE1lise de Complexidade**","",`**Tarefa:** ${Q}`,`**Classifica\xE7\xE3o:** ${Y.complexity}`,`**Requer Aprova\xE7\xE3o:** ${Y.requiresApproval?"SIM":"N\xC3O"}`,"",`**Motivo:** ${Y.reason}`];if(Y.risks.length>0){J.push("","**Riscos Identificados:**");for(let X of Y.risks)J.push(` - ${X}`)}if(Y.assumptions.length>0){J.push("","**Premissas:**");for(let X of Y.assumptions)J.push(` - ${X}`)}if(Y.requiresApproval)J.push("","**Recomenda\xE7\xE3o:** Use `propose_plan` antes de executar esta tarefa.");return J.join(`
|
|
409
|
+
`)}default:{let Q=GY.find((Y)=>Y.name===$);if(Q)return await M6(Q,Z);return`Error: unknown tool "${$}"`}}}var JY=10485760;function S8($){let Z=b$($),Q=process.cwd();if(Z!==Q&&!Z.startsWith(Q+A8))return`Error: path outside working directory is not permitted: ${Z}`;try{if(a1(Z)){let Y=nG(Z);if(Y!==Q&&!Y.startsWith(Q+A8))return`Error: symlink target is outside working directory: ${Y}`}}catch{}return null}function w8($,Z){let Q=$[Z];if(typeof Q!=="string"||Q.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function MH($){let Z=w8($,"path");if(Z)return Z;let Q=b$($.path),Y=S8(Q);if(Y)return Y;if(!a1(Q))return`Error: file not found: ${Q}`;let J=zY(Q).size;if(J>JY)return`Error: file too large (${VZ(J)}). Max is ${VZ(JY)}.`;let K=GZ(Q,"utf-8").split(`
|
|
410
|
+
`),V=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),B=K.slice(V-1,V-1+G).map((N,O)=>`${String(V+O).padStart(4)} ${N}`).join(`
|
|
411
|
+
`),W=K.length-(V-1+G);if(W>0)B+=`
|
|
412
|
+
... (${W} more lines, total ${K.length})`;return I8(B)}function FH($){let Z=w8($,"path");if(Z)return Z;let Q=b$($.path),Y=S8(Q);if(Y)return Y;let J=$.content,X=a1(Q);x8.saveState(Q),S(Q,J);let K=J.split(`
|
|
413
|
+
`).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function OH($){let Z=w8($,"path");if(Z)return Z;let Q=b$($.path),Y=S8(Q);if(Y)return Y;if(!a1(Q))return`Error: file not found: ${Q}`;let J=GZ(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.`;x8.saveState(Q);let G=J.split(X).join(K);S(Q,G);let H=X.split(`
|
|
368
414
|
`).length,z=K.split(`
|
|
369
|
-
`).length;return`Edited: ${
|
|
370
|
-
`);for(let O=0;O<
|
|
415
|
+
`).length;return`Edited: ${Q} (replaced ${H} lines with ${z} lines)`}async function RH($){let Z=w8($,"pattern");if(Z)return Z;let Q=$.pattern,Y=b$($.path||"."),J=S8(Y);if(J)return J;let X=$.include;if(await Y2())return EH(Q,Y,X);return LH(Q,Y,X)}async function EH($,Z,Q){let Y=["rg","--no-heading","--line-number","--color=never"];if(Q)Y.push("--glob",Q);for(let V of y8)Y.push("--glob",`!${V}`);Y.push("-e",$,Z);let J=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=await new Response(J.stdout).text(),K=await new Response(J.stderr).text();if(await J.exited,!X.trim()&&!K.trim())return"No matches found.";if(K.trim()&&!X.trim())return`Error: ${K.trim()}`;return IH(X,Z)}async function LH($,Z,Q){let Y;try{Y=new RegExp($)}catch(z){return`Error: invalid regex pattern: ${z instanceof Error?z.message:$}`}let J=Q||"**/*",X=new Bun.Glob(J),K=[],V=0,G=5000;for await(let z of X.scan({cwd:Z,onlyFiles:!0})){if(R5(z))continue;if(++V>G){K.push(`... (stopped after scanning ${G} files)`);break}let B=VY(Z,z);try{let N=GZ(B,"utf-8").split(`
|
|
416
|
+
`);for(let O=0;O<N.length;O++)if(Y.test(N[O])){if(K.push(`${z}:${O+1}:${N[O]}`),K.length>=100)break}}catch{}if(K.length>=100)break}if(K.length===0)return"No matches found.";let H=K.slice(0,100).join(`
|
|
371
417
|
`);if(K.length>100)H+=`
|
|
372
|
-
... (showing first 100 matches)`;return
|
|
418
|
+
... (showing first 100 matches)`;return I8(H)}async function jH($){let Z=w8($,"pattern");if(Z)return Z;let Q=$.pattern,Y=b$($.path||"."),J=S8(Y);if(J)return J;let X=new Bun.Glob(Q),K=[];for await(let G of X.scan({cwd:Y,onlyFiles:!0})){if(R5(G))continue;if(K.push(G),K.length>=200)break}if(K.length===0)return"No files found.";let V=K.join(`
|
|
373
419
|
`);if(K.length>=200)V+=`
|
|
374
|
-
... (showing first 200 files)`;return V}function
|
|
375
|
-
`)}async function
|
|
420
|
+
... (showing first 200 files)`;return V}function DH($){let Z=b$($.path||"."),Q=S8(Z);if(Q)return Q;if(!a1(Z))return`Error: not found: ${Z}`;return oG(Z,{withFileTypes:!0}).sort((X,K)=>{if(X.isDirectory()!==K.isDirectory())return X.isDirectory()?-1:1;return X.name.localeCompare(K.name)}).map((X)=>{if(X.isDirectory())return`d ${X.name}/`;try{let K=zY(VY(Z,X.name)),V=VZ(K.size);return`f ${X.name} ${V}`}catch{return`f ${X.name}`}}).join(`
|
|
421
|
+
`)}async function PH($){let Z=w8($,"command");if(Z)return Z;let Q=$.command,Y=Math.min(120,Math.max(5,$.timeout||30)),J=Q8(),X=Bun.spawn([...J,Q],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),K=setTimeout(()=>X.kill(),Y*1000),[V,G]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),H=await X.exited;clearTimeout(K);let z="";if(V.trim())z+=V.trim();if(G.trim())z+=(z?`
|
|
376
422
|
`:"")+`STDERR:
|
|
377
423
|
`+G.trim();if(H!==0)z+=(z?`
|
|
378
|
-
`:"")+`Exit code: ${H}`;return
|
|
379
|
-
(Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,z=G.headers.get("content-type")||"";if(
|
|
424
|
+
`:"")+`Exit code: ${H}`;return I8(z||"(no output)")}async function TH($){let Z=$.url,Q=$.method||"GET",Y=$.headers||{},J=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let X=XY(Z);if(X)return X;try{let K=new AbortController,V=setTimeout(()=>K.abort(),30000),G=await fetch(Z,{method:Q,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Y},body:J&&Q!=="GET"&&Q!=="HEAD"?J:void 0,signal:K.signal});if(clearTimeout(V),G.status>=300&&G.status<400){let N=G.headers.get("location");if(!N)return`Status: ${G.status} (redirect with no location header)`;let O=XY(N);if(O)return`Redirect blocked: ${O}`;return`Status: ${G.status} -> Redirect to: ${N}
|
|
425
|
+
(Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,z=G.headers.get("content-type")||"";if(Q==="HEAD"){let N=[...G.headers.entries()].map(([O,j])=>`${O}: ${j}`).join(`
|
|
380
426
|
`);return`Status: ${H}
|
|
381
|
-
${
|
|
427
|
+
${N}`}let B=G.headers.get("content-length");if(B&&Number(B)>Y5*2)return`Status: ${H}
|
|
382
428
|
|
|
383
|
-
Error: response body too large (${
|
|
429
|
+
Error: response body too large (${B} bytes). Max is ${Y5*2} bytes.`;let W=await G.text();if(z.includes("text/html")){let N=AH(W);return I8(`Status: ${H}
|
|
384
430
|
|
|
385
|
-
${
|
|
431
|
+
${N}`)}return I8(`Status: ${H}
|
|
386
432
|
|
|
387
|
-
${
|
|
433
|
+
${W}`)}catch(K){if(K instanceof Error&&K.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${K instanceof Error?K.message:String(K)}`}}function XY($){try{let Z=new URL($),Q=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(Q))return"Error: requests to localhost are blocked for security.";if(Q.endsWith(".local")||Q.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(Q==="metadata.google.internal"||Q==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let J=Q.split(".").map(Number);if(J.length===4&&J.every((X)=>!isNaN(X)&&X>=0&&X<=255)){if(J[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(J[0]===172&&J[1]>=16&&J[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(J[0]===192&&J[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(J[0]===169&&J[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(J[0]===0)return"Error: requests to 0.x IPs are blocked."}if(Q.startsWith("::ffff:")||Q.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function AH($){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,`
|
|
388
434
|
`).replace(/<(br|hr)[^>]*\/?>/gi,`
|
|
389
435
|
`).replace(/<[^>]+>/g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
390
436
|
|
|
391
|
-
`).trim()}function
|
|
392
|
-
`).map((H)=>{if(H.startsWith(Y))return"."+H.slice(
|
|
437
|
+
`).trim()}function IH($,Z){let Q=process.cwd(),Y=Q+A8,J=Z+A8,K=$.trim().split(`
|
|
438
|
+
`).map((H)=>{if(H.startsWith(Y))return"."+H.slice(Q.length).replace(/\\/g,"/");if(H.startsWith(J))return"."+H.slice(Z.length).replace(/\\/g,"/");return H}),V=K.length,G=K.slice(0,100).join(`
|
|
393
439
|
`);if(V>100)G+=`
|
|
394
|
-
... (${V-100} more matches)`;return
|
|
395
|
-
... (output truncated)`}function
|
|
440
|
+
... (${V-100} more matches)`;return I8(G)}function I8($){if($.length<=Y5)return $;return $.slice(0,Y5)+`
|
|
441
|
+
... (output truncated)`}function VZ($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function KY($){let Z=$.toLowerCase().trim(),Q=new Date;if(Z==="hoje")return Q;if(Z==="amanha"||Z==="amanh\xE3"){let V=new Date(Q);return V.setDate(V.getDate()+1),V}let Y=Z.match(/em\s+(\d+)\s*dias?/);if(Y){let V=new Date(Q);return V.setDate(V.getDate()+parseInt(Y[1])),V}let J=Z.match(/em\s+(\d+)\s*semanas?/);if(J){let V=new Date(Q);return V.setDate(V.getDate()+parseInt(J[1])*7),V}let X={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[V,G]of Object.entries(X))if(Z.includes(V)){let H=new Date(Q),z=(G-H.getDay()+7)%7||7;return H.setDate(H.getDate()+z),H}let K=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(K){let V=parseInt(K[1]),G=parseInt(K[2])-1,H=K[3]?parseInt(K[3])+(K[3].length===2?2000:0):Q.getFullYear(),z=new Date(H,G,V);if(!isNaN(z.getTime()))return z}return k1(Z)}var xH=new Set([429,500,502,503,529]);async function CY($,Z={}){let Q=Z.maxRetries??3,Y=Z.baseDelayMs??1000,J;for(let X=0;X<=Q;X++)try{return await $()}catch(K){if(J=K,Z.signal?.aborted)throw K;if(X>=Q)throw K;if(SH(K)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(X+1,500,"Auth refreshed, retrying..."),await BY(500,Z.signal);continue}}if(!wH(K))throw K;let G=kH(K)??Y*Math.pow(2,X),H=K instanceof Error?K.message:String(K);Z.onRetry?.(X+1,G,H),await BY(G,Z.signal)}throw J}function SH($){if(!($ instanceof Error))return!1;return $.status===401}function wH($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&xH.has(Z))return!0;let Q=$.message.toLowerCase();if(Q.includes("econnreset")||Q.includes("econnrefused"))return!0;if(Q.includes("etimedout")||Q.includes("socket hang up"))return!0;if(Q.includes("overloaded"))return!0;return!1}function kH($){let Z=$.headers;if(!Z)return null;let Q=Z["retry-after"];if(!Q)return null;let Y=Number(Q);if(!isNaN(Y)&&Y>0)return Math.min(Y,60)*1000;return null}function BY($,Z){return new Promise((Q,Y)=>{let J=setTimeout(Q,$);Z?.addEventListener("abort",()=>{clearTimeout(J),Y(Error("Aborted"))},{once:!0})})}var yH={haiku:200000,sonnet:200000,opus:200000};function x4($){return Math.ceil($.length/3.5)}function qZ($){let Z=0;for(let Q of $){if(Z+=x4(Q.content),Q.toolCalls)for(let Y of Q.toolCalls)Z+=x4(JSON.stringify(Y.input)),Z+=x4(Y.result);Z+=10}return Z}function UZ($){let Z=$.toLowerCase();for(let[Q,Y]of Object.entries(yH))if(Z.includes(Q))return Y;return 200000}function NY($,Z,Q){let Y=UZ(Z)-20000-Q;if(qZ($)<=Y)return $;let X=[],K=Y,V=[...$].reverse(),G=[];for(let z of V){let B=x4(z.content)+(z.toolCalls?.reduce((W,N)=>W+x4(JSON.stringify(N.input))+x4(N.result),0)??0)+10;if(K-B<0)break;K-=B,G.unshift(z)}let H=$.length-G.length;if(H>0)X.push({role:"user",content:`[Note: ${H} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return X.push(...G),X}function MY($,Z,Q){let Y=UZ(Z)-20000-Q;return qZ($)>Y*0.7}function FY($,Z,Q){let Y=UZ(Z)-20000-Q;if(qZ($)<=Y*0.7)return null;let X=Math.max(4,Math.floor($.length*0.3)),K=$.slice(0,$.length-X),V=$.slice($.length-X);if(K.length<2)return null;return{toSummarize:K,toKeep:V}}function OY($){return`Summarize this conversation concisely. Focus on:
|
|
396
442
|
1. Key decisions made
|
|
397
443
|
2. Files created or modified
|
|
398
444
|
3. Important context the user shared
|
|
@@ -401,33 +447,33 @@ ${B}`)}catch(K){if(K instanceof Error&&K.name==="AbortError")return"Error: Reque
|
|
|
401
447
|
Be brief but preserve actionable information. Output ONLY the summary.
|
|
402
448
|
|
|
403
449
|
---
|
|
404
|
-
${$.map((
|
|
405
|
-
Tools used: ${
|
|
450
|
+
${$.map((Q)=>{let Y=`[${Q.role}]: ${Q.content.slice(0,500)}`;if(Q.toolCalls?.length)Y+=`
|
|
451
|
+
Tools used: ${Q.toolCalls.map((J)=>J.name).join(", ")}`;return Y}).join(`
|
|
406
452
|
|
|
407
|
-
`)}`}function
|
|
453
|
+
`)}`}function RY($,Z=2000){return $.map((Q)=>{if(!Q.toolCalls?.length)return Q;let Y=Q.toolCalls.map((J)=>{if(J.result.length<=Z)return J;let X=J.result.split(`
|
|
408
454
|
`),K=Math.min(10,X.length),V=Math.min(5,Math.max(0,X.length-K)),G=X.length-K-V,H=[...X.slice(0,K)];if(G>0)H.push(`... (${G} lines omitted)`);if(V>0)H.push(...X.slice(-V));let z=H.join(`
|
|
409
|
-
`);return{...
|
|
410
|
-
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${
|
|
455
|
+
`);return{...J,result:z}});return{...Q,toolCalls:Y}})}var bH=[/\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],_H=[/\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 EY($,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":return{level:"moderate",reason:`write ${Z.path}`};case"edit_file":return{level:"moderate",reason:`edit ${Z.path}`};case"run_command":{let Q=String(Z.command||"");for(let Y of bH)if(Y.test(Q))return{level:"dangerous",reason:Q};for(let Y of _H)if(Y.test(Q))return{level:"moderate",reason:Q};return{level:"moderate",reason:Q}}case"execute_powershell_script":return{level:"dangerous",reason:"PowerShell script execution"};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function WZ($){if(!($ instanceof Error))return String($);let{status:Z,message:Q}=$;if(Z)switch(Z){case 400:if(Q.includes("context_length")||Q.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: ${vH(Q)}`;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.
|
|
456
|
+
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${fH(Q)}" may not exist or be unavailable.
|
|
411
457
|
Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
|
|
412
|
-
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=
|
|
413
|
-
`)[0]||"",Q
|
|
414
|
-
`).length;return`PowerShell (${
|
|
415
|
-
`),
|
|
416
|
-
`),X=[],K=Y.slice(0,
|
|
417
|
-
${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};Y=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},z,...G.toKeep]}catch{}}let X=
|
|
418
|
-
`)}function
|
|
419
|
-
`)}try{let
|
|
420
|
-
`),X=
|
|
458
|
+
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=Q.toLowerCase();if(Y.includes("econnrefused")||Y.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(Y.includes("etimedout")||Y.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(Y.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(Y.includes("expired")||Y.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return Q}function vH($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function fH($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function LY($,Z,Q){if($==="auto")return!1;if(Q==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command","execute_powershell_script"].includes(Z);if($==="confirm-all")return Q!=="safe";return!1}function jY($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let Q=String(Z.command||"");return`Run: ${Q.length>60?Q.slice(0,57)+"...":Q}`}case"execute_powershell_script":{let Q=String(Z.script||""),Y=Q.split(`
|
|
459
|
+
`)[0]||"",J=Q.split(`
|
|
460
|
+
`).length;return`PowerShell (${J} line${J>1?"s":""}): ${Y.length>50?Y.slice(0,47)+"...":Y}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function DY($,Z,Q=20){let Y=$.split(`
|
|
461
|
+
`),J=Z.split(`
|
|
462
|
+
`),X=[],K=Y.slice(0,Q);for(let G of K)X.push(` \x1B[31m- ${G}\x1B[0m`);if(Y.length>Q)X.push(` \x1B[2m ... (${Y.length-Q} more removed)\x1B[0m`);let V=J.slice(0,Q);for(let G of V)X.push(` \x1B[32m+ ${G}\x1B[0m`);if(J.length>Q)X.push(` \x1B[2m ... (${J.length-Q} more added)\x1B[0m`);return X}class BZ{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Q,Y="auto"){this.model=Z;this.maxTokens=Q;this.client=new f$({apiKey:$}),this.approvalMode=Y}updateApiKey($){this.client=new f$({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Q=!0){let Y=RY($),J=x4(Z);if(MY(Y,this.model,J)){let G=FY(Y,this.model,J);if(G)try{let z={role:"assistant",content:`[Conversation summary]
|
|
463
|
+
${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};Y=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},z,...G.toKeep]}catch{}}let X=NY(Y,this.model,J),K=hH(X),V=Q?p:void 0;try{yield*this.streamLoop(K,Z,V)}catch(G){yield{type:"error",error:WZ(G)}}}async generateSummary($){let Z=OY($),Y=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((J)=>J.type==="text");return Y?.type==="text"?Y.text:"Summary unavailable."}async*streamLoop($,Z,Q){let J=[...$],X=0;while(X++<25){let K;try{K=await CY(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:J,...Q?.length?{tools:Q}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(z){yield{type:"error",error:WZ(z)};return}for await(let z of K)if(z.type==="content_block_delta"&&z.delta.type==="text_delta")yield{type:"text",text:z.delta.text};let V=await K.finalMessage();if(V.usage)yield{type:"usage",inputTokens:V.usage.input_tokens,outputTokens:V.usage.output_tokens};if(V.stop_reason!=="tool_use"){yield{type:"done"};return}let G=V.content.filter((z)=>z.type==="tool_use");J.push({role:"assistant",content:V.content});let H=[];for(let z of G){let B=z.input,W=EY(z.name,B);if(W.level==="dangerous"){yield{type:"tool_blocked",id:z.id,name:z.name,reason:`Blocked dangerous operation: ${W.reason}`},H.push({type:"tool_result",tool_use_id:z.id,content:`Error: Operation blocked for safety. Reason: ${W.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&LY(this.approvalMode,z.name,W.level)&&this.approvalCallback){if(yield{type:"tool_call",id:z.id,name:z.name,input:z.input},!await this.approvalCallback(z.name,B,W.level)){yield{type:"tool_blocked",id:z.id,name:z.name,reason:"Rejected by user"},H.push({type:"tool_result",tool_use_id:z.id,content:"Error: User rejected this operation."});continue}let j=await HZ(z.name,B);yield{type:"tool_result",id:z.id,name:z.name,result:j},H.push({type:"tool_result",tool_use_id:z.id,content:j});continue}yield{type:"tool_call",id:z.id,name:z.name,input:z.input};let N=await HZ(z.name,B);yield{type:"tool_result",id:z.id,name:z.name,result:N},H.push({type:"tool_result",tool_use_id:z.id,content:N})}J.push({role:"user",content:H})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function hH($){let Z=[];for(let Q of $)if(Q.role==="user")if(Q.images?.length){let Y=Q.images.map((J)=>({type:"image",source:{type:"base64",media_type:J.mediaType,data:J.base64}}));Y.push({type:"text",text:Q.content}),Z.push({role:"user",content:Y})}else Z.push({role:"user",content:Q.content});else if(Q.role==="assistant")if(Q.toolCalls?.length){let Y=[];if(Q.content)Y.push({type:"text",text:Q.content});for(let J of Q.toolCalls)Y.push({type:"tool_use",id:J.id,name:J.name,input:J.input});Z.push({role:"assistant",content:Y}),Z.push({role:"user",content:Q.toolCalls.map((J)=>({type:"tool_result",tool_use_id:J.id,content:J.result}))})}else Z.push({role:"assistant",content:Q.content});return Z}n();import{existsSync as P$,mkdirSync as PY,readdirSync as TY,readFileSync as J5,unlinkSync as AY,renameSync as CZ}from"fs";import{join as K$}from"path";class NZ{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=K$($,"sessions"),this.archiveDir=K$($,"sessions","archive"),!P$(this.sessionsDir))PY(this.sessionsDir,{recursive:!0});if(!P$(this.archiveDir))PY(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(!P$(this.sessionsDir))return[];return TY(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=K$(this.sessionsDir,`${$}.json`);if(!P$(Z))return null;try{let Q=JSON.parse(J5(Z,"utf-8"));return{messageCount:Q.messages.length,updated:Q.updated}}catch{return null}}delete($){let Z=K$(this.sessionsDir,`${$}.json`);if(P$(Z))return AY(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Q=K$(this.sessionsDir,`${$}.json`);return S(Q,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=K$(this.sessionsDir,`${$}.json`);if(!P$(Z))return!1;let Q=K$(this.archiveDir,`${$}.json`);return CZ(Z,Q),!0}archiveAll(){let $=[],Z=this.list().filter((Q)=>Q!==this.current.name);for(let Q of Z)if(this.archive(Q))$.push(Q);return $}unarchive($){let Z=K$(this.archiveDir,`${$}.json`);if(!P$(Z))return!1;let Q=K$(this.sessionsDir,`${$}.json`);return CZ(Z,Q),!0}listArchived(){if(!P$(this.archiveDir))return[];return TY(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=K$(this.archiveDir,`${$}.json`);if(!P$(Z))return null;try{let Q=JSON.parse(J5(Z,"utf-8"));return{messageCount:Q.messages.length,updated:Q.updated}}catch{return null}}deleteArchived($){let Z=K$(this.archiveDir,`${$}.json`);if(P$(Z))return AY(Z),!0;return!1}loadOrCreate($){let Z=K$(this.sessionsDir,`${$}.json`);if(P$(Z))try{return JSON.parse(J5(Z,"utf-8"))}catch{let Y=K$(this.sessionsDir,`${$}.corrupt.json`);try{CZ(Z,Y)}catch{}}let Q={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return S(Z,JSON.stringify(Q,null,2)),Q}saveLastSession(){let $=K$(this.sessionsDir,"..","last-session.txt");S($,this.current.name)}getLastSession(){let $=K$(this.sessionsDir,"..","last-session.txt");if(!P$($))return null;try{let Z=J5($,"utf-8").trim();if(!Z||!P$(K$(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}save(){let $=K$(this.sessionsDir,`${this.current.name}.json`);S($,JSON.stringify(this.current,null,2))}}import{existsSync as SY,readdirSync as cH,readFileSync as wY}from"fs";import{join as FZ}from"path";Z$();import{existsSync as MZ,readFileSync as IY}from"fs";import{basename as gH,join as X5}from"path";function xY(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${Q2()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),A)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Q=mH($);if(Q)Z.push(`Project: ${Q}`);let Y=pH($);if(Y)Z.push(Y);return Z.join(`
|
|
464
|
+
`)}function mH($){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"]],Q=[];for(let[J,X]of Z)if(MZ(X5($,J)))Q.push(X);if(Q.length===0)return null;let Y=gH($);try{let J=X5($,"package.json");if(MZ(J)){let X=JSON.parse(IY(J,"utf-8"));if(X.name)Y=X.name}}catch{}return`Project: ${Y} (${Q.join(", ")})`}function pH($){if(!MZ(X5($,".git")))return null;let Z=[];try{let Q=IY(X5($,".git","HEAD"),"utf-8").trim(),Y=Q.startsWith("ref: refs/heads/")?Q.slice(16):Q.slice(0,8);Z.push(`Git branch: ${Y}`)}catch{return Z.push("Git: initialized"),Z.join(`
|
|
465
|
+
`)}try{let Q=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Q.exitCode===0){let Y=new TextDecoder().decode(Q.stdout).trim();if(Y)Z.push(`Last commit: ${Y}`)}}catch{}try{let Q=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Q.exitCode===0){let Y=new TextDecoder().decode(Q.stdout).trim();if(Y){let J=Y.split(`
|
|
466
|
+
`),X=J.slice(0,15);if(J.length>15)X.push(`... and ${J.length-15} more files`);Z.push(`Uncommitted changes:
|
|
421
467
|
`+X.join(`
|
|
422
|
-
`))}}}catch{}try{let
|
|
468
|
+
`))}}}catch{}try{let Q=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Q.exitCode===0){let Y=new TextDecoder().decode(Q.stdout).trim();if(Y){let J=Y.split(`
|
|
423
469
|
`).slice(0,10);Z.push(`Staged:
|
|
424
|
-
`+
|
|
470
|
+
`+J.join(`
|
|
425
471
|
`))}}}catch{}return Z.length>0?Z.join(`
|
|
426
|
-
`):null}function
|
|
472
|
+
`):null}function kY($,Z){if(!SY($))return[];let Q=[],Y=cH($,{withFileTypes:!0});for(let J of Y)if(J.isFile()&&J.name.endsWith(".md")){let X=wY(FZ($,J.name),"utf-8");Q.push({name:J.name.replace(".md",""),content:X.trim(),source:Z})}else if(J.isDirectory()){let X=FZ($,J.name,"SKILL.md");if(SY(X)){let K=wY(X,"utf-8");Q.push({name:J.name,content:K.trim(),source:Z})}}return Q}function yY($){let Z=kY($,"global"),Q=FZ(process.cwd(),".smolerclaw","skills"),Y=kY(Q,"local"),J=new Map;for(let X of Z)J.set(X.name,X);for(let X of Y)J.set(X.name,X);return[...J.values()]}function bY($){if($.length===0)return"No skills loaded.";return`Skills:
|
|
427
473
|
`+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
|
|
428
|
-
`)}function
|
|
429
|
-
ALWAYS respond in ${X}. This is a hard requirement.`)}if(
|
|
430
|
-
`+
|
|
474
|
+
`)}function OZ($,Z,Q="auto"){let Y=[];for(let J of Z)Y.push(J.content);if(Q&&Q!=="auto"){let X={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[Q]||Q;Y.push(`## Language Override
|
|
475
|
+
ALWAYS respond in ${X}. This is a hard requirement.`)}if(V4())Y.push(`---
|
|
476
|
+
`+QY());if(Y.push(`---
|
|
431
477
|
## Meta-Learning & Self-Awareness
|
|
432
478
|
You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
|
|
433
479
|
|
|
@@ -447,34 +493,35 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
|
|
|
447
493
|
## Environment
|
|
448
494
|
The user's current working directory and project info. Use this context when they ask about code or files.
|
|
449
495
|
|
|
450
|
-
`+
|
|
496
|
+
`+xY()),$)Y.push(`## User Instructions
|
|
451
497
|
`+$);return Y.join(`
|
|
452
498
|
|
|
453
|
-
`)}var
|
|
454
|
-
`)){if(
|
|
455
|
-
`),
|
|
456
|
-
`).filter(Boolean).slice(-
|
|
499
|
+
`)}var uH=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function m$($){return uH?"":$}var U={altOn:m$("\x1B[?1049h"),altOff:m$("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:m$("\x1B[1m"),dim:m$("\x1B[2m"),italic:m$("\x1B[3m"),underline:m$("\x1B[4m"),reset:m$("\x1B[0m"),inv:m$("\x1B[7m"),fg:($)=>m$(`\x1B[38;5;${$}m`),bg:($)=>m$(`\x1B[48;5;${$}m`)};var b={user:U.fg(75),ai:U.fg(114),tool:U.fg(215),err:U.fg(196),sys:U.fg(245),prompt:U.fg(220),code:U.fg(180),heading:U.fg(75),link:U.fg(39),quote:U.fg(245)},dH={primary:U.fg(75),secondary:U.fg(39),accent:U.fg(220),muted:U.fg(245),header:U.fg(81)},lH={primary:U.fg(215),secondary:U.fg(220),accent:U.fg(196),muted:U.fg(245),header:U.fg(214)},oH={primary:U.fg(183),secondary:U.fg(157),accent:U.fg(147),muted:U.fg(242),header:U.fg(183)};function RZ($){switch($){case"productivity":return dH;case"spillover_alert":return lH;case"sharpen_or_relax":return oH}}function E($){process.stdout.write($)}var aH=/\x1b\[[0-9;]*[a-zA-Z]/g;function S4($){return $.replace(aH,"")}function nH($){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 G$($){let Z=S4($),Q=0;for(let Y of Z)Q+=nH(Y);return Q}function w4($,Z){if(Z<10)Z=10;let Q=[];for(let Y of $.split(`
|
|
500
|
+
`)){if(G$(Y)<=Z){Q.push(Y);continue}let K=S4(Y).split(" "),V=[],G="";for(let z of K)if(G.length+(G?1:0)+z.length>Z&&G)V.push(G),G=" "+z;else G+=(G?" ":"")+z;if(G)V.push(G);let H=rH(Y);for(let z=0;z<V.length;z++)if(H&&z===0)V[z]=H+V[z]+U.reset;else if(H)V[z]=H+V[z]+U.reset;Q.push(...V)}return Q}function rH($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function K5($,Z){let Q=Z??(process.stdout.columns||80),Y=$.split(`
|
|
501
|
+
`),J=[],X=!1,K="";for(let V=0;V<Y.length;V++){let G=Y[V];if(G.trimStart().startsWith("```")){if(!X){X=!0,K=G.trimStart().slice(3).trim();let N=K?` ${K}`:"";J.push(` ${U.dim}\u250C\u2500\u2500${N}${"\u2500".repeat(Math.max(1,40-N.length))}${U.reset}`)}else X=!1,K="",J.push(` ${U.dim}\u2514${"\u2500".repeat(42)}${U.reset}`);continue}if(X){J.push(` ${U.dim}\u2502${U.reset} ${b.code}${G}${U.reset}`);continue}if(!G.trim()){J.push("");continue}let H=G.match(/^(#{1,3})\s+(.+)/);if(H){let N=H[1].length,O=H[2],j=N===1?"\u2501":N===2?"\u2500":"\xB7";J.push(` ${b.heading}${U.bold}${j} ${n1(O)}${U.reset}`);continue}if(G.trimStart().startsWith(">")){let N=G.replace(/^\s*>\s?/,"");EZ(J,` ${b.quote}\u2502 ${n1(N)}${U.reset}`,Q);continue}let z=G.match(/^(\s*)([-*+])\s+(.+)/);if(z){let N=Math.floor(z[1].length/2),O=z[3],j=" ".repeat(N);EZ(J,` ${j}${U.dim}\u2022${U.reset} ${n1(O)}`,Q);continue}let B=G.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(B){let N=Math.floor(B[1].length/2),O=B[2],j=B[3],P=" ".repeat(N);EZ(J,` ${P}${U.dim}${O}.${U.reset} ${n1(j)}`,Q);continue}if(/^[-*_]{3,}\s*$/.test(G.trim())){J.push(` ${U.dim}${"\u2500".repeat(40)}${U.reset}`);continue}let W=` ${n1(G)}`;if(G$(W)>Q)for(let N of w4(W,Q))J.push(N);else J.push(W)}if(X)J.push(` ${U.dim}\u2514${"\u2500".repeat(42)}${U.reset}`);return J}function EZ($,Z,Q){if(G$(Z)>Q)for(let Y of w4(Z,Q))$.push(Y);else $.push(Z)}function n1($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${U.inv} $1 ${U.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${U.bold}${U.italic}$1${U.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${U.bold}$1${U.reset}`),Z=Z.replace(/__(.+?)__/g,`${U.bold}$1${U.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${U.italic}$1${U.reset}`),Z=Z.replace(/_(.+?)_/g,`${U.italic}$1${U.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${U.underline}$1${U.reset} ${b.link}($2)${U.reset}`),Z}import{existsSync as iH,readFileSync as sH,writeFileSync as tH}from"fs";var LZ=500;class jZ{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>LZ)this.entries=this.entries.slice(-LZ);this.cursor=-1,this.pending="",this.save()}prev($){if(this.entries.length===0)return null;if(this.cursor===-1)this.pending=$,this.cursor=this.entries.length-1;else if(this.cursor>0)this.cursor--;else return this.entries[0];return this.entries[this.cursor]}next(){if(this.cursor===-1)return this.pending;if(this.cursor<this.entries.length-1)return this.cursor++,this.entries[this.cursor];return this.cursor=-1,this.pending}reset(){this.cursor=-1,this.pending=""}load(){try{if(iH(this.filePath)){let $=sH(this.filePath,"utf-8");this.entries=$.split(`
|
|
502
|
+
`).filter(Boolean).slice(-LZ)}}catch{}}save(){try{tH(this.filePath,this.entries.join(`
|
|
457
503
|
`)+`
|
|
458
|
-
`)}catch{}}}import{join as NH}from"path";var $H=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],ZH=" ";function ZZ($,Z={}){let{width:J=$.length,min:Y=Math.min(...$),max:Q=Math.max(...$),color:X="",showBounds:K=!1}=Z;if($.length===0)return"";let V=WH($,J),G=Q-Y||1,z=V.map((B)=>{if(B===0&&Y===0)return ZH;let M=(B-Y)/G,O=Math.min(7,Math.floor(M*8));return $H[O]}).join(""),U=X?`${X}${z}${W.reset}`:z;if(K)return`${W.dim}${Y.toFixed(0)}${W.reset}${U}${W.dim}${Q.toFixed(0)}${W.reset}`;return U}var JH="\u2588",YH="\u2589",QH="\u258A",XH="\u258B",KH="\u258C",zH="\u258D",VH="\u258E",GH="\u258F",HH="\u2591",qH=[" ",GH,VH,zH,KH,XH,QH,YH];function JZ($,Z={}){let{width:J=20,maxValue:Y=100,showValue:Q=!0,color:X=W.fg(75),label:K=""}=Z,V=Math.min(1,Math.max(0,$/Y)),G=Math.floor(V*J),H=V*J-G,z=Math.floor(H*8),U=JH.repeat(G);if(z>0&&G<J)U+=qH[z];let B=J-K$(U);U+=HH.repeat(Math.max(0,B));let M=X?`${X}${U}${W.reset}`:U,O=[];if(K)O.push(`${W.dim}${K.padEnd(12)}${W.reset}`);if(O.push(M),Q)O.push(` ${W.dim}${$.toFixed(1)}%${W.reset}`);return O.join("")}function f1($,Z){let J=[];if(J.push(`${b.ai}${$.model}${W.reset}`),$.project)J.push(`${b.heading}${$.project}${W.reset}`);if($.tokens){let{input:K,output:V}=$.tokens;J.push(`${W.dim}${$Y(K)}/${$Y(V)} tok${W.reset}`)}if($.sessionCost)J.push(`${W.dim}${$.sessionCost}${W.reset}`);if($.vaultStatus){let K=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",V=$.vaultStatus==="ok"?W.fg(114):$.vaultStatus==="warn"?W.fg(220):W.fg(196);J.push(`${V}${K}${W.reset}`)}if($.customItems)for(let K of $.customItems){let V=K.color||"";J.push(`${W.dim}${K.label}:${W.reset}${V}${K.value}${W.reset}`)}let Y=J.join(` ${W.dim}\u2502${W.reset} `),Q=K$(Y),X=Math.max(0,Z-Q-2);return`${W.inv} ${Y}${" ".repeat(X)} ${W.reset}`}function YZ($,Z=40){let J=[];J.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),J.push(`${b.heading}${W.bold} System${W.reset}`);let Y=ZZ($.cpu,{width:15,color:W.fg(75)}),Q=JZ($.currentCpu,{width:10,showValue:!1,color:W.fg(75)});J.push(` ${W.dim}CPU:${W.reset} ${Y} ${Q} ${$.currentCpu.toFixed(0)}%`);let X=ZZ($.memory,{width:15,color:W.fg(114)}),K=JZ($.currentMem,{width:10,showValue:!1,color:W.fg(114)});return J.push(` ${W.dim}MEM:${W.reset} ${X} ${K} ${$.currentMem.toFixed(0)}%`),J.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),J}function WH($,Z){if($.length<=Z){let Q=[...$];while(Q.length<Z)Q.unshift(0);return Q}let J=$.length/Z,Y=[];for(let Q=0;Q<Z;Q++){let X=Math.floor(Q*J),K=Math.floor((Q+1)*J),V=$.slice(X,K),G=V.reduce((H,z)=>H+z,0)/V.length;Y.push(G)}return Y}function $Y($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function h1($,Z,J={}){let{title:Y="",padding:Q=1,borderColor:X=W.dim,titleColor:K=b.heading}=J,V=Z-2-Q*2,G=[];if(Y){let z=K$(Y),U=2,B=Math.max(1,Z-z-2-4);G.push(`${X}\u250C${"\u2500".repeat(2)}${W.reset}${K}${W.bold} ${Y} ${W.reset}${X}${"\u2500".repeat(B)}\u2510${W.reset}`)}else G.push(`${X}\u250C${"\u2500".repeat(Z-2)}\u2510${W.reset}`);let H=" ".repeat(Q);for(let z of $){let U=K$(z)>V?D4(z,V):[z];for(let B of U){let M=K$(B),O=Math.max(0,V-M);G.push(`${X}\u2502${W.reset}${H}${B}${" ".repeat(O)}${H}${X}\u2502${W.reset}`)}}return G.push(`${X}\u2514${"\u2500".repeat(Z-2)}\u2518${W.reset}`),G}function QZ($,Z,J,Y,Q={}){let X=h1($,Y,Q);for(let K=0;K<X.length;K++)R(W.to(Z+K,J)),R(X[K])}var c7={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},UH={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function XZ($,Z={}){let{width:J=60,showActions:Y=!0,compact:Q=!1}=Z,X=[],K=UH[$.category]||"\uD83D\uDCA1",V=c7.dimYellow+c7.italic;if(Q){let z=$.title.length>J-10?$.title.slice(0,J-13)+"...":$.title;return X.push(` ${V}${K} ${z}${W.reset}`),X}X.push(` ${V}${K} ${$.title}${W.reset}`);let G=J-6,H=D4($.explanation,G);for(let z of H)X.push(` ${V} ${L4(z)}${W.reset}`);if($.suggestedAction)X.push(` ${c7.dimCyan} \u2192 ${$.suggestedAction.label}${W.reset}`);if(Y)X.push(` ${W.dim} [Y] Aceitar [N] Ignorar${W.reset}`);return X}function ZY($,Z=40){let J=[],Y=[...$].sort((Q,X)=>X.frequency-Q.frequency).slice(0,3);if(Y.length===0)return J.push(`${W.dim} Nenhuma dica disponivel ainda.${W.reset}`),J.push(`${W.dim} Continue usando para gerar insights.${W.reset}`),J;for(let Q=0;Q<Y.length;Q++){let X=Y[Q],K=Q+1,V=K===1?"\uD83E\uDD47":K===2?"\uD83E\uDD48":"\uD83E\uDD49",G=Z-8,H=X.title.length>G?X.title.slice(0,G-3)+"...":X.title;J.push(`${V} ${c7.dimYellow}${H}${W.reset}`);let z=Z-4,U=X.description.length>z?X.description.slice(0,z-3)+"...":X.description;J.push(` ${W.dim}${U}${W.reset}`);let B=X.frequency===1?"vez":"vezes";if(J.push(` ${W.dim}Detectado ${X.frequency}x${W.reset}`),Q<Y.length-1)J.push("")}return J}function p7($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:ZY($,Z)}}class g1{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;R(W.to($,1)),R(f1(this.statusConfig,this.width))}clearScreen(){R(W.clear),R(W.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)R(W.to(Z,1)),R(W.clearLine)}updateDimensions($,Z){this.width=$,this.height=Z;for(let J of this.resizeCallbacks)J()}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:J=1}=this.dashboardLayout,Y=this.getViewState(),Q=Y.contentEndRow-Y.contentStartRow,X=Math.floor((this.width-J*(Z+1))/Z),K=Y.contentStartRow,V=1+J;for(let G=0;G<$.length;G++){let H=$[G],z=H.row??K,U=H.col??V,B=H.width??X,M=H.height??Math.floor(Q/Math.ceil($.length/Z));if(this.drawDashboardPanel(H,z,U,B,M),(G+1)%Z===0)K+=M+J,V=1+J;else V+=B+J}this.renderStatusBar()}drawDashboardPanel($,Z,J,Y,Q){let X=Q-2,K=$.content.slice(0,X);QZ(K,Z,J,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 u7($,Z){R(`\x1B[${$};${Z}r`)}function d7(){R("\x1B[r")}var BH=new g1;A8();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=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","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/index","/indexar","/reindex","/memory","/memoria","/clipboard","/area","/tela","/screen","/ps1","/refresh","/renovar","/vault","/backup","/feeds","/fontes","/addfeed","/novafonte","/rmfeed","/rmfonte","/disablefeed","/desativarfonte","/enablefeed","/ativarfonte","/projeto","/project","/projetos","/projects","/sessao","/session","/relatorio","/report","/oportunidades","/opportunities","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];subcommands={"/model":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/modelo":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/news":["business","tech","finance","brazil","world","security"],"/noticias":["business","tech","finance","brazil","world","security"],"/open":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/abrir":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/sessao":["start","stop","status"],"/session":["start","stop","status"],"/relatorio":["today","week","month"],"/report":["today","week","month"],"/projeto":["auto"],"/project":["auto"],"/oportunidades":["nova","em_analise","aceita","recusada","concluida"],"/opportunities":["nova","em_analise","aceita","recusada","concluida"],"/persona":["default","business"],"/modo":["default","business"],"/people":["equipe","familia","contato"],"/pessoas":["equipe","familia","contato"],"/investigar":["bug","feature","test","audit","incident"],"/investigate":["bug","feature","test","audit","incident"],"/entrada":[],"/saida":[],"/lang":["pt","en","auto"],"/idioma":["pt","en","auto"],"/pomodoro":["start","stop","status"],"/foco":["start","stop","status"],"/monitor":["start","stop","list"],"/vigiar":["start","stop","list"],"/vault":["status","backup","sync","init"],"/workflow":["list","run","info","create","delete","enable","disable"],"/fluxo":["list","run","info","create","delete","ativar","desativar"]};onSubmit=null;onCancel=null;onExit=null;pickerActive=!1;lastCtrlCTime=0;eventUnsubscribers=[];statusBarContext="";activeInsight=null;insightSnippetLines=0;insightDisplayed=!1;metaLearningEntries=[];constructor($,Z,J="",Y){this.model=$;this.sessionName=Z;this.authInfo=J;this.dataDir=Y;this.viewManager=new g1}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(NH(this.dataDir,"history"));this.setupEventListeners(),R(W.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}setupEventListeners(){this.eventUnsubscribers.push(H$.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(H$.on("status:update",($)=>{let Z=$.level==="error"?b.err:$.level==="warning"?b.prompt:$.level==="success"?b.sys:W.dim;if(this.lines.push({text:` ${Z}[${$.source}]${W.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(H$.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${b.prompt}\u26A0 ${$.message}${W.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${b.err}\u26A0 Rate limit: ${$.message}${W.reset}`});else this.lines.push({text:` ${W.dim}[telemetry] ${$.message}${W.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(H$.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${W.dim}[backup] ${$.message||"Backup concluido"}${W.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${b.sys}[pomodoro] ${$.message}${W.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${b.err}[${$.taskType}] ${$.message}${W.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(H$.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(H$.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(),R(W.show),R(W.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=m7(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=m7(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 J=Z,Y;switch($){case"read_file":if(Y=String(J.path||""),J.offset)Y+=`:${J.offset}`;break;case"write_file":case"edit_file":Y=String(J.path||"");break;case"search_files":if(Y=`/${J.pattern||""}/`,J.include)Y+=` (${J.include})`;break;case"find_files":Y=String(J.pattern||"");break;case"list_directory":Y=String(J.path||".");break;case"run_command":if(Y=String(J.command||""),Y.length>80)Y=Y.slice(0,77)+"...";break;default:{let Q=JSON.stringify(J);Y=Q.length>80?Q.slice(0,77)+"...":Q}}this.lines.push({text:` ${b.tool}\u2699 ${$}${W.reset} ${W.dim}${Y}${W.reset}`}),this.renderMessages()}showToolResult($,Z){let J=Z.split(`
|
|
459
|
-
`),Y=8,Q
|
|
460
|
-
`)process.stdin.removeListener("data",
|
|
461
|
-
`){if(
|
|
462
|
-
|
|
463
|
-
`)
|
|
504
|
+
`)}catch{}}}import{join as Bq}from"path";var eH=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],$q=" ";function DZ($,Z={}){let{width:Q=$.length,min:Y=Math.min(...$),max:J=Math.max(...$),color:X="",showBounds:K=!1}=Z;if($.length===0)return"";let V=qq($,Q),G=J-Y||1,z=V.map((W)=>{if(W===0&&Y===0)return $q;let N=(W-Y)/G,O=Math.min(7,Math.floor(N*8));return eH[O]}).join(""),B=X?`${X}${z}${U.reset}`:z;if(K)return`${U.dim}${Y.toFixed(0)}${U.reset}${B}${U.dim}${J.toFixed(0)}${U.reset}`;return B}var Zq="\u2588",Qq="\u2589",Yq="\u258A",Jq="\u258B",Xq="\u258C",Kq="\u258D",zq="\u258E",Vq="\u258F",Gq="\u2591",Hq=[" ",Vq,zq,Kq,Xq,Jq,Yq,Qq];function PZ($,Z={}){let{width:Q=20,maxValue:Y=100,showValue:J=!0,color:X=U.fg(75),label:K=""}=Z,V=Math.min(1,Math.max(0,$/Y)),G=Math.floor(V*Q),H=V*Q-G,z=Math.floor(H*8),B=Zq.repeat(G);if(z>0&&G<Q)B+=Hq[z];let W=Q-G$(B);B+=Gq.repeat(Math.max(0,W));let N=X?`${X}${B}${U.reset}`:B,O=[];if(K)O.push(`${U.dim}${K.padEnd(12)}${U.reset}`);if(O.push(N),J)O.push(` ${U.dim}${$.toFixed(1)}%${U.reset}`);return O.join("")}function r1($,Z){let Q=[];if(Q.push(`${b.ai}${$.model}${U.reset}`),$.project)Q.push(`${b.heading}${$.project}${U.reset}`);if($.tokens){let{input:K,output:V}=$.tokens;Q.push(`${U.dim}${_Y(K)}/${_Y(V)} tok${U.reset}`)}if($.sessionCost)Q.push(`${U.dim}${$.sessionCost}${U.reset}`);if($.vaultStatus){let K=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",V=$.vaultStatus==="ok"?U.fg(114):$.vaultStatus==="warn"?U.fg(220):U.fg(196);Q.push(`${V}${K}${U.reset}`)}if($.customItems)for(let K of $.customItems){let V=K.color||"";Q.push(`${U.dim}${K.label}:${U.reset}${V}${K.value}${U.reset}`)}let Y=Q.join(` ${U.dim}\u2502${U.reset} `),J=G$(Y),X=Math.max(0,Z-J-2);return`${U.inv} ${Y}${" ".repeat(X)} ${U.reset}`}function TZ($,Z=40){let Q=[];Q.push(`${U.dim}${"\u2500".repeat(Z)}${U.reset}`),Q.push(`${b.heading}${U.bold} System${U.reset}`);let Y=DZ($.cpu,{width:15,color:U.fg(75)}),J=PZ($.currentCpu,{width:10,showValue:!1,color:U.fg(75)});Q.push(` ${U.dim}CPU:${U.reset} ${Y} ${J} ${$.currentCpu.toFixed(0)}%`);let X=DZ($.memory,{width:15,color:U.fg(114)}),K=PZ($.currentMem,{width:10,showValue:!1,color:U.fg(114)});return Q.push(` ${U.dim}MEM:${U.reset} ${X} ${K} ${$.currentMem.toFixed(0)}%`),Q.push(`${U.dim}${"\u2500".repeat(Z)}${U.reset}`),Q}function qq($,Z){if($.length<=Z){let J=[...$];while(J.length<Z)J.unshift(0);return J}let Q=$.length/Z,Y=[];for(let J=0;J<Z;J++){let X=Math.floor(J*Q),K=Math.floor((J+1)*Q),V=$.slice(X,K),G=V.reduce((H,z)=>H+z,0)/V.length;Y.push(G)}return Y}function _Y($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function i1($,Z,Q={}){let{title:Y="",padding:J=1,borderColor:X=U.dim,titleColor:K=b.heading}=Q,V=Z-2-J*2,G=[];if(Y){let z=G$(Y),B=2,W=Math.max(1,Z-z-2-4);G.push(`${X}\u250C${"\u2500".repeat(2)}${U.reset}${K}${U.bold} ${Y} ${U.reset}${X}${"\u2500".repeat(W)}\u2510${U.reset}`)}else G.push(`${X}\u250C${"\u2500".repeat(Z-2)}\u2510${U.reset}`);let H=" ".repeat(J);for(let z of $){let B=G$(z)>V?w4(z,V):[z];for(let W of B){let N=G$(W),O=Math.max(0,V-N);G.push(`${X}\u2502${U.reset}${H}${W}${" ".repeat(O)}${H}${X}\u2502${U.reset}`)}}return G.push(`${X}\u2514${"\u2500".repeat(Z-2)}\u2518${U.reset}`),G}function AZ($,Z,Q,Y,J={}){let X=i1($,Y,J);for(let K=0;K<X.length;K++)E(U.to(Z+K,Q)),E(X[K])}var z5={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},Uq={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function IZ($,Z={}){let{width:Q=60,showActions:Y=!0,compact:J=!1}=Z,X=[],K=Uq[$.category]||"\uD83D\uDCA1",V=z5.dimYellow+z5.italic;if(J){let z=$.title.length>Q-10?$.title.slice(0,Q-13)+"...":$.title;return X.push(` ${V}${K} ${z}${U.reset}`),X}X.push(` ${V}${K} ${$.title}${U.reset}`);let G=Q-6,H=w4($.explanation,G);for(let z of H)X.push(` ${V} ${S4(z)}${U.reset}`);if($.suggestedAction)X.push(` ${z5.dimCyan} \u2192 ${$.suggestedAction.label}${U.reset}`);if(Y)X.push(` ${U.dim} [Y] Aceitar [N] Ignorar${U.reset}`);return X}function vY($,Z=40){let Q=[],Y=[...$].sort((J,X)=>X.frequency-J.frequency).slice(0,3);if(Y.length===0)return Q.push(`${U.dim} Nenhuma dica disponivel ainda.${U.reset}`),Q.push(`${U.dim} Continue usando para gerar insights.${U.reset}`),Q;for(let J=0;J<Y.length;J++){let X=Y[J],K=J+1,V=K===1?"\uD83E\uDD47":K===2?"\uD83E\uDD48":"\uD83E\uDD49",G=Z-8,H=X.title.length>G?X.title.slice(0,G-3)+"...":X.title;Q.push(`${V} ${z5.dimYellow}${H}${U.reset}`);let z=Z-4,B=X.description.length>z?X.description.slice(0,z-3)+"...":X.description;Q.push(` ${U.dim}${B}${U.reset}`);let W=X.frequency===1?"vez":"vezes";if(Q.push(` ${U.dim}Detectado ${X.frequency}x${U.reset}`),J<Y.length-1)Q.push("")}return Q}function V5($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:vY($,Z)}}class s1{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(U.to($,1)),E(r1(this.statusConfig,this.width))}clearScreen(){E(U.clear),E(U.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)E(U.to(Z,1)),E(U.clearLine)}updateDimensions($,Z){this.width=$,this.height=Z;for(let Q of this.resizeCallbacks)Q()}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:Q=1}=this.dashboardLayout,Y=this.getViewState(),J=Y.contentEndRow-Y.contentStartRow,X=Math.floor((this.width-Q*(Z+1))/Z),K=Y.contentStartRow,V=1+Q;for(let G=0;G<$.length;G++){let H=$[G],z=H.row??K,B=H.col??V,W=H.width??X,N=H.height??Math.floor(J/Math.ceil($.length/Z));if(this.drawDashboardPanel(H,z,B,W,N),(G+1)%Z===0)K+=N+Q,V=1+Q;else V+=W+Q}this.renderStatusBar()}drawDashboardPanel($,Z,Q,Y,J){let X=J-2,K=$.content.slice(0,X);AZ(K,Z,Q,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:TZ($,35)}],columns:1,gap:1}}}function G5($,Z){E(`\x1B[${$};${Z}r`)}function H5(){E("\x1B[r")}var Wq=new s1;b8();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=RZ("productivity");timeContext=null;commands=["/help","/clear","/commit","/persona","/copy","/fork","/new","/load","/sessions","/delete","/model","/export","/cost","/retry","/undo","/search","/lang","/config","/exit","/briefing","/news","/open","/openfile","/openurl","/apps","/sysinfo","/calendar","/ask","/budget","/plugins","/task","/tasks","/done","/rmtask","/people","/team","/family","/person","/addperson","/delegate","/delegations","/followups","/dashboard","/contacts","/investigar","/investigate","/investigacoes","/monitor","/vigiar","/workflow","/fluxo","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/index","/indexar","/reindex","/memory","/memoria","/clipboard","/area","/tela","/screen","/ps1","/refresh","/renovar","/vault","/backup","/feeds","/fontes","/addfeed","/novafonte","/rmfeed","/rmfonte","/disablefeed","/desativarfonte","/enablefeed","/ativarfonte","/projeto","/project","/projetos","/projects","/sessao","/session","/relatorio","/report","/oportunidades","/opportunities","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];subcommands={"/model":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/modelo":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/news":["business","tech","finance","brazil","world","security"],"/noticias":["business","tech","finance","brazil","world","security"],"/open":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/abrir":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/sessao":["start","stop","status"],"/session":["start","stop","status"],"/relatorio":["today","week","month"],"/report":["today","week","month"],"/projeto":["auto"],"/project":["auto"],"/oportunidades":["nova","em_analise","aceita","recusada","concluida"],"/opportunities":["nova","em_analise","aceita","recusada","concluida"],"/persona":["default","business"],"/modo":["default","business"],"/people":["equipe","familia","contato"],"/pessoas":["equipe","familia","contato"],"/investigar":["bug","feature","test","audit","incident"],"/investigate":["bug","feature","test","audit","incident"],"/entrada":[],"/saida":[],"/lang":["pt","en","auto"],"/idioma":["pt","en","auto"],"/pomodoro":["start","stop","status"],"/foco":["start","stop","status"],"/monitor":["start","stop","list"],"/vigiar":["start","stop","list"],"/vault":["status","backup","sync","init"],"/workflow":["list","run","info","create","delete","enable","disable"],"/fluxo":["list","run","info","create","delete","ativar","desativar"]};onSubmit=null;onCancel=null;onExit=null;pickerActive=!1;lastCtrlCTime=0;eventUnsubscribers=[];statusBarContext="";activeInsight=null;insightSnippetLines=0;insightDisplayed=!1;metaLearningEntries=[];constructor($,Z,Q="",Y){this.model=$;this.sessionName=Z;this.authInfo=Q;this.dataDir=Y;this.viewManager=new s1}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 jZ(Bq(this.dataDir,"history"));this.setupEventListeners(),E(U.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(W$.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(W$.on("status:update",($)=>{let Z=$.level==="error"?b.err:$.level==="warning"?b.prompt:$.level==="success"?b.sys:U.dim;if(this.lines.push({text:` ${Z}[${$.source}]${U.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(W$.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${b.prompt}\u26A0 ${$.message}${U.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${b.err}\u26A0 Rate limit: ${$.message}${U.reset}`});else this.lines.push({text:` ${U.dim}[telemetry] ${$.message}${U.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(W$.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${U.dim}[backup] ${$.message||"Backup concluido"}${U.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${b.sys}[pomodoro] ${$.message}${U.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${b.err}[${$.taskType}] ${$.message}${U.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(W$.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(W$.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(U.show),E(U.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=K5(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=K5(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 Q=Z,Y;switch($){case"read_file":if(Y=String(Q.path||""),Q.offset)Y+=`:${Q.offset}`;break;case"write_file":case"edit_file":Y=String(Q.path||"");break;case"search_files":if(Y=`/${Q.pattern||""}/`,Q.include)Y+=` (${Q.include})`;break;case"find_files":Y=String(Q.pattern||"");break;case"list_directory":Y=String(Q.path||".");break;case"run_command":if(Y=String(Q.command||""),Y.length>80)Y=Y.slice(0,77)+"...";break;default:{let J=JSON.stringify(Q);Y=J.length>80?J.slice(0,77)+"...":J}}this.lines.push({text:` ${b.tool}\u2699 ${$}${U.reset} ${U.dim}${Y}${U.reset}`}),this.renderMessages()}showToolResult($,Z){let Q=Z.split(`
|
|
505
|
+
`),Y=8,J=Q.slice(0,8);for(let X of J){let K=X.length>this.width-6?X.slice(0,this.width-9)+"...":X;this.lines.push({text:` ${U.dim}${K}${U.reset}`})}if(Q.length>8)this.lines.push({text:` ${U.dim}... (${Q.length-8} more lines)${U.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${b.prompt}? ${$}${U.reset} ${U.dim}[y]es / [n]o / [a]ll${U.reset}`}),this.renderAll(),new Promise((Z)=>{let Q=(Y)=>{let J=Y.toString().toLowerCase();if(J==="y"||J==="\r"||J===`
|
|
506
|
+
`)process.stdin.removeListener("data",Q),this.lines.push({text:` ${b.sys}approved${U.reset}`}),this.renderAll(),Z(!0);else if(J==="n"||J==="\x1B")process.stdin.removeListener("data",Q),this.lines.push({text:` ${b.err}rejected${U.reset}`}),this.renderAll(),Z(!1);else if(J==="a")process.stdin.removeListener("data",Q),this.lines.push({text:` ${b.sys}approved all for this session${U.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Q),setTimeout(()=>{process.stdin.removeListener("data",Q),this.lines.push({text:` ${U.dim}timeout \u2014 auto-rejected${U.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 Q=$.findIndex((H)=>H.isCurrent);if(Q<0)Q=0;let Y="",J=!1,X=()=>{if(!Y)return $;let H=Y.toLowerCase();return $.filter((z)=>z.name.toLowerCase().includes(H))},K=()=>{let B=this.height-2-2,W=X();if(Q>=W.length)Q=Math.max(0,W.length-1);let N=2,O=2,j=B-N-O,P=Math.max(1,j),_=0;if(W.length>P)_=Math.max(0,Q-Math.floor(P/2)),_=Math.min(_,W.length-P);let q$=W.slice(_,_+P);if(E(U.hide),E(U.to(3,1)),E(U.clearLine),J)E(` ${b.heading}${U.bold}Sessions${U.reset} ${U.dim}filter: ${Y}\u2588${U.reset}`);else E(` ${b.heading}${U.bold}Sessions${U.reset} ${U.dim}(${W.length})${U.reset}`);E(U.to(4,1)),E(U.clearLine);for(let v=0;v<P;v++){let a=2+N+v+1;if(E(U.to(a,1)),E(U.clearLine),v>=q$.length)continue;let R=q$[v],C=_+v===Q,F=R.isCurrent?"*":" ",L=R.isArchived?`${U.dim}[arch] ${U.reset}`:" ",x=`${R.messageCount} msgs`.padEnd(10),w=Nq(R.updated);if(C)E(` ${b.prompt}${U.bold}\u203A ${F} ${L}${b.prompt}${U.bold}${R.name.padEnd(20)}${U.reset} ${U.dim}${x} ${w}${U.reset}`);else{let u=R.isArchived?U.dim:b.sys;E(` ${F} ${L}${u}${R.name.padEnd(20)}${U.reset} ${U.dim}${x} ${w}${U.reset}`)}}for(let v=q$.length;v<P;v++){let a=2+N+v+1;E(U.to(a,1)),E(U.clearLine)}let $$=2+N+P+1;if(E(U.to($$,1)),E(U.clearLine),W.length>P){let v=Math.round((Q+1)/W.length*100);E(` ${U.dim}${_>0?"\u2191":" "} ${v}% ${_+P<W.length?"\u2193":" "}${U.reset}`)}let y=this.height-2;E(U.to(y,1)),E(U.clearLine),E(` ${U.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${U.reset}`)},V=(H)=>{this.pickerActive=!1,process.stdin.removeListener("data",G),this.renderAll(),Z(H)},G=(H)=>{let z=H.toString("utf-8"),B=X();if(z==="\x1B"&&H.length===1){if(J)J=!1,Y="",K();else V(null);return}if(z==="\x03"){V(null);return}if(z==="\r"||z===`
|
|
507
|
+
`){if(B.length>0&&Q<B.length)V({action:"load",name:B[Q].name});return}if(z==="\x1B[A"||z==="w"&&!J){if(Q>0)Q--,K();return}if(z==="\x1B[B"||z==="s"&&!J){if(Q<B.length-1)Q++,K();return}if(z==="d"&&J===!1){if(B.length>0&&Q<B.length){let W=B[Q];if(!W.isCurrent)V({action:"delete",name:W.name,isArchived:W.isArchived})}return}if(z==="a"&&J===!1){if(B.length>0&&Q<B.length){let W=B[Q];if(!W.isCurrent){let N=W.isArchived?"unarchive":"archive";V({action:N,name:W.name})}}return}if(z==="/"&&J===!1){J=!0,Y="",K();return}if(J){if(z==="\x7F"||z==="\b"){if(Y.length>0)Y=Y.slice(0,-1),Q=0,K();else J=!1,K();return}if(z.length===1&&z>=" "){Y+=z,Q=0,K();return}}};process.stdin.on("data",G),K()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Q=0,Y="",J=!1,X="",K=[...new Set($.map((W)=>W.category))].sort(),V=()=>{let W=X?$.filter((N)=>N.category===X):$;if(Y){let N=Y.toLowerCase();W=W.filter((O)=>O.title.toLowerCase().includes(N)||O.source.toLowerCase().includes(N))}return W},G=(W)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[W]||W},H=()=>{let O=this.height-2-2,j=V();if(Q>=j.length)Q=Math.max(0,j.length-1);let P=2,_=2,q$=O-P-_,$$=Math.max(1,q$),y=0;if(j.length>$$)y=Math.max(0,Q-Math.floor($$/2)),y=Math.min(y,j.length-$$);let v=j.slice(y,y+$$);if(E(U.hide),E(U.to(3,1)),E(U.clearLine),J)E(` ${b.heading}${U.bold}Noticias${U.reset} ${U.dim}filtro: ${Y}\u2588${U.reset}`);else{let q=X?G(X):"Todas";E(` ${b.heading}${U.bold}Noticias${U.reset} ${U.dim}(${j.length}) ${q}${U.reset}`)}E(U.to(4,1)),E(U.clearLine);for(let q=0;q<$$;q++){let C=2+P+q+1;if(E(U.to(C,1)),E(U.clearLine),q>=v.length)continue;let F=v[q],L=y+q===Q,x=F.time?`[${F.time}]`:" ",w=this.width-30,u=F.title.length>w?F.title.slice(0,w-1)+"\u2026":F.title;if(L)E(` ${b.prompt}${U.bold}\u203A ${x} ${u}${U.reset} ${U.dim}(${F.source})${U.reset}`);else E(` ${U.dim}${x}${U.reset} ${b.sys}${u}${U.reset} ${U.dim}(${F.source})${U.reset}`)}for(let q=v.length;q<$$;q++){let C=2+P+q+1;E(U.to(C,1)),E(U.clearLine)}let a=2+P+$$+1;if(E(U.to(a,1)),E(U.clearLine),j.length>$$){let q=Math.round((Q+1)/j.length*100);E(` ${U.dim}${y>0?"\u2191":" "} ${q}% ${y+$$<j.length?"\u2193":" "}${U.reset}`)}let R=this.height-2;E(U.to(R,1)),E(U.clearLine),E(` ${U.dim}\u2191\u2193 navegar Enter abrir Ctrl+Enter ler aqui Esc cancelar / filtrar Tab categoria${U.reset}`)},z=(W)=>{this.pickerActive=!1,process.stdin.removeListener("data",B),this.renderAll(),Z(W)},B=(W)=>{let N=W.toString("utf-8"),O=V();if(N==="\x1B"&&W.length===1){if(J)J=!1,Y="",H();else z(null);return}if(N==="\x03"){z(null);return}if(N===`
|
|
508
|
+
`||N==="\x1B\r"||N==="\x1BOM"){if(O.length>0&&Q<O.length)z({action:"read",link:O[Q].link});return}if(N==="\r"||N===`
|
|
509
|
+
`){if(O.length>0&&Q<O.length)z({action:"open",link:O[Q].link});return}if(N==="\x1B[A"||N==="w"&&!J){if(Q>0)Q--,H();return}if(N==="\x1B[B"||N==="s"&&!J){if(Q<O.length-1)Q++,H();return}if(N==="\t"){if(!X)X=K[0]||"";else{let j=K.indexOf(X);X=j<K.length-1?K[j+1]:""}Q=0,H();return}if(N==="/"&&!J){J=!0,Y="",H();return}if(J){if(N==="\x7F"||N==="\b"){if(Y.length>0)Y=Y.slice(0,-1),Q=0,H();else J=!1,H();return}if(N.length===1&&N>=" "){Y+=N,Q=0,H();return}}};process.stdin.on("data",B),H()})}showUsage($){this.lines.push({text:` ${U.dim}tokens: ${$}${U.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${b.err}\u2717 ${$}${U.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
|
|
510
|
+
`))this.lines.push({text:` ${b.sys}${Z}${U.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(U.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),H5(),this.render()}enterDashboardMode($){this.viewMode="dashboard";let Z=[...$.panels];if(!Z.some((Y)=>Y.id==="meta-learning")&&this.metaLearningEntries.length>0){let Y=Math.floor(this.width/2)-4,J=V5(this.metaLearningEntries,Y);Z=[...Z,J]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),G5(3,this.height-2),this.renderDashboard()}updateDashboardPanel($,Z){let Q=this.dashboardContent.find((Y)=>Y.id===$);if(Q){if(Q.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=IZ($,{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(U.hide);for(let Q=0;Q<$.length;Q++)E(U.to(Z+Q,1)),E(U.clearLine),E($[Q]);E(U.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;E(U.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)E(U.to($+Z,1)),E(U.clearLine);E(U.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(W$.emit("insight:accepted",Z),this.lines.push({text:` ${b.sys}\u2713 Dica aceita: ${$.title}${U.reset}`}),$.suggestedAction)this.lines.push({text:` ${U.dim}Executando: ${$.suggestedAction.command}${U.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=V5($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=RZ($),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((Q)=>Q.title===$.title))this.metaLearningEntries=this.metaLearningEntries.map((Q)=>Q.title===$.title?{...Q,frequency:Q.frequency+1,lastSeen:Date.now()}:Q);else this.metaLearningEntries=[...this.metaLearningEntries,{...$,frequency:1,lastSeen:Date.now()}]}renderDashboard(){E(U.hide),E(U.clear),this.renderHeader();let $=2,Z=2+(this.statusBarEnabled?1:0),Q=this.height-$-Z,Y=this.dashboardContent,J=Math.min(2,Y.length),X=Math.ceil(Y.length/J),K=1,V=Math.floor((this.width-K*(J+1))/J),G=Math.floor((Q-K*(X+1))/X),H=0;for(let z=0;z<X;z++)for(let B=0;B<J&&H<Y.length;B++){let W=Y[H],N=$+K+z*(G+K)+1,O=K+B*(V+K)+1;this.drawDashboardPanel(W,N,O,V,G),H++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(U.show)}drawDashboardPanel($,Z,Q,Y,J){let X=this.personaMode==="sharpen_or_relax"?this.palette.muted:U.dim,K=this.palette.primary,V=i1($.content.slice(0,J-2),Y,{title:$.title,borderColor:X,titleColor:K});for(let G=0;G<V.length&&G<J;G++)E(U.to(Z+G,Q)),E(V[G])}renderStickyStatusBar(){if(!this.statusBarEnabled)return;let $=this.height-2;this.stickyStatusRow=$;let Z=[];if(this.personaMode!=="productivity"){let Y=this.personaMode==="spillover_alert"?this.palette.accent:this.palette.primary;Z.push({label:"MODE",value:this.getPersonaLabel(),color:Y})}if(this.timeContext&&this.personaMode==="spillover_alert"){let Y=this.timeContext.urgentTasks.length+this.timeContext.overdueTasks.length+this.timeContext.pendingCommits.length;if(Y>0)Z.push({label:"PEND",value:String(Y),color:this.palette.accent})}let Q={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(U.to($,1)),E(this.renderPersonaAwareStatusBar(Q))}renderPersonaAwareStatusBar($){let Z=r1($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${S4(Z)}${U.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(E(U.hide),E(U.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),E(U.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){E(U.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();E(Z),E(U.inv);let Y=` smolerclaw${this.personaMode!=="productivity"?` [${this.getPersonaLabel()}]`:""}`,J=[this.model,this.sessionName];if(this.sessionCost)J.push(this.sessionCost);if(this.authInfo)J.push(this.authInfo);let X=J.join(" | ")+" ",K=Math.max(1,this.width-G$(Y)-X.length);E(Y+" ".repeat(K)+X),E(U.reset),E(U.to(2,1));let V=this.personaMode==="sharpen_or_relax"?this.palette.muted:U.dim;E(`${V}${"\u2500".repeat(this.width)}${U.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return U.bg(52);case"sharpen_or_relax":return U.bg(53)}}renderMessages(){let Q=2+(this.statusBarEnabled?1:0),Y=this.height-2-Q,J=[...this.lines,...this.streamLines],X=J.length,K=Math.max(0,X-Y-this.scrollOffset),V=Math.min(X,K+Y),G=J.slice(K,V);E(U.hide);for(let H=0;H<Y;H++)if(E(U.to(2+H+1,1)),E(U.clearLine),H<G.length)E(G[H].text)}completeInput($){let Z=$.split(" "),Q=Z[0];if(Z.length===1){let K=this.commands.filter((V)=>V.startsWith(Q));if(K.length===1){let V=this.subcommands[K[0]];if(V&&V.length>0)return{value:K[0]+" ",options:`Opcoes: ${V.join(" ")}`};return{value:K[0]+" "}}if(K.length>1){let V=K[0];for(let G of K)while(!G.startsWith(V))V=V.slice(0,-1);return{value:V.length>$.length?V:$,options:K.join(" ")}}return null}let Y=this.subcommands[Q];if(!Y||Y.length===0)return null;let J=Z[Z.length-1].toLowerCase(),X=Y.filter((K)=>K.toLowerCase().startsWith(J));if(X.length===1)return Z[Z.length-1]=X[0],{value:Z.join(" ")+" "};if(X.length>1){let K=X[0];for(let V of X)while(!V.toLowerCase().startsWith(K.toLowerCase()))K=K.slice(0,-1);if(K.length>J.length)return Z[Z.length-1]=K,{value:Z.join(" "),options:X.join(" ")};return{value:$,options:X.join(" ")}}if(!J&&Y.length>0)return{value:$,options:Y.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(E(U.to($,1)),E(U.clearLine),E(`${U.dim}${"\u2500".repeat(this.width)}${U.reset}`),E(U.to(Z,1)),E(U.clearLine),this.isStreaming){let Q=((Date.now()-this.streamStartTime)/1000).toFixed(1);E(` ${b.ai}${this.getSpinnerChar()}${U.reset} ${U.dim}streaming... ${Q}s${U.reset}`),E(U.hide)}else{let Q=G$(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;E(`${b.prompt}\u276F${U.reset} ${Q}`);let Y=this.inputBuf.slice(0,this.inputPos),J=G$(Y)+3;E(U.to(Z,Math.min(J,this.width))),E(U.show)}}onKey($){if(this.pickerActive)return;let Z=$.toString("utf-8");if(this.hasActiveInsight()){let Q=Z.toLowerCase();if(Q==="y"){this.acceptInsight();return}if(Q==="n"||Z==="\x1B"){this.dismissInsight();return}this.dismissInsight()}if(Z==="\x03"){if(this.isStreaming){this.onCancel?.();return}let Q=Date.now(),Y=1500;if(this.inputBuf.length>0){this.inputBuf="",this.inputPos=0,this.lastCtrlCTime=Q,this.renderInput();return}if(Q-this.lastCtrlCTime<Y){this.onExit?.();return}this.lastCtrlCTime=Q,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 Q=this.completeInput(this.inputBuf);if(Q){if(this.inputBuf=Q.value,this.inputPos=this.inputBuf.length,this.renderInput(),Q.options)this.showSystem(Q.options)}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!gY(Z)){let Q=Z.replace(/\r?\n/g," ").trim();if(Q.length>0)this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Q+this.inputBuf.slice(this.inputPos),this.inputPos+=Q.length,this.renderInput();return}if(Z==="\r"||Z===`
|
|
464
511
|
`){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
|
|
465
|
-
`,this.inputPos=this.inputBuf.length,this.renderInput();return}let
|
|
512
|
+
`,this.inputPos=this.inputBuf.length,this.renderInput();return}let Q=this.inputBuf.trim();if(Q)this.history?.add(Q),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(Q);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let Q=fY(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-Q)+this.inputBuf.slice(this.inputPos),this.inputPos-=Q,this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=fY(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=hY(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let Y=this.history?.prev(this.inputBuf);if(Y!==null&&Y!==void 0)this.inputBuf=Y,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let Y=this.history?.next();if(Y!==void 0)this.inputBuf=Y,this.inputPos=this.inputBuf.length,this.renderInput();break}case"5~":if(this.scrollOffset<this.lines.length)this.scrollOffset=Math.min(this.scrollOffset+5,this.lines.length),this.renderMessages();break;case"6~":if(this.scrollOffset>0)this.scrollOffset=Math.max(0,this.scrollOffset-5),this.renderMessages();break;case"H":this.inputPos=0,this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Y=hY(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Y),this.renderInput()}break}}return}if(Cq(Z))this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.renderInput()}onResize(){if(this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.viewManager.updateDimensions(this.width,this.height),this.viewMode==="dashboard")G5(3,this.height-2);else H5();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${b.user}${U.bold} You${U.reset} ${U.dim}${Z}${U.reset}`});else this.lines.push({text:`${b.ai}${U.bold} Claude${U.reset} ${U.dim}${Z}${U.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=w4(" "+$,this.width-2);for(let Q of Z)this.lines.push({text:Q})}addMarkdown($){let Z=K5($,this.width);for(let Q of Z)this.lines.push({text:Q})}}function gY($){return[...$].length===1}function Cq($){if(!gY($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function fY($,Z){if(Z<=0)return 0;if(Z>=2){let Q=$.charCodeAt(Z-1),Y=$.charCodeAt(Z-2);if(Q>=56320&&Q<=57343&&Y>=55296&&Y<=56319)return 2}return 1}function hY($,Z){if(Z>=$.length)return 0;let Q=$.charCodeAt(Z);if(Q>=55296&&Q<=56319&&Z+1<$.length)return 2;return 1}function Nq($){let Z=Date.now()-$,Q=Math.floor(Z/1000);if(Q<60)return"just now";let Y=Math.floor(Q/60);if(Y<60)return`${Y}m ago`;let J=Math.floor(Y/60);if(J<24)return`${J}h ago`;let X=Math.floor(J/24);if(X<30)return`${X}d ago`;return`${Math.floor(X/30)}mo ago`}var t1={"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}},Mq={input:3,output:15};function mY($,Z){let Q=Fq(Z),Y=$.inputTokens/1e6*Q.input*100,J=$.outputTokens/1e6*Q.output*100;return{inputCostCents:Y,outputCostCents:J,totalCostCents:Y+J}}function Fq($){if(t1[$])return t1[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return t1["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return t1["claude-opus-4-20250514"];if(Z.includes("sonnet"))return t1["claude-sonnet-4-20250514"];return Mq}class SZ{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=mY($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=mY($,this.model);return`${q5($.inputTokens)} in / ${q5($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${q5(this.totalInput)} in / ${q5(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function q5($){return $.toLocaleString("en-US")}function pY($,Z={}){let{includeToolCalls:Q=!0,includeTimestamps:Y=!0}=Z,J=[];J.push(`# smolerclaw session: ${$.name}`),J.push(`Created: ${new Date($.created).toLocaleString()}`),J.push(""),J.push("---"),J.push("");for(let X of $.messages){let K=Y?` (${new Date(X.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(X.role==="user")J.push(`## You${K}`),J.push(""),J.push(X.content),J.push("");else{if(J.push(`## Claude${K}`),J.push(""),J.push(X.content),Q&&X.toolCalls?.length){J.push("");for(let V of X.toolCalls){let G=Oq(V.name,V.input);J.push(`> **Tool:** \`${V.name}\`${G}`);let H=V.result.split(`
|
|
466
513
|
`).slice(0,5).join(`
|
|
467
|
-
`);if(H.trim()){
|
|
468
|
-
`))
|
|
469
|
-
`)}function
|
|
470
|
-
`)}function
|
|
471
|
-
`)}class
|
|
472
|
-
`);V=
|
|
514
|
+
`);if(H.trim()){J.push("> ```");for(let z of H.split(`
|
|
515
|
+
`))J.push(`> ${z}`);J.push("> ```")}}}if(X.usage)J.push(""),J.push(`*Tokens: ${X.usage.inputTokens} in / ${X.usage.outputTokens} out (~$${(X.usage.costCents/100).toFixed(4)})*`);J.push("")}J.push("---"),J.push("")}return J.join(`
|
|
516
|
+
`)}function Oq($,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""}}var U5=[{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 wZ($){let Z=U5.find((X)=>X.id===$);if(Z)return Z.id;let Q=$.toLowerCase(),Y=U5.find((X)=>X.alias===Q);if(Y)return Y.id;let J=U5.find((X)=>X.id.includes(Q)||X.name.toLowerCase().includes(Q));if(J)return J.id;return $}function cY($){let Z=["Available models:"];for(let Q of U5){let Y=Q.id===$?" *":" ",J=Q.tier==="fast"?"\u26A1":Q.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${Y} ${Q.alias.padEnd(12)} ${J} ${Q.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
|
|
517
|
+
`)}function kZ($){if($.includes(":")){let[Q,...Y]=$.split(":");return{provider:Q.toLowerCase(),model:Y.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 Rq={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 uY(){let $=["Providers:"];for(let[Z,Q]of Object.entries(Rq)){let Y=Q.envKey?` (${Q.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${Q.description}${Y}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
|
|
518
|
+
`)}class yZ{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,Q){if(this.name=$,this.model=Z,this.maxTokens=Q,$==="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,Q=!0){if(!this.apiKey&&this.name!=="ollama"){yield{type:"error",error:"No API key found. Set OPENAI_API_KEY env var."};return}let Y=[{role:"system",content:Z},...$.map((J)=>({role:J.role,content:J.content}))];try{let J=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:Y,max_tokens:this.maxTokens,stream:!0})});if(!J.ok){let z=await J.text();yield{type:"error",error:`${this.name} API error ${J.status}: ${z.slice(0,200)}`};return}if(!J.body){yield{type:"error",error:"No response body"};return}let X=J.body.getReader(),K=new TextDecoder,V="",G=Z.length+$.reduce((z,B)=>z+B.content.length,0),H=0;while(!0){let{done:z,value:B}=await X.read();if(z)break;V+=K.decode(B,{stream:!0});let W=V.split(`
|
|
519
|
+
`);V=W.pop()||"";for(let N of W){if(!N.startsWith("data: "))continue;let O=N.slice(6).trim();if(O==="[DONE]")continue;try{let P=JSON.parse(O).choices?.[0]?.delta;if(P?.content)yield{type:"text",text:P.content},H+=P.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(G/3.5),outputTokens:Math.ceil(H/3.5)},yield{type:"done"}}catch(J){yield{type:"error",error:J instanceof Error?J.message:String(J)}}}}async function $8(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Q,Y]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),J=await Z.exited;return{stdout:Q.trim(),stderr:Y.trim(),ok:J===0}}async function dY(){let $=await $8("git","diff","--cached"),Z=await $8("git","diff"),Q=await $8("git","ls-files","--others","--exclude-standard"),Y=[];if($.stdout)Y.push(`=== STAGED ===
|
|
473
520
|
`+$.stdout);if(Z.stdout)Y.push(`=== UNSTAGED ===
|
|
474
|
-
`+Z.stdout);if(
|
|
475
|
-
`+
|
|
521
|
+
`+Z.stdout);if(Q.stdout)Y.push(`=== UNTRACKED ===
|
|
522
|
+
`+Q.stdout);return Y.join(`
|
|
476
523
|
|
|
477
|
-
`)||"(no changes)"}async function
|
|
524
|
+
`)||"(no changes)"}async function lY(){let $=await $8("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function oY(){return(await $8("git","add","-A")).ok}async function aY($){let Z=await $8("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function nY(){let $=await $8("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var rY={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.
|
|
478
525
|
|
|
479
526
|
Behavior:
|
|
480
527
|
- Write clean, production-grade code. No shortcuts.
|
|
@@ -505,108 +552,121 @@ Behavior:
|
|
|
505
552
|
- Be specific. Show the line, explain the problem, suggest the fix.
|
|
506
553
|
- Check for: error handling, input validation, edge cases, naming, complexity.
|
|
507
554
|
- Don't nitpick formatting unless it affects readability.
|
|
508
|
-
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function
|
|
509
|
-
`)}
|
|
510
|
-
Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${
|
|
511
|
-
\u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${
|
|
512
|
-
Modo: Sharpen or Relax`}}function
|
|
513
|
-
--- Tarefas Atrasadas ---`);for(let
|
|
514
|
-
--- Tarefas Urgentes (Hoje) ---`);for(let
|
|
515
|
-
--- Git Pendente ---`);for(let
|
|
516
|
-
`)}function
|
|
555
|
+
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function iY($){return rY[$.toLowerCase()]||null}function sY($){let Z=["Personas:"];for(let[Q,Y]of Object.entries(rY)){let J=Q===$?" *":" ";Z.push(`${J} ${Q.padEnd(12)} ${Y.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
|
|
556
|
+
`)}Z$();async function tY($){try{let Z=A?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:Z2?["pbcopy"]:["xclip","-selection","clipboard"],Q=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return Q.stdin.write($),Q.stdin.end(),await Q.exited===0}catch{return!1}}import{existsSync as eY,readFileSync as $J,statSync as ZJ}from"fs";import{basename as Eq,extname as QJ,resolve as YJ}from"path";var JJ=new Set([".png",".jpg",".jpeg",".gif",".webp"]),Lq=20971520,jq=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"]),Dq=1048576;function XJ($){let Z=[],Q=$.split(/\s+/),Y=[];for(let J of Q){let X=J.replace(/^["']|["']$/g,""),K=QJ(X).toLowerCase();if(JJ.has(K)){let V=YJ(X);if(eY(V))try{if(ZJ(V).size>Lq){Y.push(`[image too large: ${X}]`);continue}let z=$J(V).toString("base64"),B=Pq(K);Z.push({path:V,mediaType:B,base64:z}),Y.push(`[image: ${X}]`)}catch{Y.push(J)}else Y.push(J)}else Y.push(J)}return{text:Y.join(" "),images:Z}}function Pq($){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 KJ($){let Z=[],Q=$.split(/\s+/),Y=[];for(let J of Q){let X=J.replace(/^["']|["']$/g,""),K=QJ(X).toLowerCase();if(JJ.has(K)){Y.push(J);continue}if(!(jq.has(K)||(X.includes("/")||X.includes("\\"))&&K.length>0)){Y.push(J);continue}let G=YJ(X);if(!eY(G)){Y.push(J);continue}try{let H=ZJ(G);if(!H.isFile()){Y.push(J);continue}if(H.size>Dq){Y.push(`[file too large: ${X} (${(H.size/1024).toFixed(0)}KB)]`);continue}if(H.size===0){Y.push(`[empty file: ${X}]`);continue}let z=$J(G,"utf-8"),B=Eq(G);Z.push({path:G,name:B,content:z,size:H.size}),Y.push(`[file: ${B}]`)}catch{Y.push(J)}}return{text:Y.join(" "),files:Z}}d4();d4();import{existsSync as zJ,readFileSync as Tq}from"fs";import{join as VJ}from"path";Z$();function Aq(){let $=new Date().getDay();return $===0||$===6}function Iq(){return Aq()?"weekend":"weekday"}async function xq($){let Z=[],Q=[],Y=[],J=new Date,X=new Date(J);X.setHours(23,59,59,999);let K=VJ($,"tasks.json");if(zJ(K))try{let H=JSON.parse(Tq(K,"utf-8"));for(let z of H){if(z.done)continue;if(z.dueAt){let B=new Date(z.dueAt),W=B<J,N=!W&&B<=X;if(W)Q.push({id:z.id,title:z.title,dueAt:z.dueAt,isOverdue:!0});else if(N)Z.push({id:z.id,title:z.title,dueAt:z.dueAt,isOverdue:!1})}}}catch{}let V=D8(!0);for(let H of V.slice(0,5)){let z=await Sq(H);if(z)Y.push(z)}return{hasSpillover:Z.length>0||Q.length>0||Y.length>0,urgentTasks:Z,overdueTasks:Q,pendingCommits:Y}}async function Sq($){if(!zJ(VJ($.path,".git")))return null;try{let Z=Bun.spawn(["git","status","--porcelain"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),Q=await new Response(Z.stdout).text();await Z.exited;let Y=Q.trim().length>0,J=Bun.spawn(["git","rev-list","--count","@{u}..HEAD"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),X=await new Response(J.stdout).text(),V=await J.exited===0?parseInt(X.trim())||0:0;if(Y||V>0)return{projectName:$.name,projectPath:$.path,uncommittedChanges:Y,unpushedCommits:V}}catch{}return null}function wq($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function W5($){let Z=Iq(),Q=await xq($),Y=wq(Z,Q.hasSpillover);return{dayType:Z,workloadState:Q.hasSpillover?"spillover":"clear",persona:Y,urgentTasks:Q.urgentTasks,overdueTasks:Q.overdueTasks,pendingCommits:Q.pendingCommits}}function kq($){let Q=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Q}
|
|
557
|
+
Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${Q}
|
|
558
|
+
\u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${Q}
|
|
559
|
+
Modo: Sharpen or Relax`}}function yq($){let Z=[];if($.overdueTasks.length>0){Z.push(`
|
|
560
|
+
--- Tarefas Atrasadas ---`);for(let Q of $.overdueTasks.slice(0,5)){let Y=Q.dueAt?new Date(Q.dueAt).toLocaleDateString("pt-BR"):"";Z.push(` \u26A0 ${Q.title} (venceu ${Y})`)}}if($.urgentTasks.length>0){Z.push(`
|
|
561
|
+
--- Tarefas Urgentes (Hoje) ---`);for(let Q of $.urgentTasks.slice(0,5)){let Y=Q.dueAt?new Date(Q.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";Z.push(` ! ${Q.title} (${Y})`)}}if($.pendingCommits.length>0){Z.push(`
|
|
562
|
+
--- Git Pendente ---`);for(let Q of $.pendingCommits){let Y=[];if(Q.uncommittedChanges)Y.push("uncommitted");if(Q.unpushedCommits>0)Y.push(`${Q.unpushedCommits} unpushed`);Z.push(` ${Q.projectName}: ${Y.join(", ")}`)}}return Z.join(`
|
|
563
|
+
`)}function bq($){if($.persona!=="sharpen_or_relax")return"";return`
|
|
517
564
|
--- Fim de Semana Livre ---
|
|
518
565
|
|
|
519
566
|
[A] Amolar o Machado
|
|
520
567
|
Estudo de arquitetura, refatoracao, melhoria do CLI
|
|
521
568
|
|
|
522
569
|
[B] Descompressao Criativa
|
|
523
|
-
Projetos paralelos sem prazo, foco pessoal/familia`}function
|
|
570
|
+
Projetos paralelos sem prazo, foco pessoal/familia`}function _q($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
|
|
524
571
|
--- Sugestao: Timebox ---
|
|
525
572
|
Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
|
|
526
|
-
Depois: descanso merecido.`}async function
|
|
573
|
+
Depois: descanso merecido.`}async function GJ($){let Z=[],Q=null;if($)Q=await W5($),Z.push(kq(Q));else Z.push("=== BRIEFING DIARIO ===");let Y=await u4();if(Z.push(Y),Q&&Q.workloadState==="spillover"){let X=yq(Q);if(X)Z.push(X);let K=_q(Q);if(K)Z.push(K)}if(Q){let X=bq(Q);if(X)Z.push(X)}if(A)try{let X=await h$();Z.push(`
|
|
527
574
|
--- Agenda ---
|
|
528
575
|
${X}`)}catch{Z.push(`
|
|
529
576
|
--- Agenda ---
|
|
530
|
-
Outlook nao disponivel.`)}if(
|
|
577
|
+
Outlook nao disponivel.`)}if(A)try{let X=await c4();Z.push(`
|
|
531
578
|
--- Sistema ---
|
|
532
|
-
${X}`)}catch{}let Q
|
|
579
|
+
${X}`)}catch{}let J=Q?.persona==="sharpen_or_relax"?2:3;try{let X=await E4(["finance","business","tech"],J);Z.push(`
|
|
533
580
|
${X}`)}catch{Z.push(`
|
|
534
581
|
--- Noticias ---
|
|
535
582
|
Falha ao carregar noticias.`)}return Z.push(`
|
|
536
583
|
======================`),Z.join(`
|
|
537
|
-
`)}
|
|
538
|
-
`);let Y=await
|
|
539
|
-
--- Tarefas do dia ---`),$.push(
|
|
540
|
-
--- Follow-ups pendentes ---`),$.push(
|
|
541
|
-
--- Delegacoes atrasadas ---`),$.push(
|
|
542
|
-
${H}`);if(
|
|
543
|
-
--- Agenda ---`),$.push(
|
|
544
|
-
`+
|
|
584
|
+
`)}d4();import{existsSync as vq,readFileSync as fq,writeFileSync as hq}from"fs";import{join as gq}from"path";Z$();var HJ="",qJ=()=>gq(HJ,"last-morning.txt");function UJ($){HJ=$;let Z=qJ(),Q=new Date().toISOString().split("T")[0];if(!vq(Z))return!0;try{return fq(Z,"utf-8").trim()!==Q}catch{return!0}}function WJ(){let $=new Date().toISOString().split("T")[0];hq(qJ(),$)}async function BJ(){let $=[],Z=new Date().getHours(),Q=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Q}! Briefing do dia`),$.push(`==============================
|
|
585
|
+
`);let Y=await u4();$.push(Y);let X=e$().filter((B)=>{if(!B.dueAt)return!1;let W=new Date(B.dueAt),N=new Date;return W.toDateString()===N.toDateString()});if(X.length>0)$.push(`
|
|
586
|
+
--- Tarefas do dia ---`),$.push(l4(X));let K=O8();if(K.length>0)$.push(`
|
|
587
|
+
--- Follow-ups pendentes ---`),$.push(x7(K));let G=n4().filter((B)=>B.status==="atrasado");if(G.length>0)$.push(`
|
|
588
|
+
--- Delegacoes atrasadas ---`),$.push(I7(G));let H=s7();if(H)$.push(`
|
|
589
|
+
${H}`);if(A)try{let B=await h$();$.push(`
|
|
590
|
+
--- Agenda ---`),$.push(B)}catch{}try{let B=await E4(["finance","business","tech"],2);$.push(`
|
|
591
|
+
`+B)}catch{}let z=e$();if(z.length>0&&X.length!==z.length)$.push(`
|
|
545
592
|
${z.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
|
|
546
593
|
==============================`),$.join(`
|
|
547
|
-
`)}
|
|
594
|
+
`)}Z$();d$();var m=null,B5=null,bZ=null,_Z=0;function MJ($){bZ=$}function FJ($="foco",Z=25,Q=5){if(m)return`Pomodoro ja ativo: "${m.label}" (${EJ()}). Use /pomodoro stop para parar.`;return m={startedAt:Date.now(),durationMs:Z*60000,breakMs:Q*60000,label:$,type:"work"},_Z++,RJ(),`Pomodoro #${_Z} iniciado: "${$}" (${Z}min trabalho / ${Q}min pausa)`}function OJ(){if(!m)return"Nenhum pomodoro ativo.";let $=m.label,Z=Math.floor((Date.now()-m.startedAt)/60000);return C5(),m=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function vZ(){if(!m)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=EJ();return`${m.type==="work"?"Trabalhando":"Pausa"}: "${m.label}" \u2014 ${$} restante(s) (ciclo #${_Z})`}function RJ(){if(!m)return;C5();let $=m.startedAt+m.durationMs-Date.now();if($<=0){CJ();return}B5=setTimeout(CJ,$)}function CJ(){if(!m)return;if(m.type==="work"){let $=`Pomodoro: "${m.label}" concluido! Hora da pausa (${m.breakMs/60000}min).`;NJ("Pausa!",`"${m.label}" concluido. Descanse ${m.breakMs/60000} minutos.`),bZ?.($),m={...m,type:"break",startedAt:Date.now(),durationMs:m.breakMs},RJ()}else NJ("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),bZ?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),C5(),m=null}function C5(){if(B5)clearTimeout(B5),B5=null}function EJ(){if(!m)return"0min";let $=Math.max(0,m.startedAt+m.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function NJ($,Z){if(!A)return;try{await H4($,Z,{timeout:1e4})}catch{}}function LJ(){C5(),m=null}n();d4();Z$();d$();import{existsSync as jJ,mkdirSync as mq,readFileSync as pq}from"fs";import{join as cq}from"path";import{randomUUID as uq}from"crypto";var DJ="",H$=[],PJ=()=>cq(DJ,"workflows.json");function e1(){S(PJ(),JSON.stringify(H$,null,2))}function dq(){let $=PJ();if(!jJ($)){H$=fZ(),e1();return}try{let Z=JSON.parse(pq($,"utf-8"));if(!Array.isArray(Z)){H$=fZ(),e1();return}H$=Z.map((Q)=>({id:Q.id||hZ(),name:Q.name||"unnamed",description:Q.description||"",steps:Array.isArray(Q.steps)?Q.steps:[],tags:Array.isArray(Q.tags)?Q.tags:[],enabled:Q.enabled!==!1,createdAt:Q.createdAt||new Date().toISOString(),updatedAt:Q.updatedAt||new Date().toISOString()}))}catch{H$=fZ(),e1()}}function fZ(){let $=new Date().toISOString();return[{id:hZ(),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:hZ(),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 TJ($){if(DJ=$,!jJ($))mq($,{recursive:!0});dq()}function $0($){let Z=$.toLowerCase().trim();return H$.find((Q)=>Q.id===$)||H$.find((Q)=>Q.name.toLowerCase()===Z)||H$.find((Q)=>Q.name.toLowerCase().includes(Z))||null}function AJ($){let Z=[...H$];if($){let Q=$.toLowerCase();Z=Z.filter((Y)=>Y.tags.some((J)=>J.toLowerCase()===Q))}return Z}function gZ($,Z){let Q=$0($);if(!Q)return null;return H$=H$.map((Y)=>Y.id===Q.id?{...Y,...Z,updatedAt:new Date().toISOString()}:Y),e1(),H$.find((Y)=>Y.id===Q.id)||null}function IJ($){let Z=$0($);if(!Z)return!1;return H$=H$.filter((Q)=>Q.id!==Z.id),e1(),!0}async function mZ($,Z){let Q=$0($);if(!Q){let J=H$.map((X)=>X.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${J}`}if(!Q.enabled)return`Workflow "${Q.name}" esta desativado.`;let Y=await xJ(Q.name,Q.steps,Z);return oq(Y)}async function xJ($,Z,Q){let Y=performance.now(),J=[`Executando workflow: "${$}"`],X=0,K=0,V=0,G=!0;for(let H=0;H<Z.length;H++){let z=Z[H],B=z.label||`${z.action}:${z.target}`,W=`[${H+1}/${Z.length}]`,N=z.on_error||"continue";Q?.(`${W} ${B}...`);try{let O=await lq(z,Q);J.push(` ${W} ${O}`),X++}catch(O){let j=O instanceof Error?O.message:String(O);switch(V++,N){case"stop":return J.push(` ${W} ERRO (parando): ${j}`),G=!1,{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:J,duration:Math.round(performance.now()-Y)};case"skip":J.push(` ${W} ERRO (pulado): ${j}`),K++;break;case"continue":default:J.push(` ${W} ERRO (continuando): ${j}`);break}}}return{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:J,duration:Math.round(performance.now()-Y)}}async function lq($,Z){switch($.action){case"open_app":{if(!A)return`skip: ${$.target} (not Windows)`;return await m4($.target)}case"open_url":{if(!A)return`skip: ${$.target} (not Windows)`;let Q=$.target.trim();if(!Q.startsWith("http://")&&!Q.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Q}`);return await p4(Q)}case"run_command":{if(!A)return"skip: command (not Windows)";let Q=$.target;if(!Q.trim())throw Error("Comando vazio");let Y=await U$(Q,{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 J=Y.stdout.trim().slice(0,200);return`Command: ${Q.slice(0,60)}${J?" -> "+J:""}`}case"wait":{let Q=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Y)=>setTimeout(Y,Q*1000)),`Wait: ${Q}s`}case"notify":{if(A)try{H4("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!A)return"skip: condition (not Windows)";let Q=$.target.toLowerCase(),Y=await z0(Q,{timeout:5000});if(Y&&$.condition_steps&&$.condition_steps.length>0){let J=await xJ(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${Q} running=true, ran ${J.stepsRun} sub-steps`}return`Condition: ${Q} running=${Y}${!Y?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function SJ($){let Z=$||H$;if(Z.length===0)return"Nenhum workflow configurado.";let Q=Z.map((Y)=>{let J=Y.enabled?"":" [DESATIVADO]",X=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"",K=Y.steps.map((V)=>{let G=V.label||V.target;return V.action==="wait"?`${V.target}s`:G}).join(" -> ");return` ${Y.name}${J}${X} \u2014 ${Y.description}
|
|
548
595
|
${" ".repeat(4)}${K} {${Y.id}}`});return`Workflows (${Z.length}):
|
|
549
|
-
${
|
|
596
|
+
${Q.join(`
|
|
550
597
|
|
|
551
|
-
`)}`}function
|
|
552
|
-
`)}function
|
|
553
|
-
`)}function
|
|
598
|
+
`)}`}function wJ($){let Z=$.enabled?"ativo":"desativado",Q=$.tags.length>0?`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`:"",Y=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(Q)Y.push(Q);return Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(""),Y.push("Steps:"),$.steps.forEach((J,X)=>{let K=J.label?` (${J.label})`:"",V=J.on_error&&J.on_error!=="continue"?` [on_error: ${J.on_error}]`:"";if(Y.push(` ${X+1}. ${J.action}: ${J.target}${K}${V}`),J.action==="if_app_running"&&J.condition_steps)for(let G of J.condition_steps)Y.push(` \u21B3 ${G.action}: ${G.target}`)}),Y.join(`
|
|
599
|
+
`)}function oq($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
|
|
600
|
+
`)}function hZ(){return uq().slice(0,8)}Z$();d$();var _$=new Map,pZ=null;function yJ($){pZ=$}function bJ($,Z=60){if(!A)return"Error: monitor is only available on Windows.";let Q=$.toLowerCase();if(_$.has(Q))return`"${$}" ja esta sendo monitorado.`;let Y=setInterval(()=>kJ(Q),Z*1000);return _$.set(Q,{name:$,interval:Y,lastSeen:!0}),kJ(Q),`Monitorando "${$}" a cada ${Z}s.`}function _J($){let Z=$.toLowerCase(),Q=_$.get(Z);if(!Q)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Q.interval),_$.delete(Z),`Monitor parado: "${$}"`}function vJ(){if(_$.size===0)return"Nenhum processo monitorado.";let $=[..._$.values()].map((Z)=>{let Q=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Q}]`});return`Processos monitorados (${_$.size}):
|
|
554
601
|
${$.join(`
|
|
555
|
-
`)}`}function
|
|
602
|
+
`)}`}function fJ(){for(let $ of _$.values())clearInterval($.interval);_$.clear()}async function kJ($){let Z=_$.get($);if(!Z)return;let Q=await z0(Z.name,{timeout:1e4});if(Z.lastSeen&&!Q){let Y=`ALERTA: "${Z.name}" parou de rodar!`;H4("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),pZ?.(Y)}else if(!Z.lastSeen&&Q){let Y=`"${Z.name}" voltou a rodar.`;pZ?.(Y)}_$.set($,{...Z,lastSeen:Q})}h1();n();import{writeFileSync as aq}from"fs";import{join as nq}from"path";async function rq(){let $=uZ(process.argv.slice(2));if($.help)dZ(),process.exit(0);if($.version)console.log(`smolerclaw v${Y0()}`),process.exit(0);let Z=N2();if($.model)Z.model=wZ($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Q;try{Q=I5()}catch(O){console.error("smolerclaw:",O instanceof Error?O.message:O),process.exit(1)}let{provider:Y,model:J}=kZ(Z.model),X;if(Y==="openai"||Y==="ollama")X=new yZ(Y,J,Z.maxTokens);else{let O=new BZ(Q.token,Z.model,Z.maxTokens,Z.toolApproval);O.setAuthRefresh(()=>{let j=x5();if(j&&j.token!==Q.token)return Q=j,O.updateApiKey(j.token),!0;return!1}),X=O}let K=new NZ(Z.dataDir),V=$.session||K.getLastSession()||"default";if(V!=="default")K.switchTo(V);let G=yY(Z.skillsDir),H=OZ(Z.systemPrompt,G,Z.language),z=!$.noTools;WY();let B=O6(nq(Z.dataDir,"..")),W=C6(B);if(W.length>0)HY(W),p.push(...N6(W));let N=!process.stdin.isTTY;if($.print||N)await iq(X,K,H,z,$.prompt,N),process.exit(0);await tq(X,K,Z,Q,G,H,z,W,$.prompt)}async function iq($,Z,Q,Y,J,X){let K=J||"";if(X){let z=await sq();K=K?`${K}
|
|
556
603
|
|
|
557
|
-
${z}`:z}if(!K.trim())console.error("smolerclaw: no input provided"),process.exit(1);let V={role:"user",content:K.trim(),timestamp:Date.now()};Z.addMessage(V);let G="";for await(let z of $.chat(Z.messages,
|
|
604
|
+
${z}`:z}if(!K.trim())console.error("smolerclaw: no input provided"),process.exit(1);let V={role:"user",content:K.trim(),timestamp:Date.now()};Z.addMessage(V);let G="";for await(let z of $.chat(Z.messages,Q,Y))if(z.type==="text")process.stdout.write(z.text),G+=z.text;else if(z.type==="error")console.error(`
|
|
558
605
|
smolerclaw error: ${z.error}`);if(G&&!G.endsWith(`
|
|
559
606
|
`))process.stdout.write(`
|
|
560
|
-
`);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function
|
|
607
|
+
`);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function sq(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function tq($,Z,Q,Y,J,X,K,V,G){let H=new SZ(Q.model),z=new xZ(Q.model,Z.session.name,F2(Y),Q.dataDir),B="default",W=x3(),N=W?`${X}
|
|
561
608
|
|
|
562
|
-
${
|
|
609
|
+
${W}`:X;U2(Q.dataDir,A5().replace(/[/\\]config\.json$/,"")),M3(Q.dataDir),g6(Q.dataDir),P3(Q.dataDir),P6(Q.dataDir),UY(Z),Q3(Q.dataDir),K3(Q.dataDir),MJ((y)=>z.showSystem(`
|
|
563
610
|
*** ${y} ***
|
|
564
|
-
`)),
|
|
611
|
+
`)),TJ(Q.dataDir),L9(Q.dataDir),_3(Q.dataDir),u3(Q.dataDir),t3(Q.dataDir),MQ(Q.dataDir),_Q(Q.dataDir,(y)=>{z.showSystem(`
|
|
565
612
|
*** Meta-Insight: ${y.title} ***
|
|
566
613
|
${y.recommendation}
|
|
567
|
-
`)}),
|
|
614
|
+
`)}),yJ((y)=>z.showSystem(`
|
|
568
615
|
*** ${y} ***
|
|
569
|
-
`)),
|
|
616
|
+
`)),a6(Q.dataDir,(y)=>z.showSystem(`
|
|
617
|
+
*** ${y} ***
|
|
618
|
+
`)),w6(Q.dataDir,(y)=>{z.showSystem(`
|
|
570
619
|
*** LEMBRETE: ${y.title} ***
|
|
571
|
-
`)});let O=null;try{O=await
|
|
572
|
-
${
|
|
620
|
+
`)});let O=null;try{O=await W5(Q.dataDir),z.setTimeContext(O)}catch{z.setPersonaMode("productivity")}if(Q.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(y,v,a)=>{if(y==="edit_file"&&v.old_text&&v.new_text){let C=DY(String(v.old_text),String(v.new_text));for(let F of C)z.showSystem(F)}let R=jY(y,v),q=await z.promptApproval(R);if(z._approveAllRequested)$.setAutoApproveAll?.(!0),z._approveAllRequested=!1;return q});for(let y of Z.messages)if(y.role==="user")z.addUserMessage(y.content);else z.addAssistantMessage(y.content);let j=null;async function P(y){if(y.startsWith("/")){await _(y);return}if(Q.maxSessionCost>0){let g=H.totals.costCents;if(g>=Q.maxSessionCost){z.showError(`Budget exceeded (~$${(g/100).toFixed(4)} / $${(Q.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(g>=Q.maxSessionCost*0.8)z.showSystem(`Budget: ${Math.round(g/Q.maxSessionCost*100)}% used`)}let{text:v,images:a}=XJ(y),{text:R,files:q}=KJ(v),C=R;if(q.length>0)C=`${q.map((Z0)=>`<file name="${Z0.name}" path="${Z0.path}" size="${Z0.size}">
|
|
621
|
+
${Z0.content}
|
|
573
622
|
</file>`).join(`
|
|
574
623
|
|
|
575
624
|
`)}
|
|
576
625
|
|
|
577
|
-
${
|
|
578
|
-
${
|
|
579
|
-
`)}`);break}case"model":case"modelo":{let q=
|
|
626
|
+
${R}`;let F={role:"user",content:C,images:a.length>0?a.map((g)=>({mediaType:g.mediaType,base64:g.base64})):void 0,files:q.length>0?q:void 0,timestamp:Date.now()};Z.addMessage(F);let L=[];if(a.length>0)L.push(`${a.length} image${a.length>1?"s":""}`);if(q.length>0)L.push(`${q.length} file${q.length>1?"s":""}`);let x=L.length>0?`${R} (${L.join(", ")})`:R;z.addUserMessage(x),z.disableInput(),z.startStream();let w="",u=[],s={},w$=0,h=0;j=new AbortController;try{for await(let g of $.chat(Z.messages,N,K)){if(j.signal.aborted)break;switch(g.type){case"text":z.appendStream(g.text),w+=g.text;break;case"tool_call":z.flushStream(),z.showToolCall(g.name,g.input),s=g.input;break;case"tool_result":z.showToolResult(g.name,g.result),u.push({id:g.id,name:g.name,input:s,result:g.result}),s={},z.resetStreamBuffer();break;case"tool_blocked":z.showError(g.reason);break;case"usage":w$+=g.inputTokens,h+=g.outputTokens;break;case"error":z.showError(g.error);break;case"done":break}}}catch(g){if(!j.signal.aborted)z.showError(g instanceof Error?g.message:String(g))}j=null,z.endStream();let k$={inputTokens:w$,outputTokens:h},p$=H.add(k$);if(w$>0||h>0)z.showUsage(H.formatUsage(k$)),z.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let c$={role:"assistant",content:w,toolCalls:u.length>0?u:void 0,usage:w$>0?{inputTokens:w$,outputTokens:h,costCents:p$.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(c$),Z.trimHistory(Q.maxHistory),z.enableInput()}async function _(y){let v=y.slice(1).split(" "),a=v[0].toLowerCase(),R=v.slice(1);switch(a){case"exit":case"quit":case"sair":case"q":q$();break;case"clear":case"limpar":Z.clear(),z.clearMessages(),z.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let q=R[0]||`s-${Date.now()}`;Z.switchTo(q),z.clearMessages(),z.updateSession(q),z.showSystem(`New session: ${q}`);break}case"load":case"carregar":{let q=R[0];if(!q){z.showError("Usage: /load <name>");break}Z.switchTo(q),z.clearMessages();for(let C of Z.messages)if(C.role==="user")z.addUserMessage(C.content);else z.addAssistantMessage(C.content);z.updateSession(q),z.showSystem(`Loaded: ${q}`);break}case"sessions":case"sessoes":case"ls":{let q=Z.list().map((L)=>{let x=Z.getInfo(L);return{name:L,messageCount:x?.messageCount??0,updated:x?.updated??0,isCurrent:L===Z.session.name,isArchived:!1}}),C=Z.listArchived().map((L)=>{let x=Z.getArchivedInfo(L);return{name:L,messageCount:x?.messageCount??0,updated:x?.updated??0,isCurrent:!1,isArchived:!0}}),F=await z.promptSessionPicker([...q,...C]);if(F)switch(F.action){case"load":{let L=F.name;if(C.some((w)=>w.name===L))Z.unarchive(L);Z.switchTo(L),z.clearMessages();for(let w of Z.messages)if(w.role==="user")z.addUserMessage(w.content);else z.addAssistantMessage(w.content);z.updateSession(L),z.showSystem(`Loaded: ${L}`);break}case"delete":{let L=F.name;if(F.isArchived?Z.deleteArchived(L):Z.delete(L))z.showSystem(`Deleted: ${L}`);else z.showError(`Not found: ${L}`);break}case"archive":if(Z.archive(F.name))z.showSystem(`Archived: ${F.name}`);else z.showError(`Failed to archive: ${F.name}`);break;case"unarchive":if(Z.unarchive(F.name))z.showSystem(`Restored: ${F.name}`);else z.showError(`Not found in archive: ${F.name}`);break}break}case"delete":case"deletar":case"rm":{let q=R[0];if(!q){z.showError("Usage: /delete <name>");break}if(Z.delete(q))z.showSystem(`Deleted: ${q}`);else z.showError(`Session not found: ${q}`);break}case"archive":case"arquivar":{let q=R[0];if(!q){z.showError("Uso: /archive <nome> ou /archive all");break}if(q==="all"||q==="todas"){let C=Z.archiveAll();if(C.length>0)z.showSystem(`Arquivadas ${C.length} sessoes: ${C.join(", ")}`);else z.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.archive(q))z.showSystem(`Sessao arquivada: "${q}"`);else z.showError(`Falha ao arquivar "${q}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let q=R[0];if(!q){z.showError("Uso: /unarchive <nome>");break}if(Z.unarchive(q))z.showSystem(`Sessao restaurada: "${q}"`);else z.showError(`Sessao arquivada nao encontrada: "${q}"`);break}case"archived":case"arquivadas":{let q=Z.listArchived();if(q.length===0){z.showSystem("Nenhuma sessao arquivada.");break}let C=q.map((F)=>{let L=Z.getArchivedInfo(F),x=L?eq(L.updated):"",w=L?`${L.messageCount} msgs`:"";return` ${F.padEnd(20)} ${w.padEnd(10)} ${x}`});z.showSystem(`Sessoes arquivadas (${q.length}):
|
|
627
|
+
${C.join(`
|
|
628
|
+
`)}`);break}case"model":case"modelo":{let q=R[0];if(!q){z.showSystem(cY(Q.model)+`
|
|
580
629
|
|
|
581
|
-
`+
|
|
582
|
-
Expires: ${new Date(Y.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{z.showSystem("Renovando sessao Claude...");try{let q=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),
|
|
583
|
-
`));break;case"commit":case"commitar":{if(!await
|
|
584
|
-
`+q),z.disableInput();try{let
|
|
630
|
+
`+uY());break}let{provider:C,model:F}=kZ(q),L=C==="anthropic"?wZ(F):F;if(Q.model=C==="anthropic"?L:`${C}:${L}`,F0(Q),C==="anthropic")$.setModel(L);else z.showSystem(`Note: ${C} provider selected. Restart smolerclaw for full provider switch.`);H.setModel(L),z.updateModel(Q.model),z.showSystem(`Model -> ${Q.model}`);break}case"skills":case"habilidades":{z.showSystem(bY(J));break}case"auth":z.showSystem(`Auth: subscription (${Y.subscriptionType})
|
|
631
|
+
Expires: ${new Date(Y.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{z.showSystem("Renovando sessao Claude...");try{let q=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),C=setTimeout(()=>q.kill(),15000);await q.exited,clearTimeout(C);let F=x5();if(F){if(Y=F,"updateApiKey"in $)$.updateApiKey(F.token);z.showSystem(`Sessao renovada. Expira: ${new Date(F.expiresAt).toLocaleString()}`)}else z.showSystem("claude executado, mas credenciais nao atualizaram. Tente novamente.")}catch(q){z.showError(`Falha ao renovar: ${q instanceof Error?q.message:String(q)}`)}break}case"config":z.showSystem(`Config: ${A5()}`);break;case"export":case"exportar":{let q=new Date().toISOString().split("T")[0],C=R[0]||`smolerclaw-${Z.session.name}-${q}.md`;try{let F=pY(Z.session);aq(C,F),z.showSystem(`Exported to: ${C}`)}catch(F){z.showError(`Export failed: ${F instanceof Error?F.message:F}`)}break}case"cost":case"custo":z.showSystem(`Session: ${H.formatSession()}`);break;case"retry":case"repetir":{let q=[...Z.messages].reverse().find((x)=>x.role==="user");if(!q){z.showError("No previous message to retry.");break}let C=Z.messages,F=0;if(C.length>0&&C[C.length-1].role==="assistant")F++;if(C.length>F&&C[C.length-1-F].role==="user")F++;if(F>0)Z.popMessages(F);z.showSystem("Retrying...");let L=q.images?.length?q.content:q.content;await P(L);break}case"help":case"ajuda":case"?":z.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar Deletar sessao"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma"," /commit /commitar Git commit com IA"," /exit /sair Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias"," /open /abrir Abrir app Windows"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral","","Monitor:"," /monitor /vigiar Monitorar processo (ex: /monitor nginx)"," /monitor stop <nome> Parar monitoramento","","Workflows:"," /workflow /fluxo Listar workflows"," /workflow run <nome> Executar (ex: /workflow iniciar-dia)","","Pomodoro:"," /pomodoro /foco Iniciar (ex: /foco revisar codigo)"," /pomodoro status Ver tempo restante"," /pomodoro stop Parar","","Financas / Finance:"," /entrada <$> <cat> Registrar entrada"," /saida <$> <cat> Registrar saida"," /finance /balanco Resumo mensal","","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(`
|
|
632
|
+
`));break;case"commit":case"commitar":{if(!await nY()){z.showError("Not a git repository.");break}let q=await lY();if(q==="(clean)"){z.showSystem("Nothing to commit \u2014 working tree clean.");break}z.showSystem(`Changes:
|
|
633
|
+
`+q),z.disableInput();try{let F=`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.
|
|
585
634
|
|
|
586
635
|
Diff:
|
|
587
|
-
${(await
|
|
588
|
-
${
|
|
589
|
-
`)}`:`No matches for "${q}".`);break}case"lang":case"language":case"idioma":{let q=
|
|
590
|
-
Falhas: ${
|
|
591
|
-
|
|
592
|
-
|
|
636
|
+
${(await dY()).slice(0,8000)}`;z.startStream();let L="";for await(let w of $.chat([{role:"user",content:F,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(w.type==="text")L+=w.text,z.appendStream(w.text);else if(w.type==="error")z.showError(w.error);if(z.endStream(),L=L.trim().replace(/^["']|["']$/g,""),!L){z.showError("Failed to generate commit message. Aborting.");break}await oY();let x=await aY(L);if(x.ok)z.showSystem(`Committed: ${L}`);else z.showError(`Commit failed: ${x.output}`)}catch(C){z.showError(`Commit error: ${C instanceof Error?C.message:String(C)}`)}z.enableInput();break}case"persona":case"modo":{let q=R[0];if(!q){z.showSystem(sY(B));break}let C=iY(q);if(!C){z.showError(`Unknown persona: ${q}. Try /persona to see options.`);break}if(B=C.name,C.systemPrompt)N=OZ(C.systemPrompt,J,Q.language);else N=X;z.showSystem(`Persona -> ${C.name}: ${C.description}`);break}case"copy":case"copiar":{let q=[...Z.messages].reverse().find((F)=>F.role==="assistant");if(!q){z.showError("No assistant message to copy.");break}if(await tY(q.content))z.showSystem("Copied last response to clipboard.");else z.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let q=R.join(" ");if(!q){z.showError("Usage: /ask <question>");break}z.addUserMessage(`(ephemeral) ${q}`),z.disableInput(),z.startStream();let C="";for await(let F of $.chat([{role:"user",content:q,timestamp:Date.now()}],N,!1))if(F.type==="text")C+=F.text,z.appendStream(F.text);else if(F.type==="error")z.showError(F.error);else if(F.type==="usage")z.showUsage(`${F.inputTokens} in / ${F.outputTokens} out (ephemeral)`);z.endStream(),z.enableInput();break}case"fork":{let q=R[0]||`fork-${Date.now()}`;Z.fork(q),z.updateSession(q),z.showSystem(`Forked session -> ${q} (${Z.messages.length} messages copied)`);break}case"plugins":{z.showSystem(F6(V));break}case"budget":case"orcamento":{let q=R[0];if(!q){let F=Q.maxSessionCost,L=H.totals.costCents;if(F===0)z.showSystem(`Budget: unlimited (spent ~$${(L/100).toFixed(4)})`);else{let x=Math.round(L/F*100);z.showSystem(`Budget: ~$${(L/100).toFixed(4)} / $${(F/100).toFixed(4)} (${x}%)`)}break}let C=Number(q);if(isNaN(C)||C<0){z.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Q.maxSessionCost=C,F0(Q),z.showSystem(C===0?"Budget: unlimited":`Budget set: $${(C/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!x8.peek()){z.showError("Nothing to undo.");break}let C=x8.undo();if(C)z.showSystem(C);break}case"search":case"buscar":{let q=R.join(" ").toLowerCase();if(!q){z.showError("Usage: /search <text>");break}let C=[];for(let F of Z.messages)if(F.content.toLowerCase().includes(q)){let L=F.content.slice(0,100).replace(/\n/g," "),x=new Date(F.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});C.push(` [${F.role} ${x}] ${L}${F.content.length>100?"...":""}`)}z.showSystem(C.length>0?`Found ${C.length} match${C.length>1?"es":""}:
|
|
637
|
+
${C.join(`
|
|
638
|
+
`)}`:`No matches for "${q}".`);break}case"lang":case"language":case"idioma":{let q=R[0];if(!q){z.showSystem(`Language: ${Q.language} (auto = match user's language)`);break}Q.language=q,F0(Q),z.showSystem(`Language -> ${q}`);break}case"briefing":case"resumo":{z.showSystem("Carregando briefing..."),z.disableInput();try{let q=await GJ(Q.dataDir);z.showSystem(q);let C=await W5(Q.dataDir);z.setTimeContext(C),O=C}catch(q){z.showError(`Briefing falhou: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"news":case"noticias":{let q=R[0];if(q)z.showSystem(`Buscando noticias (${q})...`);else z.showSystem("Buscando noticias...");z.disableInput();try{let{items:C,errors:F}=await B9(q?[q]:void 0);if(C.length===0){z.showSystem(F.length>0?`Nenhuma noticia encontrada.
|
|
639
|
+
Falhas: ${F.join(", ")}`:"Nenhuma noticia encontrada."),z.enableInput();break}let L=C.map((w)=>({title:w.title,link:w.link,source:w.source,category:w.category,time:w.pubDate?w.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),x=await z.promptNewsPicker(L);if(x){if(x.action==="open"){let{openUrl:w}=await Promise.resolve().then(() => (d4(),R6));w(x.link),z.showSystem(`Abrindo: ${x.link}`)}else if(x.action==="read"){z.showSystem("Buscando conteudo...");let w=await T6(x.link);if(typeof w==="string")z.showError(w);else{let s=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
|
|
640
|
+
|
|
641
|
+
${`Noticia: ${w.title}
|
|
642
|
+
Fonte: ${x.link}
|
|
643
|
+
|
|
644
|
+
${w.content}`}`;z.enableInput(),P(s);return}}}}catch(C){z.showError(`Falha ao buscar noticias: ${C instanceof Error?C.message:String(C)}`)}z.enableInput();break}case"feeds":case"fontes":{z.showSystem(t0());break}case"addfeed":case"novafonte":{if(R.length<3){z.showError(`Uso: /addfeed <nome> <url> <categoria>
|
|
645
|
+
Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let q=R[0],C=R[1],F=R[2],L=n0(q,C,F);if(typeof L==="string")z.showError(L);else z.showSystem(`Fonte adicionada: ${L.name} (${L.category}) \u2014 ${L.url}`);break}case"rmfeed":case"rmfonte":{let q=R.join(" ");if(!q){z.showError("Uso: /rmfeed <nome ou url>");break}if(r0(q))z.showSystem(`Fonte removida: ${q}`);else z.showError(`Fonte custom nao encontrada: "${q}". Para desativar uma built-in, use /disablefeed.`);break}case"disablefeed":case"desativarfonte":{let q=R.join(" ");if(!q){z.showError("Uso: /disablefeed <nome ou url>");break}if(i0(q))z.showSystem(`Fonte desativada: ${q}`);else z.showError(`Fonte built-in nao encontrada ou ja desativada: "${q}"`);break}case"enablefeed":case"ativarfonte":{let q=R.join(" ");if(!q){z.showError("Uso: /enablefeed <nome ou url>");break}if(s0(q))z.showSystem(`Fonte reativada: ${q}`);else z.showError(`Fonte built-in nao encontrada ou nao esta desativada: "${q}"`);break}case"open":case"abrir":{if(!R.join(" ")){z.showSystem(`Apps disponiveis: ${q9().join(", ")}
|
|
646
|
+
Uso: /open <app> ou /open <app> <arquivo>`);break}let C=R.length>1?R.slice(1).join(" "):void 0,F=await m4(R[0],C);z.showSystem(F);break}case"openfile":case"abrirarquivo":{let q=R.join(" ");if(!q){z.showError("Uso: /openfile <caminho>");break}let C=await A1(q);z.showSystem(C);break}case"openurl":{let q=R[0];if(!q){z.showError("Uso: /openurl <url>");break}let C=await p4(q);z.showSystem(C);break}case"apps":case"programas":{z.disableInput();try{let q=await I1();z.showSystem(q)}catch(q){z.showError(`Apps: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"sysinfo":case"sistema":{z.disableInput();try{let q=await c4();z.showSystem(q)}catch(q){z.showError(`Sysinfo: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{z.disableInput();try{let q=await u4(),C=await h$();z.showSystem(`${q}
|
|
593
647
|
|
|
594
648
|
--- Agenda ---
|
|
595
|
-
${
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
${
|
|
609
|
-
|
|
610
|
-
`).
|
|
611
|
-
`).
|
|
612
|
-
`).
|
|
649
|
+
${C}`)}catch(q){z.showError(`Calendar: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"monitor":case"vigiar":{let q=R[0]?.toLowerCase();if(!q||q==="list"||q==="listar")z.showSystem(vJ());else if(q==="stop"||q==="parar"){let C=R[1];if(!C){z.showError("Uso: /monitor stop <processo>");break}z.showSystem(_J(C))}else{let C=parseInt(R[1])||60;z.showSystem(bJ(q,C))}break}case"workflow":case"fluxo":{let q=R[0]?.toLowerCase();if(!q||q==="list"||q==="listar"){let C=R[1];z.showSystem(SJ(AJ(C)))}else if(q==="run"||q==="rodar"){let C=R[1];if(!C){z.showError("Uso: /workflow run <nome>");break}z.disableInput();try{let F=await mZ(C,(L)=>z.showSystem(L));z.showSystem(F)}catch(F){z.showError(`Workflow: ${F instanceof Error?F.message:String(F)}`)}z.enableInput()}else if(q==="info"||q==="detalhe"){let C=R[1];if(!C){z.showError("Uso: /workflow info <nome>");break}let F=$0(C);if(F)z.showSystem(wJ(F));else z.showError(`Workflow nao encontrado: ${C}`)}else if(q==="delete"||q==="deletar"){let C=R[1];if(!C){z.showError("Uso: /workflow delete <nome>");break}if(IJ(C))z.showSystem(`Workflow removido: ${C}`);else z.showError(`Workflow nao encontrado: ${C}`)}else if(q==="enable"||q==="ativar"){let C=R[1];if(!C){z.showError("Uso: /workflow enable <nome>");break}let F=gZ(C,{enabled:!0});if(F)z.showSystem(`Workflow ativado: ${F.name}`);else z.showError(`Workflow nao encontrado: ${C}`)}else if(q==="disable"||q==="desativar"){let C=R[1];if(!C){z.showError("Uso: /workflow disable <nome>");break}let F=gZ(C,{enabled:!1});if(F)z.showSystem(`Workflow desativado: ${F.name}`);else z.showError(`Workflow nao encontrado: ${C}`)}else{z.disableInput();try{let C=await mZ(q,(F)=>z.showSystem(F));z.showSystem(C)}catch(C){z.showError(`Workflow: ${C instanceof Error?C.message:String(C)}`)}z.enableInput()}break}case"pomodoro":case"foco":{let q=R[0]?.toLowerCase();if(q==="stop"||q==="parar")z.showSystem(OJ());else if(q==="status")z.showSystem(vZ());else if(!q)z.showSystem(vZ());else{let C=R.join(" "),F=25,L=5;z.showSystem(FJ(C,25,5))}break}case"agendar":case"schedule":{let q=R[0]?.toLowerCase();if(!q||q==="list"||q==="listar"){let h=b1(R[1]==="all"||R[1]==="todos");z.showSystem(_1(h));break}if(q==="remove"||q==="remover"||q==="delete"){if(!R[1]){z.showSystem("Uso: /agendar remove <id ou nome>");break}let h=await H7(R[1]);z.showSystem(h?"Agendamento removido.":"Agendamento nao encontrado.");break}if(q==="enable"||q==="ativar"){if(!R[1]){z.showSystem("Uso: /agendar ativar <id ou nome>");break}let h=await q7(R[1]);z.showSystem(h?`Agendamento "${h.name}" ativado.`:"Agendamento nao encontrado.");break}if(q==="disable"||q==="desativar"){if(!R[1]){z.showSystem("Uso: /agendar desativar <id ou nome>");break}let h=await U7(R[1]);z.showSystem(h?`Agendamento "${h.name}" desativado.`:"Agendamento nao encontrado.");break}if(q==="run"||q==="executar"){if(!R[1]){z.showSystem("Uso: /agendar executar <id ou nome>");break}z.showSystem(await W7(R[1]));break}if(q==="clear"||q==="limpar"){z.showSystem(await s6());break}if(q==="detail"||q==="detalhe"||q==="info"){if(!R[1]){z.showSystem("Uso: /agendar info <id ou nome>");break}let h=n6(R[1]);z.showSystem(h?O9(h):"Agendamento nao encontrado.");break}let C=R.join(" "),F=C.match(/"([^"]+)"/g);if(!F||F.length<2){z.showSystem(`Uso: /agendar "<mensagem>" "<horario>" [once|daily|weekly] [data/dia]
|
|
650
|
+
Exemplos:
|
|
651
|
+
/agendar "Reuniao" "14:00"
|
|
652
|
+
/agendar "Standup" "09:00" daily
|
|
653
|
+
/agendar "Review" "15:00" weekly sexta
|
|
654
|
+
/agendar "Dentista" "10:00" once 15/04/2026`);break}let L=F[0].slice(1,-1),x=F[1].slice(1,-1),w=B7(x);if(!w){z.showSystem(`Horario invalido: "${x}". Use formato HH:MM ou HHh.`);break}let u=C.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),s="once",w$;for(let h of u){let k$=h.toLowerCase();if(k$==="daily"||k$==="diario")s="daily";else if(k$==="weekly"||k$==="semanal")s="weekly";else if(k$==="once"||k$==="uma-vez")s="once";else if(s==="weekly"){let p$=N7(h);if(p$)w$=p$}else if(s==="once"){let p$=C7(h);if(p$)w$=p$}}if(s==="once"&&!w$){let h=new Date,[k$,p$]=w.split(":").map(Number),c$=new Date(h);if(c$.setHours(k$,p$,0,0),c$<=h)c$.setDate(c$.getDate()+1);w$=[String(c$.getMonth()+1).padStart(2,"0"),String(c$.getDate()).padStart(2,"0"),String(c$.getFullYear())].join("/")}try{let h=await G7(L,s,w,"toast",L,w$);z.showSystem(`Tarefa "${h.name}" agendada para ${O9(h).split(`
|
|
655
|
+
`).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(h){z.showError(`Erro ao agendar: ${h instanceof Error?h.message:String(h)}`)}break}case"agendamentos":case"schedules":{let q=b1(R[0]==="all"||R[0]==="todos");z.showSystem(_1(q));break}case"entrada":case"income":{let q=parseFloat(R[0]);if(isNaN(q)||R.length<3){z.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let C=v1("entrada",q,R[1],R.slice(2).join(" "));z.showSystem(`+ R$ ${C.amount.toFixed(2)} (${C.category}) \u2014 ${C.description}`);break}case"saida":case"expense":{let q=parseFloat(R[0]);if(isNaN(q)||R.length<3){z.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let C=v1("saida",q,R[1],R.slice(2).join(" "));z.showSystem(`- R$ ${C.amount.toFixed(2)} (${C.category}) \u2014 ${C.description}`);break}case"finance":case"financas":case"balanco":{let q=R[0];if(q==="recent"||q==="recentes")z.showSystem(E9());else z.showSystem(F7()+`
|
|
656
|
+
|
|
657
|
+
`+E9(5));break}case"decisions":case"decisoes":{let q=R.join(" ");if(q){let C=a4(q);z.showSystem(F8(C))}else z.showSystem(F8(O7()));break}case"investigar":case"investigate":case"investigacoes":{let q=R.join(" ");if(q){let{searchInvestigations:C,formatInvestigationList:F}=await Promise.resolve().then(() => (h1(),y9));z.showSystem(F(C(q)))}else{let{listInvestigations:C,formatInvestigationList:F}=await Promise.resolve().then(() => (h1(),y9));z.showSystem(F(C()))}break}case"email":case"rascunho":{if(!R.join(" ")){z.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
|
|
658
|
+
Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let C=R[0],F=R.slice(1).join(" "),L=F.indexOf("|");if(L===-1){z.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
|
|
659
|
+
Use | para separar assunto do corpo.`);break}let x=F.slice(0,L).trim(),w=F.slice(L+1).trim();if(!x||!w){z.showError("Assunto e corpo sao obrigatorios.");break}let u={to:C,subject:x,body:w};z.showSystem(X7(u)),z.disableInput();try{let s=await J7(u);z.showSystem(s)}catch(s){z.showError(`Email: ${s instanceof Error?s.message:String(s)}`)}z.enableInput();break}case"memo":case"anotar":case"note":{let q=R.join(" ");if(!q){let L=y1();z.showSystem(o4(L));break}let C=Q7(q),F=C.tags.length>0?` [${C.tags.map((L)=>"#"+L).join(" ")}]`:"";z.showSystem(`Memo salvo${F} {${C.id}}`);break}case"memos":case"notas":{let q=R.join(" ");if(q){let C=Y7(q);z.showSystem(o4(C))}else{let C=y1();z.showSystem(o4(C))}break}case"memotags":case"tags":{z.showSystem(p6());break}case"rmmemo":case"rmnota":{let q=R[0];if(!q){z.showError("Uso: /rmmemo <id>");break}if(m6(q))z.showSystem("Memo removido.");else z.showError(`Memo nao encontrado: ${q}`);break}case"material":case"mat":{let q=R.join(" ");if(!q){let u=E8(10);z.showSystem(D4(u));break}if(/^[a-z0-9]{6}$/.test(q)){let u=A3(q);if(u)z.showSystem(S3(u));else z.showError(`Material nao encontrado: ${q}`);break}let C=q.indexOf("|");if(C===-1){z.showSystem(`Uso: /material <titulo> | <conteudo>
|
|
660
|
+
Ou peca a IA: "salva esse material sobre..."`);break}let F=q.slice(0,C).trim(),L=q.slice(C+1).trim();if(!F||!L){z.showError("Titulo e conteudo sao obrigatorios.");break}let x=S7(F,L),w=x.tags.length>0?` [${x.tags.map((u)=>"#"+u).join(" ")}]`:"";z.showSystem(`Material salvo: "${x.title}" (${x.category})${w} {${x.id}}`);break}case"materials":case"materiais":{let q=R.join(" ");if(q){let C=R8(q);z.showSystem(D4(C))}else{let C=E8();z.showSystem(D4(C))}break}case"matcats":case"categorias":{z.showSystem(w3());break}case"rmmat":case"rmmaterial":{let q=R[0];if(!q){z.showError("Uso: /rmmat <id>");break}if(w7(q))z.showSystem("Material removido.");else z.showError(`Material nao encontrado: ${q}`);break}case"reflect":case"reflexao":case"aprender":{z.showSystem("Executando reflexao de uso..."),z.disableInput();try{let q=await d1();z.showSystem(q.summary)}catch(q){z.showError(`Reflexao falhou: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"indexar":case"index":case"reindex":{z.showSystem("Indexando memoria local...");let q=v7();z.showSystem(`Indexacao concluida: ${q.indexed} fonte(s) indexada(s), ${q.skipped} sem alteracao. Total: ${q.total} chunks.`);break}case"memoria":case"memory":{let q=R.join(" ");if(q){let C=f7(q);z.showSystem(h7(C))}else{let C=_7(),F=C.builtAt?new Date(C.builtAt).toLocaleString("pt-BR"):"nunca";z.showSystem(`Memory RAG Index:
|
|
661
|
+
Chunks: ${C.chunks}
|
|
662
|
+
Fontes: ${C.sources}
|
|
663
|
+
Ultima indexacao: ${F}`)}break}case"vault":{let q=R[0]?.toLowerCase();if(!q||q==="status")z.showSystem(W0(U0()));else if(q==="backup"){z.showSystem("Realizando backup...");let C=R.slice(1).join(" ")||void 0,F=await Y8(C);z.showSystem(F)}else if(q==="sync"||q==="push"){z.showSystem("Sincronizando com remote...");let C=await C0();z.showSystem(C)}else if(q==="init"){let C=await B0();z.showSystem(C),B2(30),z.showSystem("Auto-backup ativado (a cada 30 minutos).")}else z.showError("Uso: /vault [status|backup|sync|init]");break}case"backup":{z.showSystem("Realizando backup...");let q=await Y8();z.showSystem(q);break}case"clipboard":case"area":{z.showSystem("Lendo clipboard...");let q=await g7();switch(q.type){case"text":z.showSystem(`Clipboard (texto):
|
|
664
|
+
${q.text}`);break;case"image":z.showSystem(q.text);break;case"empty":z.showSystem("Clipboard vazio.");break;case"error":z.showError(q.text);break}break}case"tela":case"screen":{z.showSystem("Analisando tela...");let q=await m7();z.showSystem(q);break}case"ps1":{let q=R.join(" ");if(!q.trim()){z.showError("Uso: /ps1 <script powershell>");break}z.showSystem("Executando script...");let C=await m1(q),F=[];if(C.stdout.trim())F.push(C.stdout.trim());if(C.stderr.trim())F.push(`stderr: ${C.stderr.trim()}`);F.push(`(exit: ${C.exitCode}, ${C.duration}ms)`),z.showSystem(F.join(`
|
|
665
|
+
`));break}case"projeto":case"project":{let q=R.join(" ");if(q){let C=u7(q);if(C)P8(C.id),z.showSystem(r7(C));else if(q==="auto"){let F=t7(process.cwd());if(F)P8(F.id),z.showSystem(`Projeto detectado: ${r7(F)}`);else z.showError("Nenhum projeto detectado no diretorio atual.")}else z.showError(`Projeto nao encontrado: "${q}"`)}else{let C=T4();if(C)z.showSystem(r7(C));else z.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{z.showSystem(n7(D8()));break}case"sessao":case"session":{let q=R[0],C=T4();if(!C){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(q==="start"||q==="iniciar"){let F=R.slice(1).join(" "),L=d7(C.id,F);if(L)z.showSystem(`Sessao iniciada para "${C.name}" [${L.id}]`)}else if(q==="stop"||q==="parar"){let F=A4(C.id);if(F){let L=l7(F.id,R.slice(1).join(" "));if(L)z.showSystem(`Sessao encerrada: ${L.durationMinutes} minutos em "${C.name}"`)}else z.showSystem("Nenhuma sessao aberta.")}else{let F=A4(C.id);if(F){let L=Math.round((Date.now()-new Date(F.startedAt).getTime())/60000);z.showSystem(`Sessao aberta: ${L} minutos em "${C.name}"`)}else z.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let q=T4();if(!q){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let C=R[0]||"today";z.showSystem("Gerando relatorio...");let F=await a7(q.id,C,"pt");if(F)z.showSystem(F.markdown);else z.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let q=R[0]||void 0,C=o7(q);z.showSystem(i7(C));break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let C={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[a]||R[0],F=D7(C);z.showSystem(T7(F));break}case"person":case"pessoa":{let q=R.join(" ");if(!q){z.showError("Uso: /person <nome>");break}let C=$4(q);if(!C){z.showError(`Pessoa nao encontrada: "${q}"`);break}z.showSystem(A7(C));break}case"addperson":case"addpessoa":case"novapessoa":{let q=R[0];if(!q||!["equipe","familia","contato"].includes(q)){z.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
|
|
666
|
+
Ex: /addperson equipe Joao dev frontend`);break}let F=R.slice(1).join(" ");if(!F){z.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[L,...x]=F.split(","),w=x.join(",").trim()||void 0,u=j7(L.trim(),q,w);z.showSystem(`Adicionado: ${u.name} (${q}) [${u.id}]`);break}case"delegate":case"delegar":{let q=R[0];if(!q||R.length<2){z.showSystem(`Uso: /delegate <pessoa> <tarefa>
|
|
667
|
+
Ex: /delegate Joao revisar relatorio`);break}let C=R.slice(1).join(" "),F=P7(q,C);if(!F){z.showError(`Pessoa nao encontrada: "${q}"`);break}z.showSystem(`Delegado para ${q}: "${C}" [${F.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let q=R[0],C=n4(q);z.showSystem(I7(C));break}case"followups":{let q=O8();z.showSystem(x7(q));break}case"dashboard":case"painel":{let q=await hJ();z.enterDashboardMode(q),process.stdin.once("data",()=>{if(z.getViewMode()==="dashboard")z.enterChatMode()});break}case"chat":{z.enterChatMode();break}case"task":case"tarefa":{let q=R.join(" ");if(!q){let w=e$();z.showSystem(l4(w));break}let C=k1(q),F=q.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(!F)F=q;let L=$7(F,C||void 0),x=C?` \u2014 lembrete: ${C.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";z.showSystem(`Tarefa criada: "${L.title}"${x} [${L.id}]`);break}case"tasks":case"tarefas":{let q=R[0]==="all"||R[0]==="todas",C=e$(q);z.showSystem(l4(C));break}case"done":case"feito":case"concluido":{let q=R.join(" ");if(!q){z.showError("Uso: /done <id ou parte do titulo>");break}let C=Z7(q);if(C)z.showSystem(`Concluida: "${C.title}"`);else z.showError(`Tarefa nao encontrada: "${q}"`);break}case"rmtask":case"rmtarefa":{let q=R.join(" ");if(!q){z.showError("Uso: /rmtask <id ou parte do titulo>");break}if(y6(q))z.showSystem("Tarefa removida.");else z.showError(`Tarefa nao encontrada: "${q}"`);break}default:z.showError(`Unknown command: /${a}. Try /help`)}}function q$(){Z.saveLastSession(),k6(),LJ(),fJ(),i6(),P5(),d1().catch(()=>{}),z.stop(),process.exit(0)}process.on("SIGINT",q$),process.on("SIGTERM",q$),z.start({onSubmit:P,onCancel:()=>{j?.abort(),z.endStream(),z.showSystem("Cancelled."),z.enableInput()},onExit:q$});let $$=`Authenticated via Claude ${Y.subscriptionType} subscription.`;if(z.showSystem(`smolerclaw v${Y0()} \u2014 the micro AI assistant.
|
|
668
|
+
${$$}
|
|
669
|
+
Type /ajuda for commands.`),UJ(Q.dataDir))try{let y=await hJ();if(y.panels.length>0){z.enterDashboardMode(y);let v=()=>{z.enterChatMode(),z.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",v)};setTimeout(()=>{if(z.getViewMode()==="dashboard")z.enterChatMode()},30000),process.stdin.once("data",()=>{if(z.getViewMode()==="dashboard")z.enterChatMode()})}else{let v=await BJ();z.showSystem(v)}WJ()}catch{}if(G)await P(G)}async function hJ(){let $=[],Z=new Date().getHours(),Q=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE",Y=new Date().toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),J=e$(),X=J.filter((z)=>{if(!z.dueAt)return!0;let B=new Date(z.dueAt),W=new Date;return B.toDateString()===W.toDateString()});if(X.length>0||J.length>0){let z=X.slice(0,8).map((B)=>{let W=B.dueAt?new Date(B.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${W?`[${W}] `:""}${B.title}`});if(J.length>X.length)z.push(`... +${J.length-X.length} outras`);$.push({id:"tasks",title:`${Q}! Tarefas (${X.length})`,content:z.length>0?z:["Nenhuma tarefa para hoje"]})}let K=O8();if(K.length>0){let z=K.slice(0,6).map((B)=>{let W=B.person.name||"Alguem",N=B.interaction.summary||"Follow-up pendente";return`${W}: ${N.slice(0,30)}...`});$.push({id:"followups",title:`Follow-ups (${K.length})`,content:z})}let G=n4().filter((z)=>z.status==="atrasado");if(G.length>0){let z=G.slice(0,5).map((B)=>{return`${$4(B.personId)?.name||"Alguem"}: ${B.task.slice(0,25)}...`});$.push({id:"delegations",title:`Atrasados (${G.length})`,content:z})}try{let B=(await h$()).split(`
|
|
670
|
+
`).filter((W)=>W.trim()).slice(0,6);if(B.length>0)$.push({id:"calendar",title:"Agenda",content:B})}catch{}let H=s7();if(H){let z=H.split(`
|
|
671
|
+
`).filter((B)=>B.trim()).slice(0,5);$.push({id:"project",title:"Projetos",content:z})}try{let B=(await E4(["finance","business","tech"],2)).split(`
|
|
672
|
+
`).filter((W)=>W.trim()).slice(0,6);if(B.length>0)$.push({id:"news",title:"Noticias",content:B})}catch{}if($.length===0)$.push({id:"greeting",title:Q,content:[Y,"","Nenhuma tarefa ou evento pendente.","Use /ajuda para ver comandos dispon\xEDveis."]});return{panels:$,columns:Math.min(2,$.length),gap:1}}function eq($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let Q=Math.floor(Z/60000);if(Q<1)return"just now";if(Q<60)return`${Q}m ago`;let Y=Math.floor(Q/60);if(Y<24)return`${Y}h ago`;let J=Math.floor(Y/24);if(J>365)return`${Math.floor(J/365)}y ago`;return`${J}d ago`}rq().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
|